title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java lang.Integer.toBinaryString() method
05 Dec, 2018 The java.lang.Integer.toBinaryString() method returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string. Syntax: public static String toBinaryString(int num) Parameter : The function accepts a single mandatory parameter num num - This parameter specifies the number to be converted to binary string. It is of int data-type Return Value: This function returns the string representation of the unsigned Integer value represented by the argument in binary (base 2).Examples: Input : 10 Output : 1010 Input : 9 Output : 1001 // Java program to demonstrate// java.lang.Integer.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { int l = 10; // returns the string representation of the unsigned int value // represented by the argument in binary (base 2) System.out.println("Binary is " + Integer.toBinaryString(l)); l = 9; System.out.println("Binary is " + Integer.toBinaryString(l)); }} Output: Binary is 1010 Binary is 1001 Java-Functions Java-Integer Java-lang package java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Dec, 2018" }, { "code": null, "e": 274, "s": 53, "text": "The java.lang.Integer.toBinaryString() method returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string." }, { "code": null, "e": 282, "s": 274, "text": "Syntax:" }, { "code": null, "e": 496, "s": 282, "text": "public static String toBinaryString(int num)\n\nParameter : The function accepts a single mandatory parameter num \nnum - This parameter specifies the number to be converted to binary string. \nIt is of int data-type " }, { "code": null, "e": 645, "s": 496, "text": "Return Value: This function returns the string representation of the unsigned Integer value represented by the argument in binary (base 2).Examples:" }, { "code": null, "e": 699, "s": 645, "text": "Input : 10 \nOutput : 1010 \n\nInput : 9\nOutput : 1001 \n" }, { "code": "// Java program to demonstrate// java.lang.Integer.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { int l = 10; // returns the string representation of the unsigned int value // represented by the argument in binary (base 2) System.out.println(\"Binary is \" + Integer.toBinaryString(l)); l = 9; System.out.println(\"Binary is \" + Integer.toBinaryString(l)); }}", "e": 1185, "s": 699, "text": null }, { "code": null, "e": 1193, "s": 1185, "text": "Output:" }, { "code": null, "e": 1224, "s": 1193, "text": "Binary is 1010\nBinary is 1001\n" }, { "code": null, "e": 1239, "s": 1224, "text": "Java-Functions" }, { "code": null, "e": 1252, "s": 1239, "text": "Java-Integer" }, { "code": null, "e": 1270, "s": 1252, "text": "Java-lang package" }, { "code": null, "e": 1280, "s": 1270, "text": "java-math" }, { "code": null, "e": 1285, "s": 1280, "text": "Java" }, { "code": null, "e": 1290, "s": 1285, "text": "Java" } ]
Smallest Pair Sum in an array
11 Aug, 2021 Given an array of distinct integers arr[], the task is to find a pair which has the minimum sum and print the sum.Examples: Input: arr[] = {1, 2, 3} Output: 3 The pair (1, 2) will have the minimum sum pair i.e. 1 + 2 = 3Input: arr[] = {3, 5, 6, 2} Output: 5 Approach: Find the minimum element from the array and store it in min. Find the second minimum element from the array and store it in secondMin. Print min + secondMin. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to print the sum of the minimum pair#include <bits/stdc++.h>using namespace std; // Function to return the sum of// the minimum pair from the arrayint smallest_pair(int a[], int n){ int min = INT_MAX, secondMin = INT_MAX; for (int j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min);} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << smallest_pair(arr, n); return 0;} // Java program to print the sum// of the minimum pairimport java .io.*; class GFG{// Function to return the sum of// the minimum pair from the arraystatic int smallest_pair(int[] a, int n){ int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE; for (int j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min);} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 2, 3 }; int n = arr.length; System.out.println(smallest_pair(arr, n));}} // This code is contributed// by inder_verma # Python3 program to print the# sum of the minimum pairimport sys # Function to return the sum of# the minimum pair from the arraydef smallest_pair(a, n) : min = sys.maxsize secondMin = sys.maxsize for j in range(n) : # If found new minimum if (a[j] < min) : # Minimum now becomes # second minimum secondMin = min # Update minimum min = a[j] # If current element is > min # and < secondMin elif ((a[j] < secondMin) and a[j] != min) : # Update secondMin secondMin = a[j] # Return the sum of the minimum pair return (secondMin + min) # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 3 ] n = len(arr) print(smallest_pair(arr, n)) # This code is contributed by Ryuga // C# program to print the sum// of the minimum pairusing System; class GFG{// Function to return the sum of// the minimum pair from the arraystatic int smallest_pair(int[] a, int n){ int min = int.MaxValue, secondMin = int.MaxValue; for (int j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min);} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3 }; int n = arr.Length; Console.Write(smallest_pair(arr, n));}} // This code is contributed// by Akanksha Rai <?php// PHP program to print the sum// of the minimum pair // Function to return the sum of// the minimum pair from the arrayfunction smallest_pair($a, $n){ $min = PHP_INT_MAX; $secondMin = PHP_INT_MAX; for ($j = 0; $j < $n; $j++) { // If found new minimum if ($a[$j] < $min) { // Minimum now becomes // second minimum $secondMin = $min; // Update minimum $min = $a[$j]; } // If current element is > min // and < secondMin else if (($a[$j] < $secondMin) && $a[$j] != $min) // Update secondMin $secondMin = $a[$j]; } // Return the sum of the minimum pair return ($secondMin + $min);} // Driver code$arr = array( 1, 2, 3 );$n = sizeof($arr);echo smallest_pair($arr, $n); // This code is contributed by ajit?> <script> // Javascript program to print the sum // of the minimum pair // Function to return the sum of // the minimum pair from the array function smallest_pair(a, n) { let min = Number.MAX_VALUE, secondMin = Number.MAX_VALUE; for (let j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min // and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min); } let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(smallest_pair(arr, n)); </script> 3 Time Complexity: ON) Auxiliary Space: O(1) jit_t Akanksha_Rai inderDuMCA ankthon mukesh07 pankajsharmagfg Algorithms Arrays C++ Programs Competitive Programming Searching Arrays Searching Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph CPU Scheduling in Operating Systems Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Arrays in C/C++ Program for array rotation
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Aug, 2021" }, { "code": null, "e": 179, "s": 53, "text": "Given an array of distinct integers arr[], the task is to find a pair which has the minimum sum and print the sum.Examples: " }, { "code": null, "e": 315, "s": 179, "text": "Input: arr[] = {1, 2, 3} Output: 3 The pair (1, 2) will have the minimum sum pair i.e. 1 + 2 = 3Input: arr[] = {3, 5, 6, 2} Output: 5 " }, { "code": null, "e": 329, "s": 317, "text": "Approach: " }, { "code": null, "e": 390, "s": 329, "text": "Find the minimum element from the array and store it in min." }, { "code": null, "e": 464, "s": 390, "text": "Find the second minimum element from the array and store it in secondMin." }, { "code": null, "e": 487, "s": 464, "text": "Print min + secondMin." }, { "code": null, "e": 539, "s": 487, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 543, "s": 539, "text": "C++" }, { "code": null, "e": 548, "s": 543, "text": "Java" }, { "code": null, "e": 556, "s": 548, "text": "Python3" }, { "code": null, "e": 559, "s": 556, "text": "C#" }, { "code": null, "e": 563, "s": 559, "text": "PHP" }, { "code": null, "e": 574, "s": 563, "text": "Javascript" }, { "code": "// C++ program to print the sum of the minimum pair#include <bits/stdc++.h>using namespace std; // Function to return the sum of// the minimum pair from the arrayint smallest_pair(int a[], int n){ int min = INT_MAX, secondMin = INT_MAX; for (int j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min);} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << smallest_pair(arr, n); return 0;}", "e": 1433, "s": 574, "text": null }, { "code": "// Java program to print the sum// of the minimum pairimport java .io.*; class GFG{// Function to return the sum of// the minimum pair from the arraystatic int smallest_pair(int[] a, int n){ int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE; for (int j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min);} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 2, 3 }; int n = arr.length; System.out.println(smallest_pair(arr, n));}} // This code is contributed// by inder_verma", "e": 2372, "s": 1433, "text": null }, { "code": "# Python3 program to print the# sum of the minimum pairimport sys # Function to return the sum of# the minimum pair from the arraydef smallest_pair(a, n) : min = sys.maxsize secondMin = sys.maxsize for j in range(n) : # If found new minimum if (a[j] < min) : # Minimum now becomes # second minimum secondMin = min # Update minimum min = a[j] # If current element is > min # and < secondMin elif ((a[j] < secondMin) and a[j] != min) : # Update secondMin secondMin = a[j] # Return the sum of the minimum pair return (secondMin + min) # Driver codeif __name__ == \"__main__\" : arr = [ 1, 2, 3 ] n = len(arr) print(smallest_pair(arr, n)) # This code is contributed by Ryuga", "e": 3221, "s": 2372, "text": null }, { "code": "// C# program to print the sum// of the minimum pairusing System; class GFG{// Function to return the sum of// the minimum pair from the arraystatic int smallest_pair(int[] a, int n){ int min = int.MaxValue, secondMin = int.MaxValue; for (int j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min);} // Driver codepublic static void Main(){ int[] arr = { 1, 2, 3 }; int n = arr.Length; Console.Write(smallest_pair(arr, n));}} // This code is contributed// by Akanksha Rai", "e": 4124, "s": 3221, "text": null }, { "code": "<?php// PHP program to print the sum// of the minimum pair // Function to return the sum of// the minimum pair from the arrayfunction smallest_pair($a, $n){ $min = PHP_INT_MAX; $secondMin = PHP_INT_MAX; for ($j = 0; $j < $n; $j++) { // If found new minimum if ($a[$j] < $min) { // Minimum now becomes // second minimum $secondMin = $min; // Update minimum $min = $a[$j]; } // If current element is > min // and < secondMin else if (($a[$j] < $secondMin) && $a[$j] != $min) // Update secondMin $secondMin = $a[$j]; } // Return the sum of the minimum pair return ($secondMin + $min);} // Driver code$arr = array( 1, 2, 3 );$n = sizeof($arr);echo smallest_pair($arr, $n); // This code is contributed by ajit?>", "e": 5001, "s": 4124, "text": null }, { "code": "<script> // Javascript program to print the sum // of the minimum pair // Function to return the sum of // the minimum pair from the array function smallest_pair(a, n) { let min = Number.MAX_VALUE, secondMin = Number.MAX_VALUE; for (let j = 0; j < n; j++) { // If found new minimum if (a[j] < min) { // Minimum now becomes second minimum secondMin = min; // Update minimum min = a[j]; } // If current element is > min // and < secondMin else if ((a[j] < secondMin) && a[j] != min) // Update secondMin secondMin = a[j]; } // Return the sum of the minimum pair return (secondMin + min); } let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(smallest_pair(arr, n)); </script>", "e": 5971, "s": 5001, "text": null }, { "code": null, "e": 5973, "s": 5971, "text": "3" }, { "code": null, "e": 6019, "s": 5975, "text": "Time Complexity: ON) Auxiliary Space: O(1) " }, { "code": null, "e": 6025, "s": 6019, "text": "jit_t" }, { "code": null, "e": 6038, "s": 6025, "text": "Akanksha_Rai" }, { "code": null, "e": 6049, "s": 6038, "text": "inderDuMCA" }, { "code": null, "e": 6057, "s": 6049, "text": "ankthon" }, { "code": null, "e": 6066, "s": 6057, "text": "mukesh07" }, { "code": null, "e": 6082, "s": 6066, "text": "pankajsharmagfg" }, { "code": null, "e": 6093, "s": 6082, "text": "Algorithms" }, { "code": null, "e": 6100, "s": 6093, "text": "Arrays" }, { "code": null, "e": 6113, "s": 6100, "text": "C++ Programs" }, { "code": null, "e": 6137, "s": 6113, "text": "Competitive Programming" }, { "code": null, "e": 6147, "s": 6137, "text": "Searching" }, { "code": null, "e": 6154, "s": 6147, "text": "Arrays" }, { "code": null, "e": 6164, "s": 6154, "text": "Searching" }, { "code": null, "e": 6175, "s": 6164, "text": "Algorithms" }, { "code": null, "e": 6273, "s": 6175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6298, "s": 6273, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 6347, "s": 6298, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 6385, "s": 6347, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6453, "s": 6385, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 6489, "s": 6453, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 6504, "s": 6489, "text": "Arrays in Java" }, { "code": null, "e": 6550, "s": 6504, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6618, "s": 6550, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6634, "s": 6618, "text": "Arrays in C/C++" } ]
Express a number as sum of consecutive numbers
04 Oct, 2021 Given a number N, write a function to express N as sum of two or more consecutive positive numbers. If there is no solution, output -1. If there are multiple solution, then print one of them.Examples: Input : N = 10 Output : 4 + 3 + 2 + 1 Input : N = 8 Output : -1 Input : N = 24 Output : 9 + 8 + 7 Sum of first n natural numbers = n * (n + 1)/2 Sum of first (n + k) numbers = (n + k) * (n + k + 1)/2 If N is sum of k consecutive numbers, then following must be true. N = [(n+k)(n+k+1) - n(n+1)] / 2 OR 2 * N = [(n+k)(n+k+1) - n(n+1)] Below is the implementation based on above idea. C++ Java Python3 C# PHP Javascript // C++ program to print a consecutive sequence// to express N if possible.#include <bits/stdc++.h>using namespace std; // Print consecutive numbers from// last to firstvoid printConsecutive(int last, int first){ cout << first++; for (int x = first; x<= last; x++) cout << " + " << x;} void findConsecutive(int N){ for (int last=1; last<N; last++) { for (int first=0; first<last; first++) { if (2*N == (last-first)*(last+first+1)) { cout << N << " = "; printConsecutive(last, first+1); return; } } } cout << "-1";} // Driver codeint main(){ int n = 12; findConsecutive(n); return 0;} // Java program to print a consecutive sequence// to express N if possible.import java.util.*;class GFG{ // Print consecutive numbers from// last to firststatic void printConsecutive(int last, int first){ System.out.print(first++); for (int x = first; x<= last; x++) System.out.print(" + " + x);} static void findConsecutive(int N){ for (int last = 1; last < N; last++) { for (int first = 0; first < last; first++) { if (2*N == (last-first)*(last+first+1)) { System.out.print(N+ " = "); printConsecutive(last, first+1); return; } } } System.out.print("-1");} // Driver codepublic static void main(String[] args){ int n = 12; findConsecutive(n);}} // This code is contributed by umadevi9616 # Python3 program to print a consecutive# sequence to express N if possible. # Print consecutive numbers# from last to firstdef printConsecutive(last, first): print (first, end = "") first += 1 for x in range(first, last + 1): print (" +", x, end = "") def findConsecutive(N): for last in range(1, N): for first in range(0, last): if 2 * N == (last - first) * (last + first + 1): print (N, "= ", end = "") printConsecutive(last, first + 1) return print ("-1") # Driver coden = 12findConsecutive(n) # This code is contributed by Shreyanshi Arun. // C# program to print a consecutive sequence// to express N if possible.using System; class GfG{ // Print consecutive numbers from // last to first static void printConsecutive(int last, int first) { Console.Write(first++); for (int x = first; x <= last; x++) Console.Write(" + "+x); } static void findConsecutive(int N) { for (int last = 1; last < N; last++) { for (int first = 0; first < last; first++) { if (2 * N == (last - first) * (last + first + 1)) { Console.Write(N + " = "); printConsecutive(last, first + 1); return; } } } Console.Write("-1"); } // Driver code public static void Main () { int n = 12; findConsecutive(n); }} // This code is contributed by vt_m <?php// PHP program to print a consecutive// sequence to express N if possible. // Print consecutive numbers from// last to firstfunction printConsecutive($last, $first){ echo $first++; for ($x = $first; $x<= $last; $x++) echo " + " , $x;} function findConsecutive($N){ for ($last = 1; $last < $N; $last++) { for ($first = 0; $first < $last; $first++) { if (2 * $N == ($last - $first) * ($last + $first + 1)) { echo $N , " = "; printConsecutive($last, $first + 1); return; } } } echo "-1";} // Driver Code $n = 12; findConsecutive($n); // This code is contributed by nitin mittal?> <script> // Javascript program to print a consecutive// sequence to express N if possible. // Print consecutive numbers from// last to firstfunction printConsecutive(last, first){ document.write(first++); for (let x = first; x<= last; x++) document.write( " + " + x);} function findConsecutive(N){ for (let last = 1; last < N; last++) { for (let first = 0; first < last; first++) { if (2 * N == (last - first) * (last + first + 1)) { document.write(N + " = "); printConsecutive(last, first + 1); return; } } } document.write("-1");} // Driver Code let n = 12; findConsecutive(n); // This code is contributed by _saurabh_jaiswal</script> Output: 12 = 3 + 4 + 5 Reference : https://math.stackexchange.com/questions/139842/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbersThis article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal _saurabh_jaiswal umadevi9616 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Oct, 2021" }, { "code": null, "e": 255, "s": 52, "text": "Given a number N, write a function to express N as sum of two or more consecutive positive numbers. If there is no solution, output -1. If there are multiple solution, then print one of them.Examples: " }, { "code": null, "e": 357, "s": 255, "text": "Input : N = 10\nOutput : 4 + 3 + 2 + 1\n\nInput : N = 8\nOutput : -1\n\nInput : N = 24\nOutput : 9 + 8 + 7" }, { "code": null, "e": 603, "s": 361, "text": "Sum of first n natural numbers = n * (n + 1)/2\n\nSum of first (n + k) numbers = (n + k) * (n + k + 1)/2\n\nIf N is sum of k consecutive numbers, then\nfollowing must be true.\n\nN = [(n+k)(n+k+1) - n(n+1)] / 2\n\nOR \n\n2 * N = [(n+k)(n+k+1) - n(n+1)]" }, { "code": null, "e": 653, "s": 603, "text": "Below is the implementation based on above idea. " }, { "code": null, "e": 657, "s": 653, "text": "C++" }, { "code": null, "e": 662, "s": 657, "text": "Java" }, { "code": null, "e": 670, "s": 662, "text": "Python3" }, { "code": null, "e": 673, "s": 670, "text": "C#" }, { "code": null, "e": 677, "s": 673, "text": "PHP" }, { "code": null, "e": 688, "s": 677, "text": "Javascript" }, { "code": "// C++ program to print a consecutive sequence// to express N if possible.#include <bits/stdc++.h>using namespace std; // Print consecutive numbers from// last to firstvoid printConsecutive(int last, int first){ cout << first++; for (int x = first; x<= last; x++) cout << \" + \" << x;} void findConsecutive(int N){ for (int last=1; last<N; last++) { for (int first=0; first<last; first++) { if (2*N == (last-first)*(last+first+1)) { cout << N << \" = \"; printConsecutive(last, first+1); return; } } } cout << \"-1\";} // Driver codeint main(){ int n = 12; findConsecutive(n); return 0;}", "e": 1404, "s": 688, "text": null }, { "code": "// Java program to print a consecutive sequence// to express N if possible.import java.util.*;class GFG{ // Print consecutive numbers from// last to firststatic void printConsecutive(int last, int first){ System.out.print(first++); for (int x = first; x<= last; x++) System.out.print(\" + \" + x);} static void findConsecutive(int N){ for (int last = 1; last < N; last++) { for (int first = 0; first < last; first++) { if (2*N == (last-first)*(last+first+1)) { System.out.print(N+ \" = \"); printConsecutive(last, first+1); return; } } } System.out.print(\"-1\");} // Driver codepublic static void main(String[] args){ int n = 12; findConsecutive(n);}} // This code is contributed by umadevi9616", "e": 2225, "s": 1404, "text": null }, { "code": "# Python3 program to print a consecutive# sequence to express N if possible. # Print consecutive numbers# from last to firstdef printConsecutive(last, first): print (first, end = \"\") first += 1 for x in range(first, last + 1): print (\" +\", x, end = \"\") def findConsecutive(N): for last in range(1, N): for first in range(0, last): if 2 * N == (last - first) * (last + first + 1): print (N, \"= \", end = \"\") printConsecutive(last, first + 1) return print (\"-1\") # Driver coden = 12findConsecutive(n) # This code is contributed by Shreyanshi Arun.", "e": 2877, "s": 2225, "text": null }, { "code": "// C# program to print a consecutive sequence// to express N if possible.using System; class GfG{ // Print consecutive numbers from // last to first static void printConsecutive(int last, int first) { Console.Write(first++); for (int x = first; x <= last; x++) Console.Write(\" + \"+x); } static void findConsecutive(int N) { for (int last = 1; last < N; last++) { for (int first = 0; first < last; first++) { if (2 * N == (last - first) * (last + first + 1)) { Console.Write(N + \" = \"); printConsecutive(last, first + 1); return; } } } Console.Write(\"-1\"); } // Driver code public static void Main () { int n = 12; findConsecutive(n); }} // This code is contributed by vt_m", "e": 3817, "s": 2877, "text": null }, { "code": "<?php// PHP program to print a consecutive// sequence to express N if possible. // Print consecutive numbers from// last to firstfunction printConsecutive($last, $first){ echo $first++; for ($x = $first; $x<= $last; $x++) echo \" + \" , $x;} function findConsecutive($N){ for ($last = 1; $last < $N; $last++) { for ($first = 0; $first < $last; $first++) { if (2 * $N == ($last - $first) * ($last + $first + 1)) { echo $N , \" = \"; printConsecutive($last, $first + 1); return; } } } echo \"-1\";} // Driver Code $n = 12; findConsecutive($n); // This code is contributed by nitin mittal?>", "e": 4559, "s": 3817, "text": null }, { "code": "<script> // Javascript program to print a consecutive// sequence to express N if possible. // Print consecutive numbers from// last to firstfunction printConsecutive(last, first){ document.write(first++); for (let x = first; x<= last; x++) document.write( \" + \" + x);} function findConsecutive(N){ for (let last = 1; last < N; last++) { for (let first = 0; first < last; first++) { if (2 * N == (last - first) * (last + first + 1)) { document.write(N + \" = \"); printConsecutive(last, first + 1); return; } } } document.write(\"-1\");} // Driver Code let n = 12; findConsecutive(n); // This code is contributed by _saurabh_jaiswal</script>", "e": 5367, "s": 4559, "text": null }, { "code": null, "e": 5377, "s": 5367, "text": "Output: " }, { "code": null, "e": 5392, "s": 5377, "text": "12 = 3 + 4 + 5" }, { "code": null, "e": 5949, "s": 5392, "text": "Reference : https://math.stackexchange.com/questions/139842/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbersThis article is contributed by Roshni Agarwal. 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": 5962, "s": 5949, "text": "nitin mittal" }, { "code": null, "e": 5979, "s": 5962, "text": "_saurabh_jaiswal" }, { "code": null, "e": 5991, "s": 5979, "text": "umadevi9616" }, { "code": null, "e": 5998, "s": 5991, "text": "series" }, { "code": null, "e": 6011, "s": 5998, "text": "Mathematical" }, { "code": null, "e": 6024, "s": 6011, "text": "Mathematical" }, { "code": null, "e": 6031, "s": 6024, "text": "series" } ]
Overfitting, underfitting, and the bias-variance tradeoff | by Steve Klosterman | Towards Data Science
Overfitting, underfitting, and the bias-variance tradeoff are foundational concepts in machine learning. A model is overfit if performance on the training data, used to fit the model, is substantially better than performance on a test set, held out from the model training process. For example, the prediction error of the training data may be noticeably smaller than that of the testing data. Comparing model performance metrics between these two data sets is one of the main reasons that data are split for training and testing. This way, the model’s capability for predictions with new, unseen data can be assessed. When a model overfits the training data, it is said to have high variance. One way to think about this is that whatever variability exists in the training data, the model has “learned” this very well. In fact, too well. A model with high variance is likely to have learned the noise in the training set. Noise consists of the random fluctuations, or offsets from true values, in the features (independent variables) and response (dependent variable) of the data. Noise can obscure the true relationship between features and the response variable. Virtually all real-world data are noisy. If there is random noise in the training set, then there is probably also random noise in the testing set. However, the specific values of the random fluctuations will be different than those of the training set, because after all, the noise is random. The model cannot anticipate the fluctuations in the new, unseen data of the testing set. This why testing performance of an overfit model is lower than training performance. Overfitting is more likely in the following circumstances: There are a large number of features available, relative to the number of samples (observations). The more features there are, the greater the chance of discovering a spurious relationship between the features and the response. A complex model is used, such as deep decision trees, or neural networks. Models like these effectively engineer their own features, and have an opportunity develop more complex hypotheses about the relationship between features and the response, making overfitting more likely. At the opposite end of the spectrum, if a model is not fitting the training data very well, this is known as underfitting, and the model is said to have high bias. In this case, the model may not be complex enough, in terms of the features or the type of model being used. Let’s examine concrete examples of underfitting, overfitting, and the ideal that sits in between, by fitting polynomial models to synthetic data in Python. The code below can be run in a Jupyter notebook to produce the results and plots shown here. #Import packagesimport numpy as np #numerical computationimport matplotlib.pyplot as plt #plotting package#Next line helps with rendering plots%matplotlib inlineimport matplotlib as mpl #additional plotting functionality First, we create the synthetic data. We: Choose 20 points randomly on the interval [0, 11). This includes 0 but not 11. We also sort them so that they’re in order, which would help if you want to create a line plot (here we’ll just make a scatter plot). Put them through a quadratic transformation and add some noise: y = (-x+2)(x-9) + ε, where ε is normally distributed noise with mean 0 and standard deviation 3 Then we make a scatter plot of the data. np.random.seed(seed=9)n_points = 20x = np.random.uniform(0, 11, n_points)x = np.sort(x)y = (-x+2) * (x-9) + np.random.normal(0, 3, n_points)mpl.rcParams['figure.dpi'] = 400plt.scatter(x, y)plt.xticks([])plt.yticks([])plt.ylim([-20, 20]) This looks like the shape of a parabola, as expected for a quadratic transformation of x. However we can see the noise in the fact that not all the points appear that they would lie perfectly along a parabola. In our synthetic example, we know the data generating process: the response variable y is a quadratic transformation of the feature x. In general, when building machine learning models, the data generating process is not known. Instead, several candidate features are proposed, a model is proposed, and an exploration is made of how well these features and this model can explain the data. In this case, we would likely plot the data, observe the apparent quadratic relationship, and use a quadratic model. However, for the sake of illustration of an underfit model, what does a linear model for these data look like? We can fit a polynomial model of degree 1, in other words a linear model, with numpy’s polyfit: lin_fit = np.polyfit(x, y, 1)lin_fit>>array([ 0.44464616, -0.61869372]) This has produced the slope and intercept of the line of best fit for these data. Let’s plot it and see what it looks like. We can calculate the linear transformation of the feature using the slope and intercept we got from fitting the linear model, again using numpy, this time the polyval function. We'll label this the "Underfit model". cmap = mpl.cm.get_cmap('tab10')plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(x, np.polyval(lin_fit, x), label='Underfit model', color=cmap(1))plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20]) Doesn’t look like a very good fit, does it! Now let’s imagine we have many features available, that are polynomial transformations of x, specifically x2, x3,... x15. This would be a large amount of features relative to the amount of samples (20) that we have. Again, in “real life”, we probably wouldn’t consider a model with all these features, since by observation we can see that a quadratic model, or 2nd degree polynomial, would likely be sufficient. However, identifying the ideal features isn’t always so straightforward. Our illustrative example serves to show what happens when we are very clearly using too many features. Let’s make a 15 degree polynomial fit: high_poly_fit = np.polyfit(x, y, 15)high_poly_fit>>array([ 1.04191511e-05, -7.58239114e-04, 2.48264043e-02, -4.83550912e-01, 6.24182399e+00, -5.63097621e+01, 3.64815913e+02, -1.71732868e+03, 5.87515347e+03, -1.44598953e+04, 2.50562989e+04, -2.94672314e+04, 2.21483755e+04, -9.60766525e+03, 1.99634019e+03, -1.43201982e+02]) These are the coefficients of all the powers of from 1 through 15 in this model, and the intercept. Notice the widely different scales of the coefficients: some are close to zero, while others are fairly large in terms of magnitude (absolute value). Let’s plot this model as well. First we generate a large number of evenly spaced points over our range of x values, so we can see how this model looks not only for the particular values used for model training, but also for values in between. plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(x, np.polyval(lin_fit, x), label='Underfit model', color=cmap(1))curve_x = np.linspace(0,11,333)plt.plot(curve_x, np.polyval(high_poly_fit, curve_x), label='Overfit model', color=cmap(2))plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20]) This is a classic case of overfitting. The overfit model passes nearly perfectly through all the training data. However it’s easy to see that for values in between, the overfit model does not look like a realistic representation of the data generating process. Rather, the overfit model has become tuned to the noise of the training data. This matches the definition of high variance given above. In the last graph, you can see another definition of high variance: a small change in the input x can result in a large change in the output y. This relationship between changes in inputs and outputs is an additional way that people talk about variance of machine learning models. You can also imagine that if we generated a new, larger synthetic data set, using the same quadratic function y=(−x+2)(x−9), but added new randomly generated noise according to the same distribution we used above, then randomly sampled 20 points and fit the high-degree polynomial, the resulting model would look much different. It would pass almost perfectly through these new noisy points and the coefficients of the 15 degree polynomial would be very different to allow this to happen. Repeating this process with different samples of 20 points, would continue to result in highly variable coefficient estimates. In other words, the coefficients would have high variance between samples of the data used for model training. This is yet another definition of a model with high variance. With our synthetic data, since in this case we know the data generating process, we can see how a 2nd degree polynomial fit looks in comparison with the underfit and overfit models. plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(x, np.polyval(lin_fit, x), label='Underfit model', color=cmap(1))plt.plot(curve_x, np.polyval(high_poly_fit, curve_x), label='Overfit model', color=cmap(2))plt.plot(curve_x, np.polyval(np.polyfit(x, y, 2), curve_x), label='Ideal model', color=cmap(3))plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20]) That’s more like it. But what do we do in the real world, when we’re not using made-up data, and we don’t know the data generating process? There are a number of machine learning techniques to deal with overfitting. One of the most popular is regularization. In order to show how regularization works to reduce overfitting, we’ll use the scikit-learn package. First, we need to create polynomial features manually. While above we simply had to tell numpy to fit a 15 degree polynomial to the data, here we need to manually create the features x2, x3,... x15 and then fit a linear model to find their coefficients. Scikit-learn makes creating polynomial features easy with PolynomialFeatures. We just say we want 15 degrees worth of polynomial features, without a bias feature (intercept), then pass our array reshaped as a column. from sklearn.preprocessing import PolynomialFeaturespoly = PolynomialFeatures(degree=15, include_bias=False)poly_features = poly.fit_transform(x.reshape(-1, 1))poly_features.shape>>(20, 15) We get back 15 columns, where the first column is x, the second x2, etc. Now we need to determine coefficients for these polynomial features. Above, we did this by using numpy to find the coefficients that provided the best fit to the training data. However, we saw this led to an overfit model. Here, we will pass these data to a routine for ridge regression, which is a kind of regularized regression. Without going too far in to details here, regularized regression works by finding the coefficients resulting in the best fit to the data while also limiting the magnitude of the coefficients. The effect of this is to provide a slightly worse fit to the data, in other words a model with higher bias. However, the goal is to avoid fitting the random noise, thus eliminating the high variance issue. Therefore, we are hoping to trade some variance for some bias, to obtain a model of the signal and not the noise. We will use the Ridge class from scikit-learn to do a ridge regression. from sklearn.linear_model import Ridgeridge = Ridge(alpha=0.001, fit_intercept=True, normalize=True, copy_X=True, max_iter=None, tol=0.001, random_state=1) There are many options to set when instantiating the Ridge class. An important one is alpha. This controls how much regularization is applied; in other words, how strongly the coefficient magnitudes are penalized, and kept close to zero. We will use a value of alpha I already found, just to illustrate the effects of regularization here. In general, the procedure for selecting alpha is to systematically evaluate a range of values, by either examining model performance on a validation set or by using a cross-validation procedure, to determine which one would be expected to provide the best performance on the unseen test set. alpha is a model hyperparameter and this would be the process of hyperparameter tuning. The other options we specified for Ridge indicate that we'd like to fit an intercept (because we didn’t include one when generating PolynomialFeatures), normalize the features to the same scale before model fitting, which is necessary since the coefficients will all be penalized in the same way, and a few others. I'm glossing over these details here, although you can consult the scikit-learn documentation, as while as my book, for further information on regularization as well as hyperparameter tuning. Now we proceed to fit the ridge regression using the polynomial features and the response variable. ridge.fit(poly_features, y)>>Ridge(alpha=0.001, copy_X=True, fit_intercept=True, max_iter=None, normalize=True, random_state=1, solver='auto', tol=0.001) What do the values of the fitted coefficients look like, in comparison to those found above by fitting the polynomial with numpy? ridge.coef_>>array([ 8.98768521e+00, -5.14275445e-01, -3.95480123e-02, -1.10685070e-03, 4.49790120e-05, 8.58383048e-06, 6.74724995e-07, 3.02757058e-08, -3.81325130e-10, -2.54650509e-10, -3.25677313e-11, -2.66208560e-12, -1.05898398e-13, 1.22711353e-14, 3.90035611e-15]) We can see that the coefficient values from the regularized regression are relatively small in magnitude, compared to those from the polynomial fit. This is how regularization works: by “shrinking” coefficient values toward zero. For this reason regularization may also be referred to as shrinkage. Let’s obtain the predicted values y_pred over the large number of evenly spaced points curve_x we used above, for plotting. First we need to generate the polynomial features for all these points. poly_features_curve = poly.fit_transform(curve_x.reshape(-1, 1))y_pred = ridge.predict(poly_features_curve) We’ll remove the underfit model from our plot, and add the regularized model. plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(curve_x, np.polyval(high_poly_fit, curve_x), label='Overfit model', color=cmap(2))plt.plot(curve_x, np.polyval(np.polyfit(x, y, 2), curve_x), label='Ideal model', color=cmap(3))plt.plot(curve_x, y_pred, label='Regularized model',color=cmap(4), linestyle='--')plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20]) The regularized model looks similar to the ideal model. This shows that even if we don’t have knowledge of the data generating process, as we typically don’t in real-world predictive modeling work, we can still use regularization to reduce the effect of overfitting when a large number of candidate features are available. Note, however, that the regularized model should not be used for extrapolation. We can see that the regularized model starts to increase toward the right side of the plot. This increase should be viewed with suspicion, as there is nothing in the training data that makes it clear that this would be expected. This is an example of the general view that extrapolation of model predictions outside the range of the training data is not recommended. The goal of trading variance for bias is to improve model performance on unseen testing data. Let’s generate some testing data, in the same way we generated the training data, to see if we achieved this goal. We repeat the process used to generate x and y=(−x+2)(x−9)+ε above, but with a different random seed. This results in different points x over the same interval and different random noise ε from the same distribution, creating new values for the response variable y, but from the same data generating process. np.random.seed(seed=4)n_points = 20x_test = np.random.uniform(0, 11, n_points)x_test = np.sort(x_test)y_test = (-x_test+2) * (x_test-9) + np.random.normal(0, 3, n_points) We’ll also define a lambda function to measure prediction error as the root mean squared error (RMSE). RMSE = lambda y, y_pred: np.sqrt(np.mean((y-y_pred)**2)) What is the RMSE of our first model, the polynomial fit to the training data? y_train_pred = np.polyval(high_poly_fit, x)RMSE(y, y_train_pred)>>1.858235982416223 How about the RMSE on the newly generated testing data? y_test_pred = np.polyval(high_poly_fit, x_test)RMSE(y_test, y_test_pred)>>9811.219078261804 The testing error is vastly larger than the training error from this model, a clear sign of overfitting. How does the regularized model compare? y_train_pred = ridge.predict(poly_features)RMSE(y, y_train_pred)>>3.235497045896461poly_features_test = poly.fit_transform(x_test.reshape(-1, 1))y_test_pred = ridge.predict(poly_features_test)RMSE(y_test, y_test_pred)>>3.5175193708774946 While the regularized model has a bit higher training error (higher bias) than the polynomial fit, the testing error is greatly improved. This shows how the bias-variance tradeoff can be leveraged to improve model predictive capability. This post illustrates the concepts of overfitting, underfitting, and the bias-variance tradeoff through an illustrative example in Python and scikit-learn. It expands on a section from my book Data Science Projects with Python: A case study approach to successful data science projects using Python, pandas, and scikit-learn. For a more in-depth explanation of how regularization works, how to use cross-validation for hyperparameter selection, and hands-on practice with these and other machine learning techniques, check out the book, which you can find on Amazon, with Q&A and errata here. Here are a few final thoughts on bias and variance. Statistical definitions of bias and variance: This post has focused on the intuitive machine learning definitions of bias and variance. There are also more formal statistical definitions. See this document for a derivation of the mathematical expressions for the bias-variance decomposition of squared error, as well as The Elements of Statistical Learning by Hastie et al. for more discussion of the bias-variance decomposition and tradeoff. Countering high variance with more data: In his Coursera course Machine Learning, Andrew Ng states that, according to the large data rationale, training on a very large data set can be an effective way to combat overfitting. The idea is that, with enough training data, the difference between the training and testing errors should be small, which means reduced variance. There is an underlying assumption to this rationale, that the features contain sufficient information to make accurate predictions of the response variable. If not, the model will suffer from high bias (high training error), so the low variance would be a moot point. A little overfitting may not be a problem: Model performance on the testing set is often a bit lower than on the training set. We saw this with our regularized model above. Technically, there is at least a little bit of overfitting going on here. However, it may not matter, since the best model is usually considered to be that with the highest testing score. Originally published at https://www.steveklosterman.com on May 19, 2019.
[ { "code": null, "e": 791, "s": 172, "text": "Overfitting, underfitting, and the bias-variance tradeoff are foundational concepts in machine learning. A model is overfit if performance on the training data, used to fit the model, is substantially better than performance on a test set, held out from the model training process. For example, the prediction error of the training data may be noticeably smaller than that of the testing data. Comparing model performance metrics between these two data sets is one of the main reasons that data are split for training and testing. This way, the model’s capability for predictions with new, unseen data can be assessed." }, { "code": null, "e": 1379, "s": 791, "text": "When a model overfits the training data, it is said to have high variance. One way to think about this is that whatever variability exists in the training data, the model has “learned” this very well. In fact, too well. A model with high variance is likely to have learned the noise in the training set. Noise consists of the random fluctuations, or offsets from true values, in the features (independent variables) and response (dependent variable) of the data. Noise can obscure the true relationship between features and the response variable. Virtually all real-world data are noisy." }, { "code": null, "e": 1806, "s": 1379, "text": "If there is random noise in the training set, then there is probably also random noise in the testing set. However, the specific values of the random fluctuations will be different than those of the training set, because after all, the noise is random. The model cannot anticipate the fluctuations in the new, unseen data of the testing set. This why testing performance of an overfit model is lower than training performance." }, { "code": null, "e": 1865, "s": 1806, "text": "Overfitting is more likely in the following circumstances:" }, { "code": null, "e": 2093, "s": 1865, "text": "There are a large number of features available, relative to the number of samples (observations). The more features there are, the greater the chance of discovering a spurious relationship between the features and the response." }, { "code": null, "e": 2372, "s": 2093, "text": "A complex model is used, such as deep decision trees, or neural networks. Models like these effectively engineer their own features, and have an opportunity develop more complex hypotheses about the relationship between features and the response, making overfitting more likely." }, { "code": null, "e": 2645, "s": 2372, "text": "At the opposite end of the spectrum, if a model is not fitting the training data very well, this is known as underfitting, and the model is said to have high bias. In this case, the model may not be complex enough, in terms of the features or the type of model being used." }, { "code": null, "e": 2894, "s": 2645, "text": "Let’s examine concrete examples of underfitting, overfitting, and the ideal that sits in between, by fitting polynomial models to synthetic data in Python. The code below can be run in a Jupyter notebook to produce the results and plots shown here." }, { "code": null, "e": 3115, "s": 2894, "text": "#Import packagesimport numpy as np #numerical computationimport matplotlib.pyplot as plt #plotting package#Next line helps with rendering plots%matplotlib inlineimport matplotlib as mpl #additional plotting functionality" }, { "code": null, "e": 3156, "s": 3115, "text": "First, we create the synthetic data. We:" }, { "code": null, "e": 3369, "s": 3156, "text": "Choose 20 points randomly on the interval [0, 11). This includes 0 but not 11. We also sort them so that they’re in order, which would help if you want to create a line plot (here we’ll just make a scatter plot)." }, { "code": null, "e": 3529, "s": 3369, "text": "Put them through a quadratic transformation and add some noise: y = (-x+2)(x-9) + ε, where ε is normally distributed noise with mean 0 and standard deviation 3" }, { "code": null, "e": 3570, "s": 3529, "text": "Then we make a scatter plot of the data." }, { "code": null, "e": 3807, "s": 3570, "text": "np.random.seed(seed=9)n_points = 20x = np.random.uniform(0, 11, n_points)x = np.sort(x)y = (-x+2) * (x-9) + np.random.normal(0, 3, n_points)mpl.rcParams['figure.dpi'] = 400plt.scatter(x, y)plt.xticks([])plt.yticks([])plt.ylim([-20, 20])" }, { "code": null, "e": 4017, "s": 3807, "text": "This looks like the shape of a parabola, as expected for a quadratic transformation of x. However we can see the noise in the fact that not all the points appear that they would lie perfectly along a parabola." }, { "code": null, "e": 4407, "s": 4017, "text": "In our synthetic example, we know the data generating process: the response variable y is a quadratic transformation of the feature x. In general, when building machine learning models, the data generating process is not known. Instead, several candidate features are proposed, a model is proposed, and an exploration is made of how well these features and this model can explain the data." }, { "code": null, "e": 4635, "s": 4407, "text": "In this case, we would likely plot the data, observe the apparent quadratic relationship, and use a quadratic model. However, for the sake of illustration of an underfit model, what does a linear model for these data look like?" }, { "code": null, "e": 4731, "s": 4635, "text": "We can fit a polynomial model of degree 1, in other words a linear model, with numpy’s polyfit:" }, { "code": null, "e": 4803, "s": 4731, "text": "lin_fit = np.polyfit(x, y, 1)lin_fit>>array([ 0.44464616, -0.61869372])" }, { "code": null, "e": 5143, "s": 4803, "text": "This has produced the slope and intercept of the line of best fit for these data. Let’s plot it and see what it looks like. We can calculate the linear transformation of the feature using the slope and intercept we got from fitting the linear model, again using numpy, this time the polyval function. We'll label this the \"Underfit model\"." }, { "code": null, "e": 5369, "s": 5143, "text": "cmap = mpl.cm.get_cmap('tab10')plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(x, np.polyval(lin_fit, x), label='Underfit model', color=cmap(1))plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20])" }, { "code": null, "e": 5413, "s": 5369, "text": "Doesn’t look like a very good fit, does it!" }, { "code": null, "e": 6001, "s": 5413, "text": "Now let’s imagine we have many features available, that are polynomial transformations of x, specifically x2, x3,... x15. This would be a large amount of features relative to the amount of samples (20) that we have. Again, in “real life”, we probably wouldn’t consider a model with all these features, since by observation we can see that a quadratic model, or 2nd degree polynomial, would likely be sufficient. However, identifying the ideal features isn’t always so straightforward. Our illustrative example serves to show what happens when we are very clearly using too many features." }, { "code": null, "e": 6040, "s": 6001, "text": "Let’s make a 15 degree polynomial fit:" }, { "code": null, "e": 6389, "s": 6040, "text": "high_poly_fit = np.polyfit(x, y, 15)high_poly_fit>>array([ 1.04191511e-05, -7.58239114e-04, 2.48264043e-02, -4.83550912e-01, 6.24182399e+00, -5.63097621e+01, 3.64815913e+02, -1.71732868e+03, 5.87515347e+03, -1.44598953e+04, 2.50562989e+04, -2.94672314e+04, 2.21483755e+04, -9.60766525e+03, 1.99634019e+03, -1.43201982e+02])" }, { "code": null, "e": 6882, "s": 6389, "text": "These are the coefficients of all the powers of from 1 through 15 in this model, and the intercept. Notice the widely different scales of the coefficients: some are close to zero, while others are fairly large in terms of magnitude (absolute value). Let’s plot this model as well. First we generate a large number of evenly spaced points over our range of x values, so we can see how this model looks not only for the particular values used for model training, but also for values in between." }, { "code": null, "e": 7207, "s": 6882, "text": "plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(x, np.polyval(lin_fit, x), label='Underfit model', color=cmap(1))curve_x = np.linspace(0,11,333)plt.plot(curve_x, np.polyval(high_poly_fit, curve_x), label='Overfit model', color=cmap(2))plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20])" }, { "code": null, "e": 7604, "s": 7207, "text": "This is a classic case of overfitting. The overfit model passes nearly perfectly through all the training data. However it’s easy to see that for values in between, the overfit model does not look like a realistic representation of the data generating process. Rather, the overfit model has become tuned to the noise of the training data. This matches the definition of high variance given above." }, { "code": null, "e": 7885, "s": 7604, "text": "In the last graph, you can see another definition of high variance: a small change in the input x can result in a large change in the output y. This relationship between changes in inputs and outputs is an additional way that people talk about variance of machine learning models." }, { "code": null, "e": 8674, "s": 7885, "text": "You can also imagine that if we generated a new, larger synthetic data set, using the same quadratic function y=(−x+2)(x−9), but added new randomly generated noise according to the same distribution we used above, then randomly sampled 20 points and fit the high-degree polynomial, the resulting model would look much different. It would pass almost perfectly through these new noisy points and the coefficients of the 15 degree polynomial would be very different to allow this to happen. Repeating this process with different samples of 20 points, would continue to result in highly variable coefficient estimates. In other words, the coefficients would have high variance between samples of the data used for model training. This is yet another definition of a model with high variance." }, { "code": null, "e": 8856, "s": 8674, "text": "With our synthetic data, since in this case we know the data generating process, we can see how a 2nd degree polynomial fit looks in comparison with the underfit and overfit models." }, { "code": null, "e": 9253, "s": 8856, "text": "plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(x, np.polyval(lin_fit, x), label='Underfit model', color=cmap(1))plt.plot(curve_x, np.polyval(high_poly_fit, curve_x), label='Overfit model', color=cmap(2))plt.plot(curve_x, np.polyval(np.polyfit(x, y, 2), curve_x), label='Ideal model', color=cmap(3))plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20])" }, { "code": null, "e": 9512, "s": 9253, "text": "That’s more like it. But what do we do in the real world, when we’re not using made-up data, and we don’t know the data generating process? There are a number of machine learning techniques to deal with overfitting. One of the most popular is regularization." }, { "code": null, "e": 10084, "s": 9512, "text": "In order to show how regularization works to reduce overfitting, we’ll use the scikit-learn package. First, we need to create polynomial features manually. While above we simply had to tell numpy to fit a 15 degree polynomial to the data, here we need to manually create the features x2, x3,... x15 and then fit a linear model to find their coefficients. Scikit-learn makes creating polynomial features easy with PolynomialFeatures. We just say we want 15 degrees worth of polynomial features, without a bias feature (intercept), then pass our array reshaped as a column." }, { "code": null, "e": 10274, "s": 10084, "text": "from sklearn.preprocessing import PolynomialFeaturespoly = PolynomialFeatures(degree=15, include_bias=False)poly_features = poly.fit_transform(x.reshape(-1, 1))poly_features.shape>>(20, 15)" }, { "code": null, "e": 10870, "s": 10274, "text": "We get back 15 columns, where the first column is x, the second x2, etc. Now we need to determine coefficients for these polynomial features. Above, we did this by using numpy to find the coefficients that provided the best fit to the training data. However, we saw this led to an overfit model. Here, we will pass these data to a routine for ridge regression, which is a kind of regularized regression. Without going too far in to details here, regularized regression works by finding the coefficients resulting in the best fit to the data while also limiting the magnitude of the coefficients." }, { "code": null, "e": 11190, "s": 10870, "text": "The effect of this is to provide a slightly worse fit to the data, in other words a model with higher bias. However, the goal is to avoid fitting the random noise, thus eliminating the high variance issue. Therefore, we are hoping to trade some variance for some bias, to obtain a model of the signal and not the noise." }, { "code": null, "e": 11262, "s": 11190, "text": "We will use the Ridge class from scikit-learn to do a ridge regression." }, { "code": null, "e": 11464, "s": 11262, "text": "from sklearn.linear_model import Ridgeridge = Ridge(alpha=0.001, fit_intercept=True, normalize=True, copy_X=True, max_iter=None, tol=0.001, random_state=1)" }, { "code": null, "e": 12183, "s": 11464, "text": "There are many options to set when instantiating the Ridge class. An important one is alpha. This controls how much regularization is applied; in other words, how strongly the coefficient magnitudes are penalized, and kept close to zero. We will use a value of alpha I already found, just to illustrate the effects of regularization here. In general, the procedure for selecting alpha is to systematically evaluate a range of values, by either examining model performance on a validation set or by using a cross-validation procedure, to determine which one would be expected to provide the best performance on the unseen test set. alpha is a model hyperparameter and this would be the process of hyperparameter tuning." }, { "code": null, "e": 12690, "s": 12183, "text": "The other options we specified for Ridge indicate that we'd like to fit an intercept (because we didn’t include one when generating PolynomialFeatures), normalize the features to the same scale before model fitting, which is necessary since the coefficients will all be penalized in the same way, and a few others. I'm glossing over these details here, although you can consult the scikit-learn documentation, as while as my book, for further information on regularization as well as hyperparameter tuning." }, { "code": null, "e": 12790, "s": 12690, "text": "Now we proceed to fit the ridge regression using the polynomial features and the response variable." }, { "code": null, "e": 12946, "s": 12790, "text": "ridge.fit(poly_features, y)>>Ridge(alpha=0.001, copy_X=True, fit_intercept=True, max_iter=None, normalize=True, random_state=1, solver='auto', tol=0.001)" }, { "code": null, "e": 13076, "s": 12946, "text": "What do the values of the fitted coefficients look like, in comparison to those found above by fitting the polynomial with numpy?" }, { "code": null, "e": 13370, "s": 13076, "text": "ridge.coef_>>array([ 8.98768521e+00, -5.14275445e-01, -3.95480123e-02, -1.10685070e-03, 4.49790120e-05, 8.58383048e-06, 6.74724995e-07, 3.02757058e-08, -3.81325130e-10, -2.54650509e-10, -3.25677313e-11, -2.66208560e-12, -1.05898398e-13, 1.22711353e-14, 3.90035611e-15])" }, { "code": null, "e": 13669, "s": 13370, "text": "We can see that the coefficient values from the regularized regression are relatively small in magnitude, compared to those from the polynomial fit. This is how regularization works: by “shrinking” coefficient values toward zero. For this reason regularization may also be referred to as shrinkage." }, { "code": null, "e": 13865, "s": 13669, "text": "Let’s obtain the predicted values y_pred over the large number of evenly spaced points curve_x we used above, for plotting. First we need to generate the polynomial features for all these points." }, { "code": null, "e": 13973, "s": 13865, "text": "poly_features_curve = poly.fit_transform(curve_x.reshape(-1, 1))y_pred = ridge.predict(poly_features_curve)" }, { "code": null, "e": 14051, "s": 13973, "text": "We’ll remove the underfit model from our plot, and add the regularized model." }, { "code": null, "e": 14464, "s": 14051, "text": "plt.scatter(x, y, label='Data', color=cmap(0))plt.plot(curve_x, np.polyval(high_poly_fit, curve_x), label='Overfit model', color=cmap(2))plt.plot(curve_x, np.polyval(np.polyfit(x, y, 2), curve_x), label='Ideal model', color=cmap(3))plt.plot(curve_x, y_pred, label='Regularized model',color=cmap(4), linestyle='--')plt.legend(loc=[0.17, 0.1])plt.xticks([])plt.yticks([])plt.ylim([-20, 20])" }, { "code": null, "e": 14787, "s": 14464, "text": "The regularized model looks similar to the ideal model. This shows that even if we don’t have knowledge of the data generating process, as we typically don’t in real-world predictive modeling work, we can still use regularization to reduce the effect of overfitting when a large number of candidate features are available." }, { "code": null, "e": 15234, "s": 14787, "text": "Note, however, that the regularized model should not be used for extrapolation. We can see that the regularized model starts to increase toward the right side of the plot. This increase should be viewed with suspicion, as there is nothing in the training data that makes it clear that this would be expected. This is an example of the general view that extrapolation of model predictions outside the range of the training data is not recommended." }, { "code": null, "e": 15752, "s": 15234, "text": "The goal of trading variance for bias is to improve model performance on unseen testing data. Let’s generate some testing data, in the same way we generated the training data, to see if we achieved this goal. We repeat the process used to generate x and y=(−x+2)(x−9)+ε above, but with a different random seed. This results in different points x over the same interval and different random noise ε from the same distribution, creating new values for the response variable y, but from the same data generating process." }, { "code": null, "e": 15923, "s": 15752, "text": "np.random.seed(seed=4)n_points = 20x_test = np.random.uniform(0, 11, n_points)x_test = np.sort(x_test)y_test = (-x_test+2) * (x_test-9) + np.random.normal(0, 3, n_points)" }, { "code": null, "e": 16026, "s": 15923, "text": "We’ll also define a lambda function to measure prediction error as the root mean squared error (RMSE)." }, { "code": null, "e": 16083, "s": 16026, "text": "RMSE = lambda y, y_pred: np.sqrt(np.mean((y-y_pred)**2))" }, { "code": null, "e": 16161, "s": 16083, "text": "What is the RMSE of our first model, the polynomial fit to the training data?" }, { "code": null, "e": 16245, "s": 16161, "text": "y_train_pred = np.polyval(high_poly_fit, x)RMSE(y, y_train_pred)>>1.858235982416223" }, { "code": null, "e": 16301, "s": 16245, "text": "How about the RMSE on the newly generated testing data?" }, { "code": null, "e": 16393, "s": 16301, "text": "y_test_pred = np.polyval(high_poly_fit, x_test)RMSE(y_test, y_test_pred)>>9811.219078261804" }, { "code": null, "e": 16538, "s": 16393, "text": "The testing error is vastly larger than the training error from this model, a clear sign of overfitting. How does the regularized model compare?" }, { "code": null, "e": 16776, "s": 16538, "text": "y_train_pred = ridge.predict(poly_features)RMSE(y, y_train_pred)>>3.235497045896461poly_features_test = poly.fit_transform(x_test.reshape(-1, 1))y_test_pred = ridge.predict(poly_features_test)RMSE(y_test, y_test_pred)>>3.5175193708774946" }, { "code": null, "e": 17013, "s": 16776, "text": "While the regularized model has a bit higher training error (higher bias) than the polynomial fit, the testing error is greatly improved. This shows how the bias-variance tradeoff can be leveraged to improve model predictive capability." }, { "code": null, "e": 17606, "s": 17013, "text": "This post illustrates the concepts of overfitting, underfitting, and the bias-variance tradeoff through an illustrative example in Python and scikit-learn. It expands on a section from my book Data Science Projects with Python: A case study approach to successful data science projects using Python, pandas, and scikit-learn. For a more in-depth explanation of how regularization works, how to use cross-validation for hyperparameter selection, and hands-on practice with these and other machine learning techniques, check out the book, which you can find on Amazon, with Q&A and errata here." }, { "code": null, "e": 17658, "s": 17606, "text": "Here are a few final thoughts on bias and variance." }, { "code": null, "e": 18101, "s": 17658, "text": "Statistical definitions of bias and variance: This post has focused on the intuitive machine learning definitions of bias and variance. There are also more formal statistical definitions. See this document for a derivation of the mathematical expressions for the bias-variance decomposition of squared error, as well as The Elements of Statistical Learning by Hastie et al. for more discussion of the bias-variance decomposition and tradeoff." }, { "code": null, "e": 18741, "s": 18101, "text": "Countering high variance with more data: In his Coursera course Machine Learning, Andrew Ng states that, according to the large data rationale, training on a very large data set can be an effective way to combat overfitting. The idea is that, with enough training data, the difference between the training and testing errors should be small, which means reduced variance. There is an underlying assumption to this rationale, that the features contain sufficient information to make accurate predictions of the response variable. If not, the model will suffer from high bias (high training error), so the low variance would be a moot point." }, { "code": null, "e": 19102, "s": 18741, "text": "A little overfitting may not be a problem: Model performance on the testing set is often a bit lower than on the training set. We saw this with our regularized model above. Technically, there is at least a little bit of overfitting going on here. However, it may not matter, since the best model is usually considered to be that with the highest testing score." } ]
A Simple Starter Guide to Build a Neural Network | by Jeff Hu | Towards Data Science
You will be able to program and build a vanilla Feedforward Neural Network (FNN) starting today via PyTorch. Here is the python jupyter codebase for the FNN: https://github.com/yhuag/neural-network-lab This guide serves as a basic hands-on work to lead you through building a neural network from scratch. Most of the mathematical concepts and scientific decisions are left out. You are free to research more on that part. Please make sure you have Python and PyTorch installed in your machine: Please make sure you have Python and PyTorch installed in your machine: Python 3.6 (installation) PyTorch (installation) 2. Check the correctness of Python installations by the commands at console: python -V The output should be Python 3.6.3 or later version 3. Open a repository(folder) and create your first Neural Network file: mkdir fnn-tutocd fnn-tutotouch fnn.py All the following codes should be written in the fnn.py file It will load PyTorch into the codes. Great! A well beginning is half done. Hyper-parameters are the powerful arguments that are set up upfront and will not be updated along with the training of the neural network. MNIST is a huge database with tons of handwritten digits (i.e. 0 to 9) aims for the usage of image processing. After downloading the MNIST dataset, we load them into our codes. Note: We shuffle the loading process of train_dataset to make the learning process independent of data order, but the order of test_loader remains to examine whether we can handle unspecified bias order of inputs. Now we have our datasets ready. We will start building the neural network. The conceptual illustration can be viewed as below: The FNN includes two fully-connected layers (i.e. fc1 & fc2) and a non-linear ReLU layer in between. Normally we call this structure 1-hidden layer FNN, without counting the output layer (fc2) in. By running the forward pass, the input images (x) can go through the neural network and generate a output (out) demonstrating how are the likabilities it belongs to each of the 10 classes. For example, a cat image can have 0.8 likability to a dog class and a 0.3 likability to a airplane class. We now create a real FNN based on our structure. net = Net(input_size, hidden_size, num_classes) Note: You could enable this line to run the codes on GPU # net.cuda() # You can comment out this line to disable GPU Loss function (criterion) decides how the output can be compared to a class, which determines how good or bad the neural network performs. And the optimizer chooses a way to update the weight in order to converge to find the best weights in this neural network. criterion = nn.CrossEntropyLoss()optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate) This process might takes around 3 to 5 minutes depending on your machine. The detailed explanations are listed as comments (#) in the following codes. Similar to training the neural network, we also need to load batches of test images and collect the outputs. The differences are that: No loss & weights calculationNo wights updateHas correct prediction calculation No loss & weights calculation No wights update Has correct prediction calculation We save the trained model as a pickle that can be loaded and used later. torch.save(net.state_dict(), ‘fnn_model.pkl’) Congrats. You have done building your first Feedforward Neural Network! Save and close the file. Start running the file at the console: python fnn.py You will see the training process going like the following: Thanks for your time and hope you enjoy the tutorial. All the codes can be found here! Credit: The codes are heavily and thankfully based on yunjey’s great codebase. ❤
[ { "code": null, "e": 374, "s": 172, "text": "You will be able to program and build a vanilla Feedforward Neural Network (FNN) starting today via PyTorch. Here is the python jupyter codebase for the FNN: https://github.com/yhuag/neural-network-lab" }, { "code": null, "e": 594, "s": 374, "text": "This guide serves as a basic hands-on work to lead you through building a neural network from scratch. Most of the mathematical concepts and scientific decisions are left out. You are free to research more on that part." }, { "code": null, "e": 666, "s": 594, "text": "Please make sure you have Python and PyTorch installed in your machine:" }, { "code": null, "e": 738, "s": 666, "text": "Please make sure you have Python and PyTorch installed in your machine:" }, { "code": null, "e": 764, "s": 738, "text": "Python 3.6 (installation)" }, { "code": null, "e": 787, "s": 764, "text": "PyTorch (installation)" }, { "code": null, "e": 864, "s": 787, "text": "2. Check the correctness of Python installations by the commands at console:" }, { "code": null, "e": 874, "s": 864, "text": "python -V" }, { "code": null, "e": 925, "s": 874, "text": "The output should be Python 3.6.3 or later version" }, { "code": null, "e": 997, "s": 925, "text": "3. Open a repository(folder) and create your first Neural Network file:" }, { "code": null, "e": 1035, "s": 997, "text": "mkdir fnn-tutocd fnn-tutotouch fnn.py" }, { "code": null, "e": 1096, "s": 1035, "text": "All the following codes should be written in the fnn.py file" }, { "code": null, "e": 1171, "s": 1096, "text": "It will load PyTorch into the codes. Great! A well beginning is half done." }, { "code": null, "e": 1310, "s": 1171, "text": "Hyper-parameters are the powerful arguments that are set up upfront and will not be updated along with the training of the neural network." }, { "code": null, "e": 1421, "s": 1310, "text": "MNIST is a huge database with tons of handwritten digits (i.e. 0 to 9) aims for the usage of image processing." }, { "code": null, "e": 1487, "s": 1421, "text": "After downloading the MNIST dataset, we load them into our codes." }, { "code": null, "e": 1701, "s": 1487, "text": "Note: We shuffle the loading process of train_dataset to make the learning process independent of data order, but the order of test_loader remains to examine whether we can handle unspecified bias order of inputs." }, { "code": null, "e": 1828, "s": 1701, "text": "Now we have our datasets ready. We will start building the neural network. The conceptual illustration can be viewed as below:" }, { "code": null, "e": 2025, "s": 1828, "text": "The FNN includes two fully-connected layers (i.e. fc1 & fc2) and a non-linear ReLU layer in between. Normally we call this structure 1-hidden layer FNN, without counting the output layer (fc2) in." }, { "code": null, "e": 2320, "s": 2025, "text": "By running the forward pass, the input images (x) can go through the neural network and generate a output (out) demonstrating how are the likabilities it belongs to each of the 10 classes. For example, a cat image can have 0.8 likability to a dog class and a 0.3 likability to a airplane class." }, { "code": null, "e": 2369, "s": 2320, "text": "We now create a real FNN based on our structure." }, { "code": null, "e": 2417, "s": 2369, "text": "net = Net(input_size, hidden_size, num_classes)" }, { "code": null, "e": 2474, "s": 2417, "text": "Note: You could enable this line to run the codes on GPU" }, { "code": null, "e": 2537, "s": 2474, "text": "# net.cuda() # You can comment out this line to disable GPU" }, { "code": null, "e": 2799, "s": 2537, "text": "Loss function (criterion) decides how the output can be compared to a class, which determines how good or bad the neural network performs. And the optimizer chooses a way to update the weight in order to converge to find the best weights in this neural network." }, { "code": null, "e": 2897, "s": 2799, "text": "criterion = nn.CrossEntropyLoss()optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)" }, { "code": null, "e": 3048, "s": 2897, "text": "This process might takes around 3 to 5 minutes depending on your machine. The detailed explanations are listed as comments (#) in the following codes." }, { "code": null, "e": 3183, "s": 3048, "text": "Similar to training the neural network, we also need to load batches of test images and collect the outputs. The differences are that:" }, { "code": null, "e": 3263, "s": 3183, "text": "No loss & weights calculationNo wights updateHas correct prediction calculation" }, { "code": null, "e": 3293, "s": 3263, "text": "No loss & weights calculation" }, { "code": null, "e": 3310, "s": 3293, "text": "No wights update" }, { "code": null, "e": 3345, "s": 3310, "text": "Has correct prediction calculation" }, { "code": null, "e": 3418, "s": 3345, "text": "We save the trained model as a pickle that can be loaded and used later." }, { "code": null, "e": 3464, "s": 3418, "text": "torch.save(net.state_dict(), ‘fnn_model.pkl’)" }, { "code": null, "e": 3536, "s": 3464, "text": "Congrats. You have done building your first Feedforward Neural Network!" }, { "code": null, "e": 3600, "s": 3536, "text": "Save and close the file. Start running the file at the console:" }, { "code": null, "e": 3614, "s": 3600, "text": "python fnn.py" }, { "code": null, "e": 3674, "s": 3614, "text": "You will see the training process going like the following:" }, { "code": null, "e": 3761, "s": 3674, "text": "Thanks for your time and hope you enjoy the tutorial. All the codes can be found here!" } ]
Helping Kids Play With Artificial Intelligence | by Jason Boog | Towards Data Science
Every day, our kids are swept through the world by algorithms. YouTube algorithms decide what videos they watch, GPS algorithms map what route they take to school, Spotify algorithms select what songs they hear, and personal assistants like Siri and Alexa advise them — all of it driven by artificial intelligence. Kids (and adults!) leave these passive engagements with AI without any physical product — just an endless stream of passive consumption. Instead of getting carried away by these digital currents, teachers, parents, and caregivers should show kids how to experiment with powerful tools like machine learning and neural networks. We must raise kids who are capable of working alongside artificial intelligence in the workplace. The best workers of the future will be able to dictate, scribble, chat, and dream better with the help of technology. Future workers will need to demonstrate creativity, flexibility, and comfort with machine learning and algorithmic tools. Through play, we can encourage these skills without sacrificing a sense of analog creativity. We can show kids that AI is not a passive feature in their lives. AI is a tool, just as much as a pencil or paper. The real trick is knowing when and why a particular problem calls for a specific digital tool. I spent the last six months learning enough code so I could use the superpowered GPT-2 language model to write stories. I emerged with 50,000 words of strange and wonderful stories from my AI writing partner. I loved it all, but never found the perfect way to share it with new readers. The text was too strange to publish traditionally and too unwieldy to read as a straight-ahead PDF. My daughter ultimately solved the problem for me, bringing home Lunch Money by Andrew Clements, a classic middle-grade novel about a kid who starts selling zines at his grade school. You should read the whole novel, but this Google Books link will take you straight to the heart of the book: a recipe for making a simple 16-page zine with two pieces of paper... books.google.com Over the holidays, my daughter and I started making zines together. It was lovely, cutting, pasting, and scribbling inside these bitty books. Each zine was a combination of images and text generated artificial intelligence, but they were edited, transcribed, and hand-written by human beings. It’s a perfect combination of human and AI creativity — we call them “Machine Zines.” That simple process was a revelation. As I took the time to hand-write my GPT-2 output, I became a participant in the writing process, rather than a passive guy pushing the “Go” button while GPT-2 did all the work. I think zines are by far the best medium for sharing GPT-2 output. You can read the zine quickly and the reader won’t get bogged down in the sometimes awkward syntax of AI-generated text. If you make your own zines, drop me a line. I’d love to share your work with more readers! You don’t have to spend six months learning how to code to write with GPT-2 or other AI language models. Following these simple steps, you could write your own Machine Zines by the end of this article! Working with the kid in your life, compose one or two sentences — the opening of a story, the first lines of a poem, or the start of a personal essay. That’s all you need. Here’s how we started: A family creates small books with artificial intelligence. They are called "machine zines." Once you have your first few sentences perfected, go to Talk To Transformer. Built by @AdamDanielKing, this website gives you instant access to GPT-2, a superpowered language model trained on eight million web pages. The company OpenAI trained GPT-2 and gradually made the powerful predictive text generator available to the public. GPT-2 has a deceptively simple skill set: it can predict what should come next based on a given writing sample. Once you type in the sentences you wrote, Talk To Transformer works like the auto-complete on your smartphone. Once you hit that button, GPT-2 will automatically complete your sentences. The output can range from a few sentences to a few paragraphs. Keep clicking “COMPLETE TEXT” until you get enough sentences to fill your zine. Now that GPT-2 worked its magic, it’s time for you to write out the text by hand. This adds a human touch to the zine, and gives you a chance to edit the story however you like. Cut sentences that don’t make sense, combine sentences, move paragraphs around, and add any words you like. You are the human! You are the boss of this zine! Here’s what our final text looked like after we trimmed the text and moved things around to help express GPT-2’s message about human and AI creativity: The first thing you need to do is stop. And think about what you want to see.Why not have the book do the talking? Why not have the machine sing? Why not have the machine write?A machine can talk to you.A machine can write you stories.They do not understand you.Sometimes a machine will do more. It will follow you from behind, writing stories for you.What will it write if you don't?What will it write if you try to stop it?Remember that it's just there to let you take the first step.What will it write? Now it’s time to make something that only a human being can make. Depending on how many pages you have, choose your favorite zine style. There are many different ways to fold zines, and they are all illustrated with amazing videos. For instance, the 8-page zine format is really easy and really satisfying once you fold things correctly... This 14-page model is a bit more complicated... My daughter and I used the awesome Lunch Money by Andrew Clements method. This Google Books link will take you straight to the heart of the book: a recipe for making a simple 16-page zine with two pieces of paper... books.google.com Once you make your zine, you can start adding text. But soon, you’ll realize something — you need some illustrations! I am a terrible artist, and I could never create an image compelling enough to accompany these computer-generated stories. BigGAN is a Generative Adversarial Network, a powerful synthesis of two separate neural networks working together to create something new. BigGAN works best for image generation, creating images of animals, objects, and people that never existed — they were generated by the AI model itself. SyncedReview wrote more about BigGAN: “All the attention surrounds the paper, Large Scale GAN Training for High Fidelity Natural Image Synthesis, which recently popped up on the social network. The paper is an internship project by Andrew Brock from Heriot-Watt University in collaboration with Jeff Donahue and Karen Simonyan from DeepMind...the model is capable of generating very impressive images with high fidelity and low variety gap.” You can try it at home with this Google Colab notebook, a super-easy way to introduce kids to AI. Simply run the notebook and then use sliders and lists of objects to create something new. My daughter and I spent a whole afternoon running the BigGAN code and generating computer versions of household objects to illustrate our Machine Zines. Once my daughter had chosen the images for the zine, we printed them and pasted them inside our zine. The final product is crooked, homemade, and perfectly human work of art, a way to share GPT-2 writing with fellow humans. Of course, you don’t need to use AI to illustrate your Machine Zine! Another day, I let my 4-year-old son illustrate a Machine Zine. I would read the GPT-2 produced text out-loud and he drew a picture. I loved how the mix of his drawings and AI words turned out. My kid had helped take this story out of a cold digital context and reframe it as something warm, friendly, and human. This was so much more than pushing “GO” button. We collaborated, my family and the AI. There is no way of hiding from this huge change in human and AI relations. The change has already begun, and we need to prepare our children to flourish in a world disrupted by machine learning, neural networks, and other 21st-century digital tools. Instead of being afraid of these changes, we can augment our children’s imaginations, expanding everything they can dream.
[ { "code": null, "e": 235, "s": 172, "text": "Every day, our kids are swept through the world by algorithms." }, { "code": null, "e": 487, "s": 235, "text": "YouTube algorithms decide what videos they watch, GPS algorithms map what route they take to school, Spotify algorithms select what songs they hear, and personal assistants like Siri and Alexa advise them — all of it driven by artificial intelligence." }, { "code": null, "e": 624, "s": 487, "text": "Kids (and adults!) leave these passive engagements with AI without any physical product — just an endless stream of passive consumption." }, { "code": null, "e": 815, "s": 624, "text": "Instead of getting carried away by these digital currents, teachers, parents, and caregivers should show kids how to experiment with powerful tools like machine learning and neural networks." }, { "code": null, "e": 1031, "s": 815, "text": "We must raise kids who are capable of working alongside artificial intelligence in the workplace. The best workers of the future will be able to dictate, scribble, chat, and dream better with the help of technology." }, { "code": null, "e": 1247, "s": 1031, "text": "Future workers will need to demonstrate creativity, flexibility, and comfort with machine learning and algorithmic tools. Through play, we can encourage these skills without sacrificing a sense of analog creativity." }, { "code": null, "e": 1457, "s": 1247, "text": "We can show kids that AI is not a passive feature in their lives. AI is a tool, just as much as a pencil or paper. The real trick is knowing when and why a particular problem calls for a specific digital tool." }, { "code": null, "e": 1577, "s": 1457, "text": "I spent the last six months learning enough code so I could use the superpowered GPT-2 language model to write stories." }, { "code": null, "e": 1844, "s": 1577, "text": "I emerged with 50,000 words of strange and wonderful stories from my AI writing partner. I loved it all, but never found the perfect way to share it with new readers. The text was too strange to publish traditionally and too unwieldy to read as a straight-ahead PDF." }, { "code": null, "e": 2027, "s": 1844, "text": "My daughter ultimately solved the problem for me, bringing home Lunch Money by Andrew Clements, a classic middle-grade novel about a kid who starts selling zines at his grade school." }, { "code": null, "e": 2206, "s": 2027, "text": "You should read the whole novel, but this Google Books link will take you straight to the heart of the book: a recipe for making a simple 16-page zine with two pieces of paper..." }, { "code": null, "e": 2223, "s": 2206, "text": "books.google.com" }, { "code": null, "e": 2365, "s": 2223, "text": "Over the holidays, my daughter and I started making zines together. It was lovely, cutting, pasting, and scribbling inside these bitty books." }, { "code": null, "e": 2516, "s": 2365, "text": "Each zine was a combination of images and text generated artificial intelligence, but they were edited, transcribed, and hand-written by human beings." }, { "code": null, "e": 2602, "s": 2516, "text": "It’s a perfect combination of human and AI creativity — we call them “Machine Zines.”" }, { "code": null, "e": 2817, "s": 2602, "text": "That simple process was a revelation. As I took the time to hand-write my GPT-2 output, I became a participant in the writing process, rather than a passive guy pushing the “Go” button while GPT-2 did all the work." }, { "code": null, "e": 3005, "s": 2817, "text": "I think zines are by far the best medium for sharing GPT-2 output. You can read the zine quickly and the reader won’t get bogged down in the sometimes awkward syntax of AI-generated text." }, { "code": null, "e": 3096, "s": 3005, "text": "If you make your own zines, drop me a line. I’d love to share your work with more readers!" }, { "code": null, "e": 3298, "s": 3096, "text": "You don’t have to spend six months learning how to code to write with GPT-2 or other AI language models. Following these simple steps, you could write your own Machine Zines by the end of this article!" }, { "code": null, "e": 3493, "s": 3298, "text": "Working with the kid in your life, compose one or two sentences — the opening of a story, the first lines of a poem, or the start of a personal essay. That’s all you need. Here’s how we started:" }, { "code": null, "e": 3585, "s": 3493, "text": "A family creates small books with artificial intelligence. They are called \"machine zines.\"" }, { "code": null, "e": 3918, "s": 3585, "text": "Once you have your first few sentences perfected, go to Talk To Transformer. Built by @AdamDanielKing, this website gives you instant access to GPT-2, a superpowered language model trained on eight million web pages. The company OpenAI trained GPT-2 and gradually made the powerful predictive text generator available to the public." }, { "code": null, "e": 4141, "s": 3918, "text": "GPT-2 has a deceptively simple skill set: it can predict what should come next based on a given writing sample. Once you type in the sentences you wrote, Talk To Transformer works like the auto-complete on your smartphone." }, { "code": null, "e": 4360, "s": 4141, "text": "Once you hit that button, GPT-2 will automatically complete your sentences. The output can range from a few sentences to a few paragraphs. Keep clicking “COMPLETE TEXT” until you get enough sentences to fill your zine." }, { "code": null, "e": 4538, "s": 4360, "text": "Now that GPT-2 worked its magic, it’s time for you to write out the text by hand. This adds a human touch to the zine, and gives you a chance to edit the story however you like." }, { "code": null, "e": 4696, "s": 4538, "text": "Cut sentences that don’t make sense, combine sentences, move paragraphs around, and add any words you like. You are the human! You are the boss of this zine!" }, { "code": null, "e": 4848, "s": 4696, "text": "Here’s what our final text looked like after we trimmed the text and moved things around to help express GPT-2’s message about human and AI creativity:" }, { "code": null, "e": 5354, "s": 4848, "text": "The first thing you need to do is stop. And think about what you want to see.Why not have the book do the talking? Why not have the machine sing? Why not have the machine write?A machine can talk to you.A machine can write you stories.They do not understand you.Sometimes a machine will do more. It will follow you from behind, writing stories for you.What will it write if you don't?What will it write if you try to stop it?Remember that it's just there to let you take the first step.What will it write?" }, { "code": null, "e": 5420, "s": 5354, "text": "Now it’s time to make something that only a human being can make." }, { "code": null, "e": 5586, "s": 5420, "text": "Depending on how many pages you have, choose your favorite zine style. There are many different ways to fold zines, and they are all illustrated with amazing videos." }, { "code": null, "e": 5694, "s": 5586, "text": "For instance, the 8-page zine format is really easy and really satisfying once you fold things correctly..." }, { "code": null, "e": 5742, "s": 5694, "text": "This 14-page model is a bit more complicated..." }, { "code": null, "e": 5816, "s": 5742, "text": "My daughter and I used the awesome Lunch Money by Andrew Clements method." }, { "code": null, "e": 5958, "s": 5816, "text": "This Google Books link will take you straight to the heart of the book: a recipe for making a simple 16-page zine with two pieces of paper..." }, { "code": null, "e": 5975, "s": 5958, "text": "books.google.com" }, { "code": null, "e": 6093, "s": 5975, "text": "Once you make your zine, you can start adding text. But soon, you’ll realize something — you need some illustrations!" }, { "code": null, "e": 6216, "s": 6093, "text": "I am a terrible artist, and I could never create an image compelling enough to accompany these computer-generated stories." }, { "code": null, "e": 6508, "s": 6216, "text": "BigGAN is a Generative Adversarial Network, a powerful synthesis of two separate neural networks working together to create something new. BigGAN works best for image generation, creating images of animals, objects, and people that never existed — they were generated by the AI model itself." }, { "code": null, "e": 6546, "s": 6508, "text": "SyncedReview wrote more about BigGAN:" }, { "code": null, "e": 6950, "s": 6546, "text": "“All the attention surrounds the paper, Large Scale GAN Training for High Fidelity Natural Image Synthesis, which recently popped up on the social network. The paper is an internship project by Andrew Brock from Heriot-Watt University in collaboration with Jeff Donahue and Karen Simonyan from DeepMind...the model is capable of generating very impressive images with high fidelity and low variety gap.”" }, { "code": null, "e": 7139, "s": 6950, "text": "You can try it at home with this Google Colab notebook, a super-easy way to introduce kids to AI. Simply run the notebook and then use sliders and lists of objects to create something new." }, { "code": null, "e": 7292, "s": 7139, "text": "My daughter and I spent a whole afternoon running the BigGAN code and generating computer versions of household objects to illustrate our Machine Zines." }, { "code": null, "e": 7394, "s": 7292, "text": "Once my daughter had chosen the images for the zine, we printed them and pasted them inside our zine." }, { "code": null, "e": 7516, "s": 7394, "text": "The final product is crooked, homemade, and perfectly human work of art, a way to share GPT-2 writing with fellow humans." }, { "code": null, "e": 7585, "s": 7516, "text": "Of course, you don’t need to use AI to illustrate your Machine Zine!" }, { "code": null, "e": 7718, "s": 7585, "text": "Another day, I let my 4-year-old son illustrate a Machine Zine. I would read the GPT-2 produced text out-loud and he drew a picture." }, { "code": null, "e": 7898, "s": 7718, "text": "I loved how the mix of his drawings and AI words turned out. My kid had helped take this story out of a cold digital context and reframe it as something warm, friendly, and human." }, { "code": null, "e": 7985, "s": 7898, "text": "This was so much more than pushing “GO” button. We collaborated, my family and the AI." }, { "code": null, "e": 8060, "s": 7985, "text": "There is no way of hiding from this huge change in human and AI relations." }, { "code": null, "e": 8235, "s": 8060, "text": "The change has already begun, and we need to prepare our children to flourish in a world disrupted by machine learning, neural networks, and other 21st-century digital tools." } ]
Tryit Editor v3.7
Tryit: Template 1 - using grid
[]
Spatial Filtering and its Types - GeeksforGeeks
06 Dec, 2019 Spatial Filtering technique is used directly on pixels of an image. Mask is usually considered to be added in size so that it has specific center pixel. This mask is moved on the image such that the center of the mask traverses all image pixels. Classification on the basis of linearity:There are two types: 1. Linear Spatial Filter 2. Non-linear Spatial Filter General Classification: Smoothing Spatial Filter: Smoothing filter is used for blurring and noise reduction in the image. Blurring is pre-processing steps for removal of small details and Noise Reduction is accomplished by blurring. Types of Smoothing Spatial Filter: 1. Linear Filter (Mean Filter) 2. Order Statistics (Non-linear) filter These are explained as following below. Mean Filter:Linear spatial filter is simply the average of the pixels contained in the neighborhood of the filter mask. The idea is replacing the value of every pixel in an image by the average of the grey levels in the neighborhood define by the filter mask.Types of Mean filter:(i) Averaging filter: It is used in reduction of the detail in image. All coefficients are equal.(ii) Weighted averaging filter: In this, pixels are multiplied by different coefficients. Center pixel is multiplied by a higher value than average filter.Order Statistics Filter:It is based on the ordering the pixels contained in the image area encompassed by the filter. It replaces the value of the center pixel with the value determined by the ranking result. Edges are better preserved in this filtering.Types of Order statistics filter:(i) Minimum filter: 0th percentile filter is the minimum filter. The value of the center is replaced by the smallest value in the window.(ii) Maximum filter: 100th percentile filter is the maximum filter. The value of the center is replaced by the largest value in the window.(iii) Median filter: Each pixel in the image is considered. First neighboring pixels are sorted and original values of the pixel is replaced by the median of the list. Mean Filter:Linear spatial filter is simply the average of the pixels contained in the neighborhood of the filter mask. The idea is replacing the value of every pixel in an image by the average of the grey levels in the neighborhood define by the filter mask.Types of Mean filter:(i) Averaging filter: It is used in reduction of the detail in image. All coefficients are equal.(ii) Weighted averaging filter: In this, pixels are multiplied by different coefficients. Center pixel is multiplied by a higher value than average filter. Types of Mean filter: (i) Averaging filter: It is used in reduction of the detail in image. All coefficients are equal. (ii) Weighted averaging filter: In this, pixels are multiplied by different coefficients. Center pixel is multiplied by a higher value than average filter. Order Statistics Filter:It is based on the ordering the pixels contained in the image area encompassed by the filter. It replaces the value of the center pixel with the value determined by the ranking result. Edges are better preserved in this filtering.Types of Order statistics filter:(i) Minimum filter: 0th percentile filter is the minimum filter. The value of the center is replaced by the smallest value in the window.(ii) Maximum filter: 100th percentile filter is the maximum filter. The value of the center is replaced by the largest value in the window.(iii) Median filter: Each pixel in the image is considered. First neighboring pixels are sorted and original values of the pixel is replaced by the median of the list. Types of Order statistics filter: (i) Minimum filter: 0th percentile filter is the minimum filter. The value of the center is replaced by the smallest value in the window. (ii) Maximum filter: 100th percentile filter is the maximum filter. The value of the center is replaced by the largest value in the window. (iii) Median filter: Each pixel in the image is considered. First neighboring pixels are sorted and original values of the pixel is replaced by the median of the list. Sharpening Spatial Filter: It is also known as derivative filter. The purpose of the sharpening spatial filter is just the opposite of the smoothing spatial filter. Its main focus in on the removal of blurring and highlight the edges. It is based on the first and second order derivative. First order derivative: Must be zero in flat segments. Must be non zero at the onset of a grey level step. Must be non zero along ramps. First order derivative in 1-D is given by: f' = f(x+1) - f(x) Second order derivative: Must be zero in flat areas. Must be zero at the onset and end of a ramp. Must be zero along ramps. Second order derivative in 1-D is given by: f'' = f(x+1) + f(x-1) - 2f(x) computer-graphics Image-Processing Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 How to write Regular Expressions? fgets() and gets() in C language Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move) Association Rule Recursive Functions Software Engineering | Prototyping Model Java Math min() method with Examples Set add() method in Java with Examples OOPs | Object Oriented Design
[ { "code": null, "e": 24552, "s": 24524, "text": "\n06 Dec, 2019" }, { "code": null, "e": 24798, "s": 24552, "text": "Spatial Filtering technique is used directly on pixels of an image. Mask is usually considered to be added in size so that it has specific center pixel. This mask is moved on the image such that the center of the mask traverses all image pixels." }, { "code": null, "e": 24860, "s": 24798, "text": "Classification on the basis of linearity:There are two types:" }, { "code": null, "e": 24915, "s": 24860, "text": "1. Linear Spatial Filter\n2. Non-linear Spatial Filter " }, { "code": null, "e": 24939, "s": 24915, "text": "General Classification:" }, { "code": null, "e": 25148, "s": 24939, "text": "Smoothing Spatial Filter: Smoothing filter is used for blurring and noise reduction in the image. Blurring is pre-processing steps for removal of small details and Noise Reduction is accomplished by blurring." }, { "code": null, "e": 25183, "s": 25148, "text": "Types of Smoothing Spatial Filter:" }, { "code": null, "e": 25255, "s": 25183, "text": "1. Linear Filter (Mean Filter)\n2. Order Statistics (Non-linear) filter " }, { "code": null, "e": 25295, "s": 25255, "text": "These are explained as following below." }, { "code": null, "e": 26558, "s": 25295, "text": "Mean Filter:Linear spatial filter is simply the average of the pixels contained in the neighborhood of the filter mask. The idea is replacing the value of every pixel in an image by the average of the grey levels in the neighborhood define by the filter mask.Types of Mean filter:(i) Averaging filter: It is used in reduction of the detail in image. All coefficients are equal.(ii) Weighted averaging filter: In this, pixels are multiplied by different coefficients. Center pixel is multiplied by a higher value than average filter.Order Statistics Filter:It is based on the ordering the pixels contained in the image area encompassed by the filter. It replaces the value of the center pixel with the value determined by the ranking result. Edges are better preserved in this filtering.Types of Order statistics filter:(i) Minimum filter: 0th percentile filter is the minimum filter. The value of the center is replaced by the smallest value in the window.(ii) Maximum filter: 100th percentile filter is the maximum filter. The value of the center is replaced by the largest value in the window.(iii) Median filter: Each pixel in the image is considered. First neighboring pixels are sorted and original values of the pixel is replaced by the median of the list." }, { "code": null, "e": 27091, "s": 26558, "text": "Mean Filter:Linear spatial filter is simply the average of the pixels contained in the neighborhood of the filter mask. The idea is replacing the value of every pixel in an image by the average of the grey levels in the neighborhood define by the filter mask.Types of Mean filter:(i) Averaging filter: It is used in reduction of the detail in image. All coefficients are equal.(ii) Weighted averaging filter: In this, pixels are multiplied by different coefficients. Center pixel is multiplied by a higher value than average filter." }, { "code": null, "e": 27113, "s": 27091, "text": "Types of Mean filter:" }, { "code": null, "e": 27211, "s": 27113, "text": "(i) Averaging filter: It is used in reduction of the detail in image. All coefficients are equal." }, { "code": null, "e": 27367, "s": 27211, "text": "(ii) Weighted averaging filter: In this, pixels are multiplied by different coefficients. Center pixel is multiplied by a higher value than average filter." }, { "code": null, "e": 28098, "s": 27367, "text": "Order Statistics Filter:It is based on the ordering the pixels contained in the image area encompassed by the filter. It replaces the value of the center pixel with the value determined by the ranking result. Edges are better preserved in this filtering.Types of Order statistics filter:(i) Minimum filter: 0th percentile filter is the minimum filter. The value of the center is replaced by the smallest value in the window.(ii) Maximum filter: 100th percentile filter is the maximum filter. The value of the center is replaced by the largest value in the window.(iii) Median filter: Each pixel in the image is considered. First neighboring pixels are sorted and original values of the pixel is replaced by the median of the list." }, { "code": null, "e": 28132, "s": 28098, "text": "Types of Order statistics filter:" }, { "code": null, "e": 28270, "s": 28132, "text": "(i) Minimum filter: 0th percentile filter is the minimum filter. The value of the center is replaced by the smallest value in the window." }, { "code": null, "e": 28410, "s": 28270, "text": "(ii) Maximum filter: 100th percentile filter is the maximum filter. The value of the center is replaced by the largest value in the window." }, { "code": null, "e": 28578, "s": 28410, "text": "(iii) Median filter: Each pixel in the image is considered. First neighboring pixels are sorted and original values of the pixel is replaced by the median of the list." }, { "code": null, "e": 28867, "s": 28578, "text": "Sharpening Spatial Filter: It is also known as derivative filter. The purpose of the sharpening spatial filter is just the opposite of the smoothing spatial filter. Its main focus in on the removal of blurring and highlight the edges. It is based on the first and second order derivative." }, { "code": null, "e": 28891, "s": 28867, "text": "First order derivative:" }, { "code": null, "e": 28922, "s": 28891, "text": "Must be zero in flat segments." }, { "code": null, "e": 28974, "s": 28922, "text": "Must be non zero at the onset of a grey level step." }, { "code": null, "e": 29004, "s": 28974, "text": "Must be non zero along ramps." }, { "code": null, "e": 29047, "s": 29004, "text": "First order derivative in 1-D is given by:" }, { "code": null, "e": 29066, "s": 29047, "text": "f' = f(x+1) - f(x)" }, { "code": null, "e": 29091, "s": 29066, "text": "Second order derivative:" }, { "code": null, "e": 29119, "s": 29091, "text": "Must be zero in flat areas." }, { "code": null, "e": 29164, "s": 29119, "text": "Must be zero at the onset and end of a ramp." }, { "code": null, "e": 29190, "s": 29164, "text": "Must be zero along ramps." }, { "code": null, "e": 29234, "s": 29190, "text": "Second order derivative in 1-D is given by:" }, { "code": null, "e": 29264, "s": 29234, "text": "f'' = f(x+1) + f(x-1) - 2f(x)" }, { "code": null, "e": 29282, "s": 29264, "text": "computer-graphics" }, { "code": null, "e": 29299, "s": 29282, "text": "Image-Processing" }, { "code": null, "e": 29304, "s": 29299, "text": "Misc" }, { "code": null, "e": 29309, "s": 29304, "text": "Misc" }, { "code": null, "e": 29314, "s": 29309, "text": "Misc" }, { "code": null, "e": 29412, "s": 29314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29421, "s": 29412, "text": "Comments" }, { "code": null, "e": 29434, "s": 29421, "text": "Old Comments" }, { "code": null, "e": 29479, "s": 29434, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 29513, "s": 29479, "text": "How to write Regular Expressions?" }, { "code": null, "e": 29546, "s": 29513, "text": "fgets() and gets() in C language" }, { "code": null, "e": 29627, "s": 29546, "text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)" }, { "code": null, "e": 29644, "s": 29627, "text": "Association Rule" }, { "code": null, "e": 29664, "s": 29644, "text": "Recursive Functions" }, { "code": null, "e": 29705, "s": 29664, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 29742, "s": 29705, "text": "Java Math min() method with Examples" }, { "code": null, "e": 29781, "s": 29742, "text": "Set add() method in Java with Examples" } ]
Build your own deep learning image classification model in Keras | by Edward Jones | Towards Data Science
Image classification is a field of artificial intelligence that is gaining in popularity in the latest years. It has various applications: self-driving cars, face recognition, augmented reality,... . In this article, you will learn how to build a deep learning image classification model that is able to detect which objects are present in an image in 10 steps. The full code is available in a shared google collab so you can easily code along while reading the article. After reading this guide, you will know the following things: How to set up an coding environment made for deep learning models. How to connect with a popular image classification dataset (Pascal VOC) How to create a deep learning convolutional neural network using the combination of Keras & Tensorflow How to efficiently train a deep learning model using a datagenerator How to evaluate the datagenerator performance Please check the google collab for the required packages. Building a deep learning convolutional network from scratch requires huge amounts of computing power. Ordinary laptops are not equipped to handle these requests. Luckily, Google comes to our rescue! They have developed an online python notebook which gives users free computing power. You can enable the computing power feature by select the GPU option in the notebook settings. We will use the Pascal VOC image dataset for our deep learning model. The Pascal VOC dataset is an image dataset and is a very popular for computer vision competitions on Kaggle. Use the Wget package to download the dataset. This package fetches the data and downloads it to your current working directory. import tarfile!wget -nc http://host.robots.ox.ac.uk/pascal/VOC/voc2009/VOCtrainval_11-May-2009.tar As a last step, you open the tarfile and extract it. tf = tarfile.open("/content/VOCtrainval_11-May-2009.tar")tf.extractall() Good job! You have now successfully loaded in and extracted the dataset. The current data structure is not optimal for building deep learning convolutional models. Therefore, the data needs to be transformed to a more workable format. The Pascal VOC dataset that you extracted should contain the two following folders: Annotations: This folder contains all the information about the image labels. JPEGImages: This folder contains all the raw images Create two lists: Filenames: In this list, you save all the filenames of the pictures. Eg. “2208–001068.jpeg” Classification: In this list, you save all of the classification labels. Eg. “Bicycle, Sofa” directory_annotations = '/content/VOCdevkit/VOC2009/Annotations'filenames = []classification = [] You iterate over the annotations directory and extract the filename and label and add it to the respective lists. for xml_file in os.listdir(directory_annotations): # Save image for classification and their class label if os.path.isfile(xml_file): xml_tree = ET.parse(xml_file) root = xml_tree.getroot() imgname = root.find('filename').text.strip('.jpg') labels = [] for obj in root.findall('object'): label = obj.find('name').text labels.append(label) filenames.append(imgname) classification.append(labels) In this step, you will have to preprocess the data: Split the up the filenames and their respective classification in a training and test set. label_filenames_temp = os.listdir(directory_annotations)filenames = []for lbl in label_filenames_temp: filenames.append(lbl.split('.')[0])filecount = len(filenames)indexes = []for index in range(filecount): indexes.append(index)training_indexes = indexes[:int(filecount*0.7)]validation_indexes = indexes[int(filecount*0.7):int(filecount*0.9)]testing_indexes = indexes[int(filecount*0.9):] The output labels needs to be converted to numeric values since deep learning networks perform better when the input and output variables are numbers. directory_images = '/content/VOCdevkit/VOC2009/JPEGImages'directory_annotations = '/content/VOCdevkit/VOC2009/Annotations'labelnames = preprocessing.LabelEncoder()labelnames.fit(["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]) The images are resized to the 224,224,3 format. Literature review advises this when building a deep learning network based on the VGG16 model archtiecture. (Simonyan & Zisserman, 2014) def generate_from_xml(filename):label = np.zeros((20), dtype = 'float32')tree = ET.parse(os.path.join(directory_annotations, filename + ".xml"))raw_image = cv2.imread(os.path.join(directory_images, filename + ".jpg"))res_img = cv2.resize(raw_image, (224,224)) for elems in tree.iter(): if elems.tag == "object": name = elems.find("name").text labelnr = labelnames.transform([name])[0] label[labelnr] = 1return label, res_img Training a model on huge datasets requires huge amounts of ram memory. If you are like me and are not in possession of a supercomputer, you have to use a datagenerator. A datagenerator feeds the data in small batches to the model. This allows us to train our model without having huge amounts of ram memory. It is best practice to use a datagenerator when using big datasets (opposed to buying more ram memory). The details of a datagenerator are out of scope in this article but feel free to check out the following link if you are interested. In the next code block, you create a datagenerator class instance and call it twice: One time for the training set One time for the validation set In this step, you will build the architecture of the classification convolutional neural network. The model architecture is based on the popular VGG-16 architecture. This is a CNN with a total of 13 convolutional layers (cfr. figure 1). The following code block indicates that you will be building the model in a sequential way. This means that you will layer after layer. model = Sequential() You add 2 convolutional layers.In the convolutional layers, multiple filters are applied to the image to extract different features. Arguments given: - Input-shape: The image given should be of the shape (224,224,3). - Filters: The number of filters that the convolutional layer will learn. - Kernel_size: specifies the width and height of the 2D convolution window. - Padding: Specifying “same” ensures that the spatial dimensions are the same after the convolution. - Activation: This is more of a convenience argument. Here, we specify which activation function will be applied after the convolutional layers. We will apply the ReLU activation function. More on this later. model.add(Conv2D(input_shape=(224,224,3),filters=64,kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu")) Next, you add 1 maxpool layer. Pooling is used to reduce the dimensionality of images by reducing the number of pixels in the output of the previous convolutional layer. - Pool_size= 2,2 -> this is the ‘matrix’ that will go over the output and where the maximum value is taken from - strides= 2,2 -> the increment of how the pool matrix will move along x & y -axis. model.add(MaxPool2D(pool_size=(2,2),strides=(2,2))) We continue to add layers to our deep learning network. The same logic as described above is applied. model.add(Conv2D(filters=128, kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=128, kernel_size=(3,3),padding="same", activation="relu"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))model.add(Conv2D(filters=256, kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=256, kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=256, kernel_size=(3,3),padding="same", activation="relu"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))model.add(Conv2D(filters=512, kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding="same", activation="relu"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))model.add(Conv2D(filters=512, kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding="same", activation="relu"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding="same", activation="relu"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2))) Now the convolutional base is created. To be able to generate a prediction, you have to flatten the output of the convolutional base. model.add(Flatten()) Add the dense layers. The dense layers feeds the output of the convolutional base to its neurons. Arguments: - Units: Number of neurons - Activation function: Relu The Relu activation function speeds up training since the gradient computation is very simple (0 or 1). This also implies that negative values are not passed or “activated” on to the next layer. This makes that only a certain number of neurons are activated which makes it computationally interesting. model.add(Dense(units=4096,activation="relu"))model.add(Dense(units=4096,activation="relu")) You add a sigmoid layer in order to turn the output of the previous layer into a probability distribution. The sigmoid is ideal for multi label classification so that is why we used sigmoid instead of for example a softmax activation. The probabilities produced by a sigmoid are independent and are not constrained to sum to one. This is crucial in a classification with multiple output labels. You set the units argument to 20 since we have 20 possible classes. model.add(Dense(units=20, activation="sigmoid")) In step 7, you have to compile the model. You use the RMSprop optimier to be able to reach the global minima. You set the learning rate at 0.001. RMSprop, root mean square prop, is an unpublished optimization algorithm but is very popular by machine learning practitioners. It reduces the fluctuations in the vertical direction while speeding up the learning in the horizontal direction. This causes our model to converge faster to a global minima. The main difference with the regular gradient descent algorithm is how the gradients are calculated. The formula of the calculation of the gradients is shown in the figure below. You set the binary cross-entropy loss as your loss function. It is recommended to use this loss function for a multi-label classification since each element belonging to a certain class should not be influenced by the decision for another class. model.compile(optimizer= keras.optimizers.RMSprop(lr=0.001), loss='binary_crossentropy',metrics=['accuracy'])model.summary() You use the earlystopping method to stop the training once the model performance stops improving on a hold out dataset. In this way, you automatically have the perfect number of epochs while monitoring overfitting. You give the earlystopping the instructions to seek a minimum for the validation loss. The earlystopping method only stops training when no further improvement is detected. However, the last epoch is not necessarily the one with the best performance. Therefore, you also use the model checkpoint method. This will save the best model observed during the training based on the validation loss. filepath = "/content/drive/My Drive/MYCNN/CNN1505_v1.h5"earlyStopping = EarlyStopping(monitor='val_loss', verbose=0, mode='min', patience = 4)mcp_save = ModelCheckpoint(filepath, save_best_only=True, monitor='val_loss', mode='min') Now, you will start training our deep learning neural network. We use the fit generator from keras to load in the data in batches.This is necessary since our entire training set doesn’t fit in our RAM. You set the following arguments: Use multiprocessing: Whether to use process-based threading Workers: Number of threads generating batches in parallel. history = model.fit_generator(generator=training_generator,validation_data=val_generator,use_multiprocessing=True,workers=6,epochs = 20,callbacks=[earlyStopping, mcp_save]) When our training has finished, you visualize our training and validation results. Two metrics are plotted: Model accuracy Model loss You see that the model quickly converged from a huge training loss in the first epoch to lower numbers. This fast learning rate is due to the nature of the optimizer chosen (RMS prop) which speeds up convergence.The training process picks the model with the lowest validation loss when this metric has not been improved over four epochs. df = pd.DataFrame(history.history)print(history.history.keys())# summarize history for accuracyplt.plot(history.history['accuracy'])plt.plot(history.history['val_accuracy'])plt.title('model accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.show()# summarize history for lossplt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.show() In our final step, we test our model performance on unseen data (test set).
[ { "code": null, "e": 372, "s": 172, "text": "Image classification is a field of artificial intelligence that is gaining in popularity in the latest years. It has various applications: self-driving cars, face recognition, augmented reality,... ." }, { "code": null, "e": 534, "s": 372, "text": "In this article, you will learn how to build a deep learning image classification model that is able to detect which objects are present in an image in 10 steps." }, { "code": null, "e": 643, "s": 534, "text": "The full code is available in a shared google collab so you can easily code along while reading the article." }, { "code": null, "e": 705, "s": 643, "text": "After reading this guide, you will know the following things:" }, { "code": null, "e": 772, "s": 705, "text": "How to set up an coding environment made for deep learning models." }, { "code": null, "e": 844, "s": 772, "text": "How to connect with a popular image classification dataset (Pascal VOC)" }, { "code": null, "e": 947, "s": 844, "text": "How to create a deep learning convolutional neural network using the combination of Keras & Tensorflow" }, { "code": null, "e": 1016, "s": 947, "text": "How to efficiently train a deep learning model using a datagenerator" }, { "code": null, "e": 1062, "s": 1016, "text": "How to evaluate the datagenerator performance" }, { "code": null, "e": 1120, "s": 1062, "text": "Please check the google collab for the required packages." }, { "code": null, "e": 1282, "s": 1120, "text": "Building a deep learning convolutional network from scratch requires huge amounts of computing power. Ordinary laptops are not equipped to handle these requests." }, { "code": null, "e": 1405, "s": 1282, "text": "Luckily, Google comes to our rescue! They have developed an online python notebook which gives users free computing power." }, { "code": null, "e": 1499, "s": 1405, "text": "You can enable the computing power feature by select the GPU option in the notebook settings." }, { "code": null, "e": 1569, "s": 1499, "text": "We will use the Pascal VOC image dataset for our deep learning model." }, { "code": null, "e": 1678, "s": 1569, "text": "The Pascal VOC dataset is an image dataset and is a very popular for computer vision competitions on Kaggle." }, { "code": null, "e": 1806, "s": 1678, "text": "Use the Wget package to download the dataset. This package fetches the data and downloads it to your current working directory." }, { "code": null, "e": 1905, "s": 1806, "text": "import tarfile!wget -nc http://host.robots.ox.ac.uk/pascal/VOC/voc2009/VOCtrainval_11-May-2009.tar" }, { "code": null, "e": 1958, "s": 1905, "text": "As a last step, you open the tarfile and extract it." }, { "code": null, "e": 2031, "s": 1958, "text": "tf = tarfile.open(\"/content/VOCtrainval_11-May-2009.tar\")tf.extractall()" }, { "code": null, "e": 2104, "s": 2031, "text": "Good job! You have now successfully loaded in and extracted the dataset." }, { "code": null, "e": 2266, "s": 2104, "text": "The current data structure is not optimal for building deep learning convolutional models. Therefore, the data needs to be transformed to a more workable format." }, { "code": null, "e": 2350, "s": 2266, "text": "The Pascal VOC dataset that you extracted should contain the two following folders:" }, { "code": null, "e": 2428, "s": 2350, "text": "Annotations: This folder contains all the information about the image labels." }, { "code": null, "e": 2480, "s": 2428, "text": "JPEGImages: This folder contains all the raw images" }, { "code": null, "e": 2498, "s": 2480, "text": "Create two lists:" }, { "code": null, "e": 2590, "s": 2498, "text": "Filenames: In this list, you save all the filenames of the pictures. Eg. “2208–001068.jpeg”" }, { "code": null, "e": 2683, "s": 2590, "text": "Classification: In this list, you save all of the classification labels. Eg. “Bicycle, Sofa”" }, { "code": null, "e": 2781, "s": 2683, "text": "directory_annotations = '/content/VOCdevkit/VOC2009/Annotations'filenames = []classification = []" }, { "code": null, "e": 2895, "s": 2781, "text": "You iterate over the annotations directory and extract the filename and label and add it to the respective lists." }, { "code": null, "e": 3323, "s": 2895, "text": "for xml_file in os.listdir(directory_annotations): # Save image for classification and their class label if os.path.isfile(xml_file): xml_tree = ET.parse(xml_file) root = xml_tree.getroot() imgname = root.find('filename').text.strip('.jpg') labels = [] for obj in root.findall('object'): label = obj.find('name').text labels.append(label) filenames.append(imgname) classification.append(labels)" }, { "code": null, "e": 3375, "s": 3323, "text": "In this step, you will have to preprocess the data:" }, { "code": null, "e": 3466, "s": 3375, "text": "Split the up the filenames and their respective classification in a training and test set." }, { "code": null, "e": 3862, "s": 3466, "text": "label_filenames_temp = os.listdir(directory_annotations)filenames = []for lbl in label_filenames_temp: filenames.append(lbl.split('.')[0])filecount = len(filenames)indexes = []for index in range(filecount): indexes.append(index)training_indexes = indexes[:int(filecount*0.7)]validation_indexes = indexes[int(filecount*0.7):int(filecount*0.9)]testing_indexes = indexes[int(filecount*0.9):]" }, { "code": null, "e": 4013, "s": 3862, "text": "The output labels needs to be converted to numeric values since deep learning networks perform better when the input and output variables are numbers." }, { "code": null, "e": 4388, "s": 4013, "text": "directory_images = '/content/VOCdevkit/VOC2009/JPEGImages'directory_annotations = '/content/VOCdevkit/VOC2009/Annotations'labelnames = preprocessing.LabelEncoder()labelnames.fit([\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"])" }, { "code": null, "e": 4573, "s": 4388, "text": "The images are resized to the 224,224,3 format. Literature review advises this when building a deep learning network based on the VGG16 model archtiecture. (Simonyan & Zisserman, 2014)" }, { "code": null, "e": 5043, "s": 4573, "text": "def generate_from_xml(filename):label = np.zeros((20), dtype = 'float32')tree = ET.parse(os.path.join(directory_annotations, filename + \".xml\"))raw_image = cv2.imread(os.path.join(directory_images, filename + \".jpg\"))res_img = cv2.resize(raw_image, (224,224)) for elems in tree.iter(): if elems.tag == \"object\": name = elems.find(\"name\").text labelnr = labelnames.transform([name])[0] label[labelnr] = 1return label, res_img" }, { "code": null, "e": 5114, "s": 5043, "text": "Training a model on huge datasets requires huge amounts of ram memory." }, { "code": null, "e": 5212, "s": 5114, "text": "If you are like me and are not in possession of a supercomputer, you have to use a datagenerator." }, { "code": null, "e": 5351, "s": 5212, "text": "A datagenerator feeds the data in small batches to the model. This allows us to train our model without having huge amounts of ram memory." }, { "code": null, "e": 5588, "s": 5351, "text": "It is best practice to use a datagenerator when using big datasets (opposed to buying more ram memory). The details of a datagenerator are out of scope in this article but feel free to check out the following link if you are interested." }, { "code": null, "e": 5673, "s": 5588, "text": "In the next code block, you create a datagenerator class instance and call it twice:" }, { "code": null, "e": 5703, "s": 5673, "text": "One time for the training set" }, { "code": null, "e": 5735, "s": 5703, "text": "One time for the validation set" }, { "code": null, "e": 5833, "s": 5735, "text": "In this step, you will build the architecture of the classification convolutional neural network." }, { "code": null, "e": 5972, "s": 5833, "text": "The model architecture is based on the popular VGG-16 architecture. This is a CNN with a total of 13 convolutional layers (cfr. figure 1)." }, { "code": null, "e": 6108, "s": 5972, "text": "The following code block indicates that you will be building the model in a sequential way. This means that you will layer after layer." }, { "code": null, "e": 6129, "s": 6108, "text": "model = Sequential()" }, { "code": null, "e": 6262, "s": 6129, "text": "You add 2 convolutional layers.In the convolutional layers, multiple filters are applied to the image to extract different features." }, { "code": null, "e": 6279, "s": 6262, "text": "Arguments given:" }, { "code": null, "e": 6346, "s": 6279, "text": "- Input-shape: The image given should be of the shape (224,224,3)." }, { "code": null, "e": 6420, "s": 6346, "text": "- Filters: The number of filters that the convolutional layer will learn." }, { "code": null, "e": 6496, "s": 6420, "text": "- Kernel_size: specifies the width and height of the 2D convolution window." }, { "code": null, "e": 6597, "s": 6496, "text": "- Padding: Specifying “same” ensures that the spatial dimensions are the same after the convolution." }, { "code": null, "e": 6806, "s": 6597, "text": "- Activation: This is more of a convenience argument. Here, we specify which activation function will be applied after the convolutional layers. We will apply the ReLU activation function. More on this later." }, { "code": null, "e": 6993, "s": 6806, "text": "model.add(Conv2D(input_shape=(224,224,3),filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))" }, { "code": null, "e": 7024, "s": 6993, "text": "Next, you add 1 maxpool layer." }, { "code": null, "e": 7163, "s": 7024, "text": "Pooling is used to reduce the dimensionality of images by reducing the number of pixels in the output of the previous convolutional layer." }, { "code": null, "e": 7275, "s": 7163, "text": "- Pool_size= 2,2 -> this is the ‘matrix’ that will go over the output and where the maximum value is taken from" }, { "code": null, "e": 7359, "s": 7275, "text": "- strides= 2,2 -> the increment of how the pool matrix will move along x & y -axis." }, { "code": null, "e": 7411, "s": 7359, "text": "model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))" }, { "code": null, "e": 7513, "s": 7411, "text": "We continue to add layers to our deep learning network. The same logic as described above is applied." }, { "code": null, "e": 8631, "s": 7513, "text": "model.add(Conv2D(filters=128, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=128, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))model.add(Conv2D(filters=256, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=256, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=256, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))model.add(Conv2D(filters=512, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))model.add(Conv2D(filters=512, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(Conv2D(filters=512, kernel_size=(3,3),padding=\"same\", activation=\"relu\"))model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))" }, { "code": null, "e": 8765, "s": 8631, "text": "Now the convolutional base is created. To be able to generate a prediction, you have to flatten the output of the convolutional base." }, { "code": null, "e": 8786, "s": 8765, "text": "model.add(Flatten())" }, { "code": null, "e": 8884, "s": 8786, "text": "Add the dense layers. The dense layers feeds the output of the convolutional base to its neurons." }, { "code": null, "e": 8895, "s": 8884, "text": "Arguments:" }, { "code": null, "e": 8922, "s": 8895, "text": "- Units: Number of neurons" }, { "code": null, "e": 8950, "s": 8922, "text": "- Activation function: Relu" }, { "code": null, "e": 9252, "s": 8950, "text": "The Relu activation function speeds up training since the gradient computation is very simple (0 or 1). This also implies that negative values are not passed or “activated” on to the next layer. This makes that only a certain number of neurons are activated which makes it computationally interesting." }, { "code": null, "e": 9345, "s": 9252, "text": "model.add(Dense(units=4096,activation=\"relu\"))model.add(Dense(units=4096,activation=\"relu\"))" }, { "code": null, "e": 9580, "s": 9345, "text": "You add a sigmoid layer in order to turn the output of the previous layer into a probability distribution. The sigmoid is ideal for multi label classification so that is why we used sigmoid instead of for example a softmax activation." }, { "code": null, "e": 9740, "s": 9580, "text": "The probabilities produced by a sigmoid are independent and are not constrained to sum to one. This is crucial in a classification with multiple output labels." }, { "code": null, "e": 9808, "s": 9740, "text": "You set the units argument to 20 since we have 20 possible classes." }, { "code": null, "e": 9857, "s": 9808, "text": "model.add(Dense(units=20, activation=\"sigmoid\"))" }, { "code": null, "e": 10003, "s": 9857, "text": "In step 7, you have to compile the model. You use the RMSprop optimier to be able to reach the global minima. You set the learning rate at 0.001." }, { "code": null, "e": 10485, "s": 10003, "text": "RMSprop, root mean square prop, is an unpublished optimization algorithm but is very popular by machine learning practitioners. It reduces the fluctuations in the vertical direction while speeding up the learning in the horizontal direction. This causes our model to converge faster to a global minima. The main difference with the regular gradient descent algorithm is how the gradients are calculated. The formula of the calculation of the gradients is shown in the figure below." }, { "code": null, "e": 10731, "s": 10485, "text": "You set the binary cross-entropy loss as your loss function. It is recommended to use this loss function for a multi-label classification since each element belonging to a certain class should not be influenced by the decision for another class." }, { "code": null, "e": 10856, "s": 10731, "text": "model.compile(optimizer= keras.optimizers.RMSprop(lr=0.001), loss='binary_crossentropy',metrics=['accuracy'])model.summary()" }, { "code": null, "e": 11071, "s": 10856, "text": "You use the earlystopping method to stop the training once the model performance stops improving on a hold out dataset. In this way, you automatically have the perfect number of epochs while monitoring overfitting." }, { "code": null, "e": 11158, "s": 11071, "text": "You give the earlystopping the instructions to seek a minimum for the validation loss." }, { "code": null, "e": 11244, "s": 11158, "text": "The earlystopping method only stops training when no further improvement is detected." }, { "code": null, "e": 11322, "s": 11244, "text": "However, the last epoch is not necessarily the one with the best performance." }, { "code": null, "e": 11464, "s": 11322, "text": "Therefore, you also use the model checkpoint method. This will save the best model observed during the training based on the validation loss." }, { "code": null, "e": 11696, "s": 11464, "text": "filepath = \"/content/drive/My Drive/MYCNN/CNN1505_v1.h5\"earlyStopping = EarlyStopping(monitor='val_loss', verbose=0, mode='min', patience = 4)mcp_save = ModelCheckpoint(filepath, save_best_only=True, monitor='val_loss', mode='min')" }, { "code": null, "e": 11898, "s": 11696, "text": "Now, you will start training our deep learning neural network. We use the fit generator from keras to load in the data in batches.This is necessary since our entire training set doesn’t fit in our RAM." }, { "code": null, "e": 11931, "s": 11898, "text": "You set the following arguments:" }, { "code": null, "e": 11991, "s": 11931, "text": "Use multiprocessing: Whether to use process-based threading" }, { "code": null, "e": 12050, "s": 11991, "text": "Workers: Number of threads generating batches in parallel." }, { "code": null, "e": 12223, "s": 12050, "text": "history = model.fit_generator(generator=training_generator,validation_data=val_generator,use_multiprocessing=True,workers=6,epochs = 20,callbacks=[earlyStopping, mcp_save])" }, { "code": null, "e": 12331, "s": 12223, "text": "When our training has finished, you visualize our training and validation results. Two metrics are plotted:" }, { "code": null, "e": 12346, "s": 12331, "text": "Model accuracy" }, { "code": null, "e": 12357, "s": 12346, "text": "Model loss" }, { "code": null, "e": 12695, "s": 12357, "text": "You see that the model quickly converged from a huge training loss in the first epoch to lower numbers. This fast learning rate is due to the nature of the optimizer chosen (RMS prop) which speeds up convergence.The training process picks the model with the lowest validation loss when this metric has not been improved over four epochs." }, { "code": null, "e": 13209, "s": 12695, "text": "df = pd.DataFrame(history.history)print(history.history.keys())# summarize history for accuracyplt.plot(history.history['accuracy'])plt.plot(history.history['val_accuracy'])plt.title('model accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.show()# summarize history for lossplt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('model loss')plt.ylabel('loss')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.show()" } ]
Splitting Arrays in NumPy - GeeksforGeeks
10 May, 2020 Array splitting can be vertical, horizontal, or depth-wise. We can use functions hsplit(), vsplit() and dsplit() respectively for the same . We can split arrays into arrays of the same shape by indicating the position after which the split should occur. Horizontal splitting: The ‘hsplit()’ function splits an array along axis parameter = 1. ‘numpy.hsplit’ is equivalent to ‘split’ with axis parameter = 1, the array is always splitted along the second axis regardless of the array dimension. This function split an array into multiple sub-arrays horizontally (column-wise).Syntax:numpy.hsplit(ary, indices_or_sections)Example:# Horizontal array splitting using np.hsplit()import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Horizontal splitting of array # 'a' using np.hsplit().print("The array {} gets splitted \horizontally to form {} ".format(a, np.hsplit(a, 3))) # Horizontal splitting of array 'a' # using 'split' with axis parameter = 1.print("The array {} gets splitted \horizontally to form {} ".format(a, np.split(a, 3, 1)))Output: The array [[0 1 2] [3 4 5] [6 7 8]] gets splitted horizontally to form [array([[0], [3], [6]]), array([[1], [4], [7]]), array([[2], [5], [8]])] The array [[0 1 2] [3 4 5] [6 7 8]] gets splitted horizontally to form [array([[0], [3], [6]]), array([[1], [4], [7]]), array([[2], [5], [8]])] Syntax: numpy.hsplit(ary, indices_or_sections) Example: # Horizontal array splitting using np.hsplit()import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Horizontal splitting of array # 'a' using np.hsplit().print("The array {} gets splitted \horizontally to form {} ".format(a, np.hsplit(a, 3))) # Horizontal splitting of array 'a' # using 'split' with axis parameter = 1.print("The array {} gets splitted \horizontally to form {} ".format(a, np.split(a, 3, 1))) Output: The array [[0 1 2] [3 4 5] [6 7 8]] gets splitted horizontally to form [array([[0], [3], [6]]), array([[1], [4], [7]]), array([[2], [5], [8]])] The array [[0 1 2] [3 4 5] [6 7 8]] gets splitted horizontally to form [array([[0], [3], [6]]), array([[1], [4], [7]]), array([[2], [5], [8]])] Vertical splitting: The ‘vsplit()’ function splits an array along axis parameter = 0.‘numpy.vsplit’ is equivalent to ‘split’ with axis parameter = 0. This function split an array into multiple sub-arrays vertically (row-wise).numpy.vsplit(ary, indices_or_sections)Example:import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Vertical splitting of array 'a'# using np.vsplit().print("The array {} gets splitted \vertically to form {} ".format(a, np.vsplit(a, 3))) # Vertical splitting of array 'a' # using 'split' with axis parameter = 0.print("The array {} gets splitted \vertically to form {} ".format(a, np.split(a, 3, 0)))Output:The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])] numpy.vsplit(ary, indices_or_sections) Example: import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Vertical splitting of array 'a'# using np.vsplit().print("The array {} gets splitted \vertically to form {} ".format(a, np.vsplit(a, 3))) # Vertical splitting of array 'a' # using 'split' with axis parameter = 0.print("The array {} gets splitted \vertically to form {} ".format(a, np.split(a, 3, 0))) Output: The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])] Depth-wise splitting: It Split the array into multiple sub-arrays along the 3rd axis (depth).numpy.dsplit(ary, indices_or_sections)Example:import numpy as np # Making of a 3x3x3 array.b = np.arange(27).reshape(3, 3, 3) # Depth-wise splitting of array# 'b' using np.dsplit().print("The array {} gets splitted \depth-wise to form {}".format(b, np.dsplit(b, 3)))Output:The array [[[ 0 1 2][ 3 4 5][ 6 7 8]][[ 9 10 11][12 13 14][15 16 17]][[18 19 20][21 22 23][24 25 26]]] gets splitted depth-wise to form [array([[[ 0],[ 3],[ 6]],[[ 9],[12],[15]],[[18],[21],[24]]]), array([[[ 1],[ 4],[ 7]],[[10],[13],[16]],[[19],[22],[25]]]), array([[[ 2],[ 5],[ 8]],[[11],[14],[17]],[[20],[23],[26]]])] numpy.dsplit(ary, indices_or_sections) Example: import numpy as np # Making of a 3x3x3 array.b = np.arange(27).reshape(3, 3, 3) # Depth-wise splitting of array# 'b' using np.dsplit().print("The array {} gets splitted \depth-wise to form {}".format(b, np.dsplit(b, 3))) Output: The array [[[ 0 1 2][ 3 4 5][ 6 7 8]] [[ 9 10 11][12 13 14][15 16 17]] [[18 19 20][21 22 23][24 25 26]]] gets splitted depth-wise to form [array([[[ 0],[ 3],[ 6]], [[ 9],[12],[15]], [[18],[21],[24]]]), array([[[ 1],[ 4],[ 7]], [[10],[13],[16]], [[19],[22],[25]]]), array([[[ 2],[ 5],[ 8]], [[11],[14],[17]], [[20],[23],[26]]])] Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n10 May, 2020" }, { "code": null, "e": 24155, "s": 23901, "text": "Array splitting can be vertical, horizontal, or depth-wise. We can use functions hsplit(), vsplit() and dsplit() respectively for the same . We can split arrays into arrays of the same shape by indicating the position after which the split should occur." }, { "code": null, "e": 25349, "s": 24155, "text": "Horizontal splitting: The ‘hsplit()’ function splits an array along axis parameter = 1. ‘numpy.hsplit’ is equivalent to ‘split’ with axis parameter = 1, the array is always splitted along the second axis regardless of the array dimension. This function split an array into multiple sub-arrays horizontally (column-wise).Syntax:numpy.hsplit(ary, indices_or_sections)Example:# Horizontal array splitting using np.hsplit()import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Horizontal splitting of array # 'a' using np.hsplit().print(\"The array {} gets splitted \\horizontally to form {} \".format(a, np.hsplit(a, 3))) # Horizontal splitting of array 'a' # using 'split' with axis parameter = 1.print(\"The array {} gets splitted \\horizontally to form {} \".format(a, np.split(a, 3, 1)))Output: The array [[0 1 2]\n [3 4 5]\n [6 7 8]] gets splitted horizontally to form [array([[0],\n [3],\n [6]]), array([[1],\n [4],\n [7]]), array([[2],\n [5],\n [8]])] \nThe array [[0 1 2]\n [3 4 5]\n [6 7 8]] gets splitted horizontally to form [array([[0],\n [3],\n [6]]), array([[1],\n [4],\n [7]]), array([[2],\n [5],\n [8]])]" }, { "code": null, "e": 25357, "s": 25349, "text": "Syntax:" }, { "code": null, "e": 25396, "s": 25357, "text": "numpy.hsplit(ary, indices_or_sections)" }, { "code": null, "e": 25405, "s": 25396, "text": "Example:" }, { "code": "# Horizontal array splitting using np.hsplit()import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Horizontal splitting of array # 'a' using np.hsplit().print(\"The array {} gets splitted \\horizontally to form {} \".format(a, np.hsplit(a, 3))) # Horizontal splitting of array 'a' # using 'split' with axis parameter = 1.print(\"The array {} gets splitted \\horizontally to form {} \".format(a, np.split(a, 3, 1)))", "e": 25842, "s": 25405, "text": null }, { "code": null, "e": 25850, "s": 25842, "text": "Output:" }, { "code": null, "e": 26228, "s": 25850, "text": " The array [[0 1 2]\n [3 4 5]\n [6 7 8]] gets splitted horizontally to form [array([[0],\n [3],\n [6]]), array([[1],\n [4],\n [7]]), array([[2],\n [5],\n [8]])] \nThe array [[0 1 2]\n [3 4 5]\n [6 7 8]] gets splitted horizontally to form [array([[0],\n [3],\n [6]]), array([[1],\n [4],\n [7]]), array([[2],\n [5],\n [8]])]" }, { "code": null, "e": 27143, "s": 26228, "text": "Vertical splitting: The ‘vsplit()’ function splits an array along axis parameter = 0.‘numpy.vsplit’ is equivalent to ‘split’ with axis parameter = 0. This function split an array into multiple sub-arrays vertically (row-wise).numpy.vsplit(ary, indices_or_sections)Example:import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Vertical splitting of array 'a'# using np.vsplit().print(\"The array {} gets splitted \\vertically to form {} \".format(a, np.vsplit(a, 3))) # Vertical splitting of array 'a' # using 'split' with axis parameter = 0.print(\"The array {} gets splitted \\vertically to form {} \".format(a, np.split(a, 3, 0)))Output:The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]" }, { "code": null, "e": 27182, "s": 27143, "text": "numpy.vsplit(ary, indices_or_sections)" }, { "code": null, "e": 27191, "s": 27182, "text": "Example:" }, { "code": "import numpy as np # Making of a 3x3 arraya = np.arange(9).reshape(3, 3) # Vertical splitting of array 'a'# using np.vsplit().print(\"The array {} gets splitted \\vertically to form {} \".format(a, np.vsplit(a, 3))) # Vertical splitting of array 'a' # using 'split' with axis parameter = 0.print(\"The array {} gets splitted \\vertically to form {} \".format(a, np.split(a, 3, 0)))", "e": 27573, "s": 27191, "text": null }, { "code": null, "e": 27581, "s": 27573, "text": "Output:" }, { "code": null, "e": 27836, "s": 27581, "text": "The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]The array [[0 1 2][3 4 5][6 7 8]] gets splitted vertically to form [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]" }, { "code": null, "e": 28527, "s": 27836, "text": "Depth-wise splitting: It Split the array into multiple sub-arrays along the 3rd axis (depth).numpy.dsplit(ary, indices_or_sections)Example:import numpy as np # Making of a 3x3x3 array.b = np.arange(27).reshape(3, 3, 3) # Depth-wise splitting of array# 'b' using np.dsplit().print(\"The array {} gets splitted \\depth-wise to form {}\".format(b, np.dsplit(b, 3)))Output:The array [[[ 0 1 2][ 3 4 5][ 6 7 8]][[ 9 10 11][12 13 14][15 16 17]][[18 19 20][21 22 23][24 25 26]]] gets splitted depth-wise to form [array([[[ 0],[ 3],[ 6]],[[ 9],[12],[15]],[[18],[21],[24]]]), array([[[ 1],[ 4],[ 7]],[[10],[13],[16]],[[19],[22],[25]]]), array([[[ 2],[ 5],[ 8]],[[11],[14],[17]],[[20],[23],[26]]])]" }, { "code": null, "e": 28566, "s": 28527, "text": "numpy.dsplit(ary, indices_or_sections)" }, { "code": null, "e": 28575, "s": 28566, "text": "Example:" }, { "code": "import numpy as np # Making of a 3x3x3 array.b = np.arange(27).reshape(3, 3, 3) # Depth-wise splitting of array# 'b' using np.dsplit().print(\"The array {} gets splitted \\depth-wise to form {}\".format(b, np.dsplit(b, 3)))", "e": 28801, "s": 28575, "text": null }, { "code": null, "e": 28809, "s": 28801, "text": "Output:" }, { "code": null, "e": 28847, "s": 28809, "text": "The array [[[ 0 1 2][ 3 4 5][ 6 7 8]]" }, { "code": null, "e": 28880, "s": 28847, "text": "[[ 9 10 11][12 13 14][15 16 17]]" }, { "code": null, "e": 28973, "s": 28880, "text": "[[18 19 20][21 22 23][24 25 26]]] gets splitted depth-wise to form [array([[[ 0],[ 3],[ 6]]," }, { "code": null, "e": 28991, "s": 28973, "text": "[[ 9],[12],[15]]," }, { "code": null, "e": 29036, "s": 28991, "text": "[[18],[21],[24]]]), array([[[ 1],[ 4],[ 7]]," }, { "code": null, "e": 29054, "s": 29036, "text": "[[10],[13],[16]]," }, { "code": null, "e": 29099, "s": 29054, "text": "[[19],[22],[25]]]), array([[[ 2],[ 5],[ 8]]," }, { "code": null, "e": 29117, "s": 29099, "text": "[[11],[14],[17]]," }, { "code": null, "e": 29137, "s": 29117, "text": "[[20],[23],[26]]])]" }, { "code": null, "e": 29168, "s": 29137, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 29181, "s": 29168, "text": "Python-numpy" }, { "code": null, "e": 29188, "s": 29181, "text": "Python" }, { "code": null, "e": 29286, "s": 29188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29295, "s": 29286, "text": "Comments" }, { "code": null, "e": 29308, "s": 29295, "text": "Old Comments" }, { "code": null, "e": 29340, "s": 29308, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29396, "s": 29340, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29438, "s": 29396, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29480, "s": 29438, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29516, "s": 29480, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 29538, "s": 29516, "text": "Defaultdict in Python" }, { "code": null, "e": 29577, "s": 29538, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29604, "s": 29577, "text": "Python Classes and Objects" }, { "code": null, "e": 29635, "s": 29604, "text": "Python | os.path.join() method" } ]
Share Price Forecasting Using Facebook Prophet - GeeksforGeeks
30 Aug, 2021 Time series forecast can be used in a wide verity of applications such as Budget Forecasting, Stock Market Analysis, etc. But as useful it is also challenging to forecast the correct projections, Thus can’t be easily automated because of the underlying assumptions and factors. The analysts who produced accurate forecasts are also rare, and there is a big market available for them because it requires a substantial understanding of statistics and data analysis and has prior experience of producing time series forecasting. Facebook open-sourced its time-series forecasting tool called Prophet in 2017 which produced accurate forecasts as produced by skilled analysts with a minimum amount of human efforts. The Facebook prophet is available in the form of API in Python and R/ How Prophet Works: Facebook Prophet using Additive Regressive models using the following four components: y(t) = g(t) + s(t) + h(t) + \epsilon_t g(t): A piecewise linear or logistic growth curve trend. Prophet automatically detects changes in trends by selecting change points from the data. s(t): A yearly seasonal component modeled using the Fourier series and weekly seasonal component using dummy variable h(t): A user-provided list of important holidays. et: Error term used by the prophet. Advantages of Facebook Prophet: the prophet is optimized for business-related problems that are encountered at Facebook, it has the following characteristics: The Facebook prophet is as accurate as a skilled analyst and can generate results in seconds Facebook prophet requires minimal data processing and can deal with several outliers and null values. User can add seasonality and holidays values manually, this can help easily integrate the particular domain knowledge. In this post, we will use Facebook prophet with Python. We try to forecast the share price of Amazon Stock (from 2019-2020) using the share price data from (2015-2019). Implementation: For this post, we will be using Amazon Stock Price data, it can be downloaded from yahoo finance website. First, we need to install the fbprophet tool, it can be installed with the following command in python. Requirement already satisfied: fbprophet in /usr/local/lib/python3.6/dist-packages (0.6) Requirement already satisfied: Cython>=0.22 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.29.21) Requirement already satisfied: cmdstanpy==0.4 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.4.0) Requirement already satisfied: pystan>=2.14 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (2.19.1.1) Requirement already satisfied: numpy>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (1.18.5) Requirement already satisfied: pandas>=0.23.4 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (1.0.5) Requirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (3.2.2) Requirement already satisfied: LunarCalendar>=0.0.9 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.0.9) Requirement already satisfied: convertdate>=2.1.2 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (2.2.1) Requirement already satisfied: holidays>=0.9.5 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.9.12) Requirement already satisfied: setuptools-git>=1.2 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (1.2) Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (2.8.1) Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.4->fbprophet) (2018.9) Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.0.0->fbprophet) (0.10.0) Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.0.0->fbprophet) (1.2.0) Requirement already satisfied: pyparsing!=2.0.4, !=2.1.2, !=2.1.6, >=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.0.0->fbprophet) (2.4.7) Requirement already satisfied: ephem>=3.7.5.3 in /usr/local/lib/python3.6/dist-packages (from LunarCalendar>=0.0.9->fbprophet) (3.7.7.1) Requirement already satisfied: pymeeus<=1, >=0.3.6 in /usr/local/lib/python3.6/dist-packages (from convertdate>=2.1.2->fbprophet) (0.3.7) Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from holidays>=0.9.5->fbprophet) (1.12.0) Now, we need to import fbprophet and some other modules for data processing and plotting. We will use mean squared error and mean absolute error as our metrics. Code: python3 import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport fbprophet as fbpfrom sklearn.metrics import mean_squared_error, mean_absolute_error# Use fivethirtyeight plot styleplt.style.use('fivethirtyeight') Now, we will read data from CSV file and put them into a pandas data frame. Code: python3 # We will be using amazon share price dat whichcanbe downloaded from YAHOO finance website.df = pd.read_csv('sample_data / AMZN.csv')df.head() Output: Date Open High Low Close Adj Close Volume 0 2015-07-21 487.899994 488.880005 482.549988 488.000000 488.000000 3181800 1 2015-07-22 485.989990 492.500000 484.899994 488.269989 488.269989 3114900 2 2015-07-23 491.660004 491.660004 475.700012 482.179993 482.179993 9374400 3 2015-07-24 578.989990 580.570007 529.349976 529.419983 529.419983 21909400 4 2015-07-27 527.750000 544.950012 526.599976 531.409973 531.409973 7491000 Since we need only two columns date and adjusted close price, so, we subset the original dataset to get these columns. Since the data is required in a prophet in the form of two columns named ds (for date column) and y (for data column). Code: python3 # add two columnsin dataframe having values as Date and Adj Closedf[['ds', 'y']] = df[['Date', 'Adj Close']]# Subset two columns from data framedf = df[['ds', 'y']] df.head() Output: ds y 0 2015-07-21 488.000000 1 2015-07-22 488.269989 2 2015-07-23 482.179993 3 2015-07-24 529.419983 4 2015-07-27 531.409973 Now, we split the data frame into train and test data, we will be using 4 years of data for training and a year of data for test purpose. Code: python3 # split data frame into two parts train and testsplit_date = "2019-07-21"df_train = df.loc[df.ds <= split_date].copy()df_test = df.loc[df.ds > split_date].copy() Now, we instantiate the Facebook prophet API, this prophet API works similar to scikit-learn. It uses the fit function to fit the dataset into the model and predict function to forecast future values. Code: python3 # Instantiate prophetmodel = fbp.Prophet()# fit the training datamodel.fit(df_train) Now, we use predict function to forecast the share price for next 1 year. Code: python3 forecast = model.predict(df_test)forecast.tail() Output: ds trend yhat_lower yhat_upper trend_lower trend_upper additive_terms additive_terms_lower additive_terms_upper weekly weekly_lower weekly_upper yearly yearly_lower yearly_upper multiplicative_terms multiplicative_terms_lower multiplicative_terms_upper yhat 247 2020-07-14 1992.862925 1479.553875 2566.925238 1403.962381 2483.045869 93.536964 93.536964 93.536964 -25.535936 -25.535936 -25.535936 119.072900 119.072900 119.072900 0.0 0.0 0.0 2086.399889 248 2020-07-15 1993.215324 1485.368711 2575.314593 1401.835761 2485.386736 97.405883 97.405883 97.405883 -25.138654 -25.138654 -25.138654 122.544537 122.544537 122.544537 0.0 0.0 0.0 2090.621207 249 2020-07-16 1993.567723 1484.197262 2589.201052 1399.740456 2487.727602 100.236350 100.236350 100.236350 -25.549805 -25.549805 -25.549805 125.786155 125.786155 125.786155 0.0 0.0 0.0 2093.804073 250 2020-07-17 1993.920121 1478.807958 2617.093500 1397.645151 2490.068469 99.309824 99.309824 99.309824 -29.445843 -29.445843 -29.445843 128.755666 128.755666 128.755666 0.0 0.0 0.0 2093.229945 251 2020-07-20 1994.977318 1475.034301 2618.609494 1389.089958 2497.091069 104.649308 104.649308 104.649308 -31.050560 -31.050560 -31.050560 135.699868 135.699868 135.699868 0.0 0.0 0.0 2099.626626 As we can see this column contains the date column, predict share price (y_hat), lower and upper estimates of it, trend components, seasonal components (weekly and yearly). Code: python3 model.plot(forecast) Output: The command will plot the components of the prophet such as: trend line, weekly and yearly seasonality. Code: python3 # plot graphs of different components:model.plot_components(forecast) Output: Now, we calculate the mean square error and mean absolute error for the forecasted data. Code: python3 # codeprint("Mean Squared Error (MSE):", mean_squared_error(y_true = df_test["y"], y_pred = forecast['yhat']))print("Mean Absolute Error (MAE):", mean_absolute_error(y_true = df_test["y"], y_pred = forecast['yhat'])) Output: Mean Squared Error (MSE): 121417.80253038534 Mean Absolute Error (MAE): 246.57694290710793 Now, we calculate the mean absolute percentage error of our forecast, because it gives a better idea about how accurate our prediction is Code: python3 def mean_abs_perc_err(y_true, y_pred): return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 print("Mean Absolute % Error (MAPE): ", mean_abs_perc_err(y_true = np.asarray(df_test["y"]), y_pred = np.asarray(forecast['yhat']))) Output: Mean Absolute % Error (MAPE): 10.693787212532687 References: Facebook Prophet blog Facebook Prophet Documentation gabaa406 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Python | Decision tree implementation Search Algorithms in AI Difference between Informed and Uninformed Search in AI Decision Tree Introduction with example Read JSON file using Python Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python
[ { "code": null, "e": 24639, "s": 24611, "text": "\n30 Aug, 2021" }, { "code": null, "e": 25165, "s": 24639, "text": "Time series forecast can be used in a wide verity of applications such as Budget Forecasting, Stock Market Analysis, etc. But as useful it is also challenging to forecast the correct projections, Thus can’t be easily automated because of the underlying assumptions and factors. The analysts who produced accurate forecasts are also rare, and there is a big market available for them because it requires a substantial understanding of statistics and data analysis and has prior experience of producing time series forecasting." }, { "code": null, "e": 25419, "s": 25165, "text": "Facebook open-sourced its time-series forecasting tool called Prophet in 2017 which produced accurate forecasts as produced by skilled analysts with a minimum amount of human efforts. The Facebook prophet is available in the form of API in Python and R/" }, { "code": null, "e": 25438, "s": 25419, "text": "How Prophet Works:" }, { "code": null, "e": 25525, "s": 25438, "text": "Facebook Prophet using Additive Regressive models using the following four components:" }, { "code": null, "e": 25564, "s": 25525, "text": "y(t) = g(t) + s(t) + h(t) + \\epsilon_t" }, { "code": null, "e": 25711, "s": 25564, "text": "g(t): A piecewise linear or logistic growth curve trend. Prophet automatically detects changes in trends by selecting change points from the data." }, { "code": null, "e": 25829, "s": 25711, "text": "s(t): A yearly seasonal component modeled using the Fourier series and weekly seasonal component using dummy variable" }, { "code": null, "e": 25879, "s": 25829, "text": "h(t): A user-provided list of important holidays." }, { "code": null, "e": 25916, "s": 25879, "text": "et: Error term used by the prophet." }, { "code": null, "e": 25948, "s": 25916, "text": "Advantages of Facebook Prophet:" }, { "code": null, "e": 26075, "s": 25948, "text": "the prophet is optimized for business-related problems that are encountered at Facebook, it has the following characteristics:" }, { "code": null, "e": 26168, "s": 26075, "text": "The Facebook prophet is as accurate as a skilled analyst and can generate results in seconds" }, { "code": null, "e": 26270, "s": 26168, "text": "Facebook prophet requires minimal data processing and can deal with several outliers and null values." }, { "code": null, "e": 26389, "s": 26270, "text": "User can add seasonality and holidays values manually, this can help easily integrate the particular domain knowledge." }, { "code": null, "e": 26558, "s": 26389, "text": "In this post, we will use Facebook prophet with Python. We try to forecast the share price of Amazon Stock (from 2019-2020) using the share price data from (2015-2019)." }, { "code": null, "e": 26574, "s": 26558, "text": "Implementation:" }, { "code": null, "e": 26680, "s": 26574, "text": "For this post, we will be using Amazon Stock Price data, it can be downloaded from yahoo finance website." }, { "code": null, "e": 26784, "s": 26680, "text": "First, we need to install the fbprophet tool, it can be installed with the following command in python." }, { "code": null, "e": 29093, "s": 26784, "text": "Requirement already satisfied: fbprophet in /usr/local/lib/python3.6/dist-packages (0.6)\nRequirement already satisfied: Cython>=0.22 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.29.21)\nRequirement already satisfied: cmdstanpy==0.4 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.4.0)\nRequirement already satisfied: pystan>=2.14 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (2.19.1.1)\nRequirement already satisfied: numpy>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (1.18.5)\nRequirement already satisfied: pandas>=0.23.4 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (1.0.5)\nRequirement already satisfied: matplotlib>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (3.2.2)\nRequirement already satisfied: LunarCalendar>=0.0.9 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.0.9)\nRequirement already satisfied: convertdate>=2.1.2 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (2.2.1)\nRequirement already satisfied: holidays>=0.9.5 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (0.9.12)\nRequirement already satisfied: setuptools-git>=1.2 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (1.2)\nRequirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from fbprophet) (2.8.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.4->fbprophet) (2018.9)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.0.0->fbprophet) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.0.0->fbprophet) (1.2.0)\nRequirement already satisfied: pyparsing!=2.0.4, !=2.1.2, !=2.1.6, >=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=2.0.0->fbprophet) (2.4.7)\nRequirement already satisfied: ephem>=3.7.5.3 in /usr/local/lib/python3.6/dist-packages (from LunarCalendar>=0.0.9->fbprophet) (3.7.7.1)\nRequirement already satisfied: pymeeus<=1, >=0.3.6 in /usr/local/lib/python3.6/dist-packages (from convertdate>=2.1.2->fbprophet) (0.3.7)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from holidays>=0.9.5->fbprophet) (1.12.0)" }, { "code": null, "e": 29254, "s": 29093, "text": "Now, we need to import fbprophet and some other modules for data processing and plotting. We will use mean squared error and mean absolute error as our metrics." }, { "code": null, "e": 29261, "s": 29254, "text": "Code: " }, { "code": null, "e": 29269, "s": 29261, "text": "python3" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport fbprophet as fbpfrom sklearn.metrics import mean_squared_error, mean_absolute_error# Use fivethirtyeight plot styleplt.style.use('fivethirtyeight')", "e": 29492, "s": 29269, "text": null }, { "code": null, "e": 29568, "s": 29492, "text": "Now, we will read data from CSV file and put them into a pandas data frame." }, { "code": null, "e": 29575, "s": 29568, "text": "Code: " }, { "code": null, "e": 29583, "s": 29575, "text": "python3" }, { "code": "# We will be using amazon share price dat whichcanbe downloaded from YAHOO finance website.df = pd.read_csv('sample_data / AMZN.csv')df.head()", "e": 29726, "s": 29583, "text": null }, { "code": null, "e": 29736, "s": 29726, "text": "Output: " }, { "code": null, "e": 30282, "s": 29736, "text": "Date Open High Low Close Adj Close Volume\n0 2015-07-21 487.899994 488.880005 482.549988 488.000000 488.000000 3181800\n1 2015-07-22 485.989990 492.500000 484.899994 488.269989 488.269989 3114900\n2 2015-07-23 491.660004 491.660004 475.700012 482.179993 482.179993 9374400\n3 2015-07-24 578.989990 580.570007 529.349976 529.419983 529.419983 21909400\n4 2015-07-27 527.750000 544.950012 526.599976 531.409973 531.409973 7491000" }, { "code": null, "e": 30520, "s": 30282, "text": "Since we need only two columns date and adjusted close price, so, we subset the original dataset to get these columns. Since the data is required in a prophet in the form of two columns named ds (for date column) and y (for data column)." }, { "code": null, "e": 30527, "s": 30520, "text": "Code: " }, { "code": null, "e": 30535, "s": 30527, "text": "python3" }, { "code": "# add two columnsin dataframe having values as Date and Adj Closedf[['ds', 'y']] = df[['Date', 'Adj Close']]# Subset two columns from data framedf = df[['ds', 'y']] df.head()", "e": 30710, "s": 30535, "text": null }, { "code": null, "e": 30720, "s": 30710, "text": "Output: " }, { "code": null, "e": 30878, "s": 30720, "text": "ds y\n0 2015-07-21 488.000000\n1 2015-07-22 488.269989\n2 2015-07-23 482.179993\n3 2015-07-24 529.419983\n4 2015-07-27 531.409973" }, { "code": null, "e": 31016, "s": 30878, "text": "Now, we split the data frame into train and test data, we will be using 4 years of data for training and a year of data for test purpose." }, { "code": null, "e": 31023, "s": 31016, "text": "Code: " }, { "code": null, "e": 31031, "s": 31023, "text": "python3" }, { "code": "# split data frame into two parts train and testsplit_date = \"2019-07-21\"df_train = df.loc[df.ds <= split_date].copy()df_test = df.loc[df.ds > split_date].copy()", "e": 31194, "s": 31031, "text": null }, { "code": null, "e": 31395, "s": 31194, "text": "Now, we instantiate the Facebook prophet API, this prophet API works similar to scikit-learn. It uses the fit function to fit the dataset into the model and predict function to forecast future values." }, { "code": null, "e": 31402, "s": 31395, "text": "Code: " }, { "code": null, "e": 31410, "s": 31402, "text": "python3" }, { "code": "# Instantiate prophetmodel = fbp.Prophet()# fit the training datamodel.fit(df_train)", "e": 31495, "s": 31410, "text": null }, { "code": null, "e": 31569, "s": 31495, "text": "Now, we use predict function to forecast the share price for next 1 year." }, { "code": null, "e": 31576, "s": 31569, "text": "Code: " }, { "code": null, "e": 31584, "s": 31576, "text": "python3" }, { "code": "forecast = model.predict(df_test)forecast.tail()", "e": 31633, "s": 31584, "text": null }, { "code": null, "e": 31643, "s": 31633, "text": "Output: " }, { "code": null, "e": 33221, "s": 31643, "text": "ds trend yhat_lower yhat_upper trend_lower trend_upper additive_terms additive_terms_lower additive_terms_upper weekly weekly_lower weekly_upper yearly yearly_lower yearly_upper multiplicative_terms multiplicative_terms_lower multiplicative_terms_upper yhat\n247 2020-07-14 1992.862925 1479.553875 2566.925238 1403.962381 2483.045869 93.536964 93.536964 93.536964 -25.535936 -25.535936 -25.535936 119.072900 119.072900 119.072900 0.0 0.0 0.0 2086.399889\n248 2020-07-15 1993.215324 1485.368711 2575.314593 1401.835761 2485.386736 97.405883 97.405883 97.405883 -25.138654 -25.138654 -25.138654 122.544537 122.544537 122.544537 0.0 0.0 0.0 2090.621207\n249 2020-07-16 1993.567723 1484.197262 2589.201052 1399.740456 2487.727602 100.236350 100.236350 100.236350 -25.549805 -25.549805 -25.549805 125.786155 125.786155 125.786155 0.0 0.0 0.0 2093.804073\n250 2020-07-17 1993.920121 1478.807958 2617.093500 1397.645151 2490.068469 99.309824 99.309824 99.309824 -29.445843 -29.445843 -29.445843 128.755666 128.755666 128.755666 0.0 0.0 0.0 2093.229945\n251 2020-07-20 1994.977318 1475.034301 2618.609494 1389.089958 2497.091069 104.649308 104.649308 104.649308 -31.050560 -31.050560 -31.050560 135.699868 135.699868 135.699868 0.0 0.0 0.0 2099.626626" }, { "code": null, "e": 33394, "s": 33221, "text": "As we can see this column contains the date column, predict share price (y_hat), lower and upper estimates of it, trend components, seasonal components (weekly and yearly)." }, { "code": null, "e": 33401, "s": 33394, "text": "Code: " }, { "code": null, "e": 33409, "s": 33401, "text": "python3" }, { "code": "model.plot(forecast)", "e": 33430, "s": 33409, "text": null }, { "code": null, "e": 33440, "s": 33430, "text": "Output: " }, { "code": null, "e": 33544, "s": 33440, "text": "The command will plot the components of the prophet such as: trend line, weekly and yearly seasonality." }, { "code": null, "e": 33552, "s": 33544, "text": "Code: " }, { "code": null, "e": 33560, "s": 33552, "text": "python3" }, { "code": "# plot graphs of different components:model.plot_components(forecast)", "e": 33630, "s": 33560, "text": null }, { "code": null, "e": 33639, "s": 33630, "text": "Output: " }, { "code": null, "e": 33732, "s": 33643, "text": "Now, we calculate the mean square error and mean absolute error for the forecasted data." }, { "code": null, "e": 33739, "s": 33732, "text": "Code: " }, { "code": null, "e": 33747, "s": 33739, "text": "python3" }, { "code": "# codeprint(\"Mean Squared Error (MSE):\", mean_squared_error(y_true = df_test[\"y\"], y_pred = forecast['yhat']))print(\"Mean Absolute Error (MAE):\", mean_absolute_error(y_true = df_test[\"y\"], y_pred = forecast['yhat']))", "e": 33964, "s": 33747, "text": null }, { "code": null, "e": 33974, "s": 33964, "text": "Output: " }, { "code": null, "e": 34065, "s": 33974, "text": "Mean Squared Error (MSE): 121417.80253038534\nMean Absolute Error (MAE): 246.57694290710793" }, { "code": null, "e": 34203, "s": 34065, "text": "Now, we calculate the mean absolute percentage error of our forecast, because it gives a better idea about how accurate our prediction is" }, { "code": null, "e": 34211, "s": 34203, "text": "Code: " }, { "code": null, "e": 34219, "s": 34211, "text": "python3" }, { "code": "def mean_abs_perc_err(y_true, y_pred): return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 print(\"Mean Absolute % Error (MAPE): \", mean_abs_perc_err(y_true = np.asarray(df_test[\"y\"]), y_pred = np.asarray(forecast['yhat'])))", "e": 34451, "s": 34219, "text": null }, { "code": null, "e": 34461, "s": 34451, "text": "Output: " }, { "code": null, "e": 34511, "s": 34461, "text": "Mean Absolute % Error (MAPE): 10.693787212532687" }, { "code": null, "e": 34525, "s": 34513, "text": "References:" }, { "code": null, "e": 34549, "s": 34527, "text": "Facebook Prophet blog" }, { "code": null, "e": 34581, "s": 34549, "text": "Facebook Prophet Documentation " }, { "code": null, "e": 34592, "s": 34583, "text": "gabaa406" }, { "code": null, "e": 34609, "s": 34592, "text": "Machine Learning" }, { "code": null, "e": 34616, "s": 34609, "text": "Python" }, { "code": null, "e": 34633, "s": 34616, "text": "Machine Learning" }, { "code": null, "e": 34731, "s": 34633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34740, "s": 34731, "text": "Comments" }, { "code": null, "e": 34753, "s": 34740, "text": "Old Comments" }, { "code": null, "e": 34776, "s": 34753, "text": "ML | Linear Regression" }, { "code": null, "e": 34814, "s": 34776, "text": "Python | Decision tree implementation" }, { "code": null, "e": 34838, "s": 34814, "text": "Search Algorithms in AI" }, { "code": null, "e": 34894, "s": 34838, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 34934, "s": 34894, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 34962, "s": 34934, "text": "Read JSON file using Python" }, { "code": null, "e": 34984, "s": 34962, "text": "Python map() function" }, { "code": null, "e": 35028, "s": 34984, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 35046, "s": 35028, "text": "Python Dictionary" } ]
How to move button in the same line with Checkbox and Textbox using JavaScript ? - GeeksforGeeks
16 Jul, 2020 The style “display” property in HTML DOM is used to set elements to “display” property. To set the button in the same line with other elements of the web page is done using the inline property. Syntax: It returns the “display” property.object.style.display object.style.display It sets the “display” property.object.style.display = inline; object.style.display = inline; Example: <!DOCTYPE html><html> <head> <!-- script to set display property --> <script> function myGeeks() { document.getElementById("GFG") .style.display = "inline"; } </script></head> <body> <div id="GFG"> <input type="checkbox" checked> computer <input type="checkbox"> mobile <input type="text"> </div> <button onclick="myGeeks()"> Press </button></body> </html> Output: Before click on the button: After click on the button: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 26083, "s": 26055, "text": "\n16 Jul, 2020" }, { "code": null, "e": 26277, "s": 26083, "text": "The style “display” property in HTML DOM is used to set elements to “display” property. To set the button in the same line with other elements of the web page is done using the inline property." }, { "code": null, "e": 26285, "s": 26277, "text": "Syntax:" }, { "code": null, "e": 26340, "s": 26285, "text": "It returns the “display” property.object.style.display" }, { "code": null, "e": 26361, "s": 26340, "text": "object.style.display" }, { "code": null, "e": 26423, "s": 26361, "text": "It sets the “display” property.object.style.display = inline;" }, { "code": null, "e": 26454, "s": 26423, "text": "object.style.display = inline;" }, { "code": null, "e": 26463, "s": 26454, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- script to set display property --> <script> function myGeeks() { document.getElementById(\"GFG\") .style.display = \"inline\"; } </script></head> <body> <div id=\"GFG\"> <input type=\"checkbox\" checked> computer <input type=\"checkbox\"> mobile <input type=\"text\"> </div> <button onclick=\"myGeeks()\"> Press </button></body> </html>", "e": 26919, "s": 26463, "text": null }, { "code": null, "e": 26927, "s": 26919, "text": "Output:" }, { "code": null, "e": 26955, "s": 26927, "text": "Before click on the button:" }, { "code": null, "e": 26982, "s": 26955, "text": "After click on the button:" }, { "code": null, "e": 26991, "s": 26982, "text": "CSS-Misc" }, { "code": null, "e": 27001, "s": 26991, "text": "HTML-Misc" }, { "code": null, "e": 27017, "s": 27001, "text": "JavaScript-Misc" }, { "code": null, "e": 27024, "s": 27017, "text": "Picked" }, { "code": null, "e": 27028, "s": 27024, "text": "CSS" }, { "code": null, "e": 27033, "s": 27028, "text": "HTML" }, { "code": null, "e": 27044, "s": 27033, "text": "JavaScript" }, { "code": null, "e": 27061, "s": 27044, "text": "Web Technologies" }, { "code": null, "e": 27088, "s": 27061, "text": "Web technologies Questions" }, { "code": null, "e": 27093, "s": 27088, "text": "HTML" }, { "code": null, "e": 27191, "s": 27093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27246, "s": 27191, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 27283, "s": 27246, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27347, "s": 27283, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27384, "s": 27347, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27445, "s": 27384, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27505, "s": 27445, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27558, "s": 27505, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27608, "s": 27558, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27632, "s": 27608, "text": "REST API (Introduction)" } ]
LocalDate compareTo() method in Java - GeeksforGeeks
28 Nov, 2018 The compareTo() method of LocalDate class in Java method compares this date to another date. Syntax: public int compareTo(ChronoLocalDate other) Parameter: This method accepts a parameter other which specifies the other date to compare to and it is not specifically null. Return Value: It returns the comparator value which is negative if it is less else it is positive if it is greater. Below programs illustrate the compareTo() method of LocalDate in Java: Program 1: // Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // First date LocalDate dt = LocalDate.parse("2018-11-01"); System.out.println(dt); // Second date LocalDate dt1 = LocalDate.parse("2018-11-14"); System.out.println(dt1); // Compare both dates System.out.println(dt1.compareTo(dt)); }} 2018-11-01 2018-11-14 13 Program 2: // Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // First date LocalDate dt = LocalDate.parse("2018-11-21"); System.out.println(dt); // Second date LocalDate dt1 = LocalDate.parse("2018-11-14"); System.out.println(dt1); // Compare both dates System.out.println(dt1.compareTo(dt)); }} 2018-11-21 2018-11-14 -7 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#compareTo(java.time.chrono.ChronoLocalDate) Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25559, "s": 25531, "text": "\n28 Nov, 2018" }, { "code": null, "e": 25652, "s": 25559, "text": "The compareTo() method of LocalDate class in Java method compares this date to another date." }, { "code": null, "e": 25660, "s": 25652, "text": "Syntax:" }, { "code": null, "e": 25705, "s": 25660, "text": "public int compareTo(ChronoLocalDate other)\n" }, { "code": null, "e": 25832, "s": 25705, "text": "Parameter: This method accepts a parameter other which specifies the other date to compare to and it is not specifically null." }, { "code": null, "e": 25948, "s": 25832, "text": "Return Value: It returns the comparator value which is negative if it is less else it is positive if it is greater." }, { "code": null, "e": 26019, "s": 25948, "text": "Below programs illustrate the compareTo() method of LocalDate in Java:" }, { "code": null, "e": 26030, "s": 26019, "text": "Program 1:" }, { "code": "// Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // First date LocalDate dt = LocalDate.parse(\"2018-11-01\"); System.out.println(dt); // Second date LocalDate dt1 = LocalDate.parse(\"2018-11-14\"); System.out.println(dt1); // Compare both dates System.out.println(dt1.compareTo(dt)); }}", "e": 26483, "s": 26030, "text": null }, { "code": null, "e": 26509, "s": 26483, "text": "2018-11-01\n2018-11-14\n13\n" }, { "code": null, "e": 26520, "s": 26509, "text": "Program 2:" }, { "code": "// Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // First date LocalDate dt = LocalDate.parse(\"2018-11-21\"); System.out.println(dt); // Second date LocalDate dt1 = LocalDate.parse(\"2018-11-14\"); System.out.println(dt1); // Compare both dates System.out.println(dt1.compareTo(dt)); }}", "e": 26973, "s": 26520, "text": null }, { "code": null, "e": 26999, "s": 26973, "text": "2018-11-21\n2018-11-14\n-7\n" }, { "code": null, "e": 27122, "s": 26999, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#compareTo(java.time.chrono.ChronoLocalDate)" }, { "code": null, "e": 27137, "s": 27122, "text": "Java-Functions" }, { "code": null, "e": 27152, "s": 27137, "text": "Java-LocalDate" }, { "code": null, "e": 27170, "s": 27152, "text": "Java-time package" }, { "code": null, "e": 27175, "s": 27170, "text": "Java" }, { "code": null, "e": 27180, "s": 27175, "text": "Java" }, { "code": null, "e": 27278, "s": 27180, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27329, "s": 27278, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27359, "s": 27329, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27378, "s": 27359, "text": "Interfaces in Java" }, { "code": null, "e": 27393, "s": 27378, "text": "Stream In Java" }, { "code": null, "e": 27424, "s": 27393, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27442, "s": 27424, "text": "ArrayList in Java" }, { "code": null, "e": 27474, "s": 27442, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27494, "s": 27474, "text": "Stack Class in Java" }, { "code": null, "e": 27526, "s": 27494, "text": "Multidimensional Arrays in Java" } ]
HTML <hgroup> Tag - GeeksforGeeks
17 Mar, 2022 The <hgroup> tag in HTML stands for heading group and is used to group the heading elements. The <hgroup> tag in HTML is used to wrap one or more heading elements from <h1> to <h6>, such as the headings and sub-headings. The <hgroup> tag requires the starting tag as well as ending tag. Note: <hgroup> is deprecated from HTML5 specification.Syntax : <hgroup> ... </hgroup> Below examples illustrate the <hgroup> tag in HTML:Example 1: This example contains the Title and Sub-Title. HTML <!DOCTYPE html> <html> <body> <!--HTML hgroup tag starts here--> <hgroup> <h1>This is the title.</h1> <h2>This is sub-title.</h2> </hgroup> <!--HTML hgroup tag ends here--> </body> </html> Output: Example 2: This example contains Title, Sub-Title, and Metadata. HTML <!DOCTYPE html> <html> <body> <!--HTML hgroup tag starts here--> <hgroup> <h1>This is the title.</h1> <h2>This is sub-title.</h2> <p>This is the metadata.</p> </hgroup> <!--HTML hgroup tag ends here--> </body> </html> Output: Supported Browsers: Google Chrome 5.0 Internet Explorer 9.0 Firefox 4.0 Opera 11.1 Safari 5.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamyadav4 ManasChhabra2 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24325, "s": 24297, "text": "\n17 Mar, 2022" }, { "code": null, "e": 24612, "s": 24325, "text": "The <hgroup> tag in HTML stands for heading group and is used to group the heading elements. The <hgroup> tag in HTML is used to wrap one or more heading elements from <h1> to <h6>, such as the headings and sub-headings. The <hgroup> tag requires the starting tag as well as ending tag." }, { "code": null, "e": 24677, "s": 24612, "text": "Note: <hgroup> is deprecated from HTML5 specification.Syntax : " }, { "code": null, "e": 24700, "s": 24677, "text": "<hgroup> ... </hgroup>" }, { "code": null, "e": 24811, "s": 24700, "text": "Below examples illustrate the <hgroup> tag in HTML:Example 1: This example contains the Title and Sub-Title. " }, { "code": null, "e": 24816, "s": 24811, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <body> <!--HTML hgroup tag starts here--> <hgroup> <h1>This is the title.</h1> <h2>This is sub-title.</h2> </hgroup> <!--HTML hgroup tag ends here--> </body> </html> ", "e": 25112, "s": 24816, "text": null }, { "code": null, "e": 25122, "s": 25112, "text": "Output: " }, { "code": null, "e": 25189, "s": 25122, "text": "Example 2: This example contains Title, Sub-Title, and Metadata. " }, { "code": null, "e": 25194, "s": 25189, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <body> <!--HTML hgroup tag starts here--> <hgroup> <h1>This is the title.</h1> <h2>This is sub-title.</h2> <p>This is the metadata.</p> </hgroup> <!--HTML hgroup tag ends here--> </body> </html> ", "e": 25518, "s": 25194, "text": null }, { "code": null, "e": 25528, "s": 25518, "text": "Output: " }, { "code": null, "e": 25549, "s": 25528, "text": "Supported Browsers: " }, { "code": null, "e": 25567, "s": 25549, "text": "Google Chrome 5.0" }, { "code": null, "e": 25589, "s": 25567, "text": "Internet Explorer 9.0" }, { "code": null, "e": 25601, "s": 25589, "text": "Firefox 4.0" }, { "code": null, "e": 25612, "s": 25601, "text": "Opera 11.1" }, { "code": null, "e": 25623, "s": 25612, "text": "Safari 5.0" }, { "code": null, "e": 25762, "s": 25625, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 25776, "s": 25762, "text": "shubhamyadav4" }, { "code": null, "e": 25790, "s": 25776, "text": "ManasChhabra2" }, { "code": null, "e": 25800, "s": 25790, "text": "HTML-Tags" }, { "code": null, "e": 25805, "s": 25800, "text": "HTML" }, { "code": null, "e": 25810, "s": 25805, "text": "HTML" }, { "code": null, "e": 25908, "s": 25810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25970, "s": 25908, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26020, "s": 25970, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26068, "s": 26020, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26128, "s": 26068, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26181, "s": 26128, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 26242, "s": 26181, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26266, "s": 26242, "text": "REST API (Introduction)" }, { "code": null, "e": 26316, "s": 26266, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26366, "s": 26316, "text": "CSS to put icon inside an input element in a form" } ]
ML | Bagging classifier - GeeksforGeeks
20 May, 2019 A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it.Each base classifier is trained in parallel with a training set which is generated by randomly drawing, with replacement, N examples(or data) from the original training dataset – where N is the size of the original training set. Training set for each of the base classifiers is independent of each other. Many of the original data may be repeated in the resulting training set while others may be left out. Bagging reduces overfitting (variance) by averaging or voting, however, this leads to an increase in bias, which is compensated by the reduction in variance though. How Bagging works on training dataset ?How bagging works on an imaginary training dataset is shown below. Since Bagging resamples the original training dataset with replacement, some instance(or data) may be present multiple times while others are left out. Original training dataset: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Resampled training set 1: 2, 3, 3, 5, 6, 1, 8, 10, 9, 1Resampled training set 2: 1, 1, 5, 6, 3, 8, 9, 10, 2, 7Resampled training set 3: 1, 5, 8, 9, 2, 10, 9, 7, 5, 4 Algorithm for the Bagging classifier: Classifier generation: Let N be the size of the training set. for each of t iterations: sample N instances with replacement from the original training set. apply the learning algorithm to the sample. store the resulting classifier. Classification: for each of the t classifiers: predict class of instance using classifier. return class that was predicted most often. Below is the Python implementation of the above algorithm: from sklearn import model_selectionfrom sklearn.ensemble import BaggingClassifierfrom sklearn.tree import DecisionTreeClassifierimport pandas as pd # load the dataurl = "/home/debomit/Downloads/wine_data.xlsx"dataframe = pd.read_excel(url)arr = dataframe.valuesX = arr[:, 1:14]Y = arr[:, 0] seed = 8kfold = model_selection.KFold(n_splits = 3, random_state = seed) # initialize the base classifierbase_cls = DecisionTreeClassifier() # no. of base classifiernum_trees = 500 # bagging classifiermodel = BaggingClassifier(base_estimator = base_cls, n_estimators = num_trees, random_state = seed) results = model_selection.cross_val_score(model, X, Y, cv = kfold)print("accuracy :")print(results.mean()) Output: accuracy : 0.8372093023255814 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Activation functions in Neural Networks Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Underfitting and Overfitting 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": 25481, "s": 25453, "text": "\n20 May, 2019" }, { "code": null, "e": 26349, "s": 25481, "text": "A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it.Each base classifier is trained in parallel with a training set which is generated by randomly drawing, with replacement, N examples(or data) from the original training dataset – where N is the size of the original training set. Training set for each of the base classifiers is independent of each other. Many of the original data may be repeated in the resulting training set while others may be left out." }, { "code": null, "e": 26514, "s": 26349, "text": "Bagging reduces overfitting (variance) by averaging or voting, however, this leads to an increase in bias, which is compensated by the reduction in variance though." }, { "code": null, "e": 26772, "s": 26514, "text": "How Bagging works on training dataset ?How bagging works on an imaginary training dataset is shown below. Since Bagging resamples the original training dataset with replacement, some instance(or data) may be present multiple times while others are left out." }, { "code": null, "e": 26829, "s": 26772, "text": "Original training dataset: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10" }, { "code": null, "e": 26995, "s": 26829, "text": "Resampled training set 1: 2, 3, 3, 5, 6, 1, 8, 10, 9, 1Resampled training set 2: 1, 1, 5, 6, 3, 8, 9, 10, 2, 7Resampled training set 3: 1, 5, 8, 9, 2, 10, 9, 7, 5, 4" }, { "code": null, "e": 27033, "s": 26995, "text": "Algorithm for the Bagging classifier:" }, { "code": null, "e": 27419, "s": 27033, "text": "Classifier generation:\n\nLet N be the size of the training set.\nfor each of t iterations:\n sample N instances with replacement from the original training set.\n apply the learning algorithm to the sample.\n store the resulting classifier.\n\nClassification:\nfor each of the t classifiers:\n predict class of instance using classifier.\nreturn class that was predicted most often.\n" }, { "code": null, "e": 27479, "s": 27419, "text": " Below is the Python implementation of the above algorithm:" }, { "code": "from sklearn import model_selectionfrom sklearn.ensemble import BaggingClassifierfrom sklearn.tree import DecisionTreeClassifierimport pandas as pd # load the dataurl = \"/home/debomit/Downloads/wine_data.xlsx\"dataframe = pd.read_excel(url)arr = dataframe.valuesX = arr[:, 1:14]Y = arr[:, 0] seed = 8kfold = model_selection.KFold(n_splits = 3, random_state = seed) # initialize the base classifierbase_cls = DecisionTreeClassifier() # no. of base classifiernum_trees = 500 # bagging classifiermodel = BaggingClassifier(base_estimator = base_cls, n_estimators = num_trees, random_state = seed) results = model_selection.cross_val_score(model, X, Y, cv = kfold)print(\"accuracy :\")print(results.mean())", "e": 28256, "s": 27479, "text": null }, { "code": null, "e": 28264, "s": 28256, "text": "Output:" }, { "code": null, "e": 28295, "s": 28264, "text": "accuracy :\n0.8372093023255814\n" }, { "code": null, "e": 28312, "s": 28295, "text": "Machine Learning" }, { "code": null, "e": 28319, "s": 28312, "text": "Python" }, { "code": null, "e": 28336, "s": 28319, "text": "Machine Learning" }, { "code": null, "e": 28434, "s": 28336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28457, "s": 28434, "text": "ML | Linear Regression" }, { "code": null, "e": 28497, "s": 28457, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 28538, "s": 28497, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28571, "s": 28538, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28605, "s": 28571, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 28633, "s": 28605, "text": "Read JSON file using Python" }, { "code": null, "e": 28683, "s": 28633, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28705, "s": 28683, "text": "Python map() function" } ]
Find length of longest Fibonacci like subsequence - GeeksforGeeks
05 Apr, 2022 Given a strictly increasing array A of positive integers where, . The task is to find the length of the longest Fibonacci-like subsequence of A. If such subsequence does not exist, return 0. Examples: Input: A = [1, 3, 7, 11, 12, 14, 18] Output: 3 Explanation: The longest subsequence that is Fibonacci-like: [1, 11, 12]. Other possible subsequences are [3, 11, 14] or [7, 11, 18]. Input: A = [1, 2, 3, 4, 5, 6, 7, 8] Output: 5 Explanation: The longest subsequence that is Fibonacci-like: [1, 2, 3, 5, 8]. Naive Approach: A Fibonacci-like sequence is such that it has each two adjacent terms that determine the next expected term. For example, with 1, 1, we expect that the sequence must continue 2, 3, 5, 8, 13, ... and so on. Use Set or Map to determine quickly whether the next term of Fibonacci sequence is present in the array A or not. Because of the exponential growth of these terms, there will be not more than log(M) searches to get next element on each iteration. For each starting pair A[i], A[j], we maintain the next expected value y = A[i] + A[j] and the previously seen largest value x = A[j]. If y is in the array, then we can then update these values (x, y) -> (y, x+y) otherwise we stop immediately. Below is the implementation of above approach: C++ Java Python3 C# Javascript // CPP implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to return the max Length of// Fibonacci subsequenceint LongestFibSubseq(int A[], int n){ // Store all array elements in a hash // table unordered_set<int> S(A, A + n); int maxLen = 0, x, y; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; int length = 2; // check until next fib element is found while (S.find(y) != S.end()) { // next element of fib subseq int z = x + y; x = y; y = z; maxLen = max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0;} // Driver programint main(){ int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = sizeof(A) / sizeof(A[0]); cout << LongestFibSubseq(A, n); return 0;} // This code is written by Sanjit_Prasad // Java implementation of above approachimport java.util.*;public class GFG { // Function to return the max Length of// Fibonacci subsequence static int LongestFibSubseq(int A[], int n) { // Store all array elements in a hash // table TreeSet<Integer> S = new TreeSet<>(); for (int t : A) { // Add each element into the set S.add(t); } int maxLen = 0, x, y; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; int length = 3; // check until next fib element is found while (S.contains(y) && (y != S.last())) { // next element of fib subseq int z = x + y; x = y; y = z; maxLen = Math.max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0; } // Driver program public static void main(String[] args) { int A[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = A.length; System.out.print(LongestFibSubseq(A, n)); }}// This code is contributed by 29AjayKumar # Python3 implementation of the# above approach # Function to return the max Length# of Fibonacci subsequencedef LongestFibSubseq(A, n): # Store all array elements in # a hash table S = set(A) maxLen = 0 for i in range(0, n): for j in range(i + 1, n): x = A[j] y = A[i] + A[j] length = 2 # check until next fib # element is found while y in S: # next element of fib subseq z = x + y x = y y = z length += 1 maxLen = max(maxLen, length) return maxLen if maxLen >= 3 else 0 # Driver Codeif __name__ == "__main__": A = [1, 2, 3, 4, 5, 6, 7, 8] n = len(A) print(LongestFibSubseq(A, n)) # This code is contributed# by Rituraj Jain // C# implementation of above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the max Length of // Fibonacci subsequence static int LongestFibSubseq(int []A, int n) { // Store all array elements in a hash // table SortedSet<int> S = new SortedSet<int>(); foreach (int t in A) { // Add each element into the set S.Add(t); } int maxLen = 0, x, y; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; int length = 3; // check until next fib element is found while (S.Contains(y) && y != last(S)) { // next element of fib subseq int z = x + y; x = y; y = z; maxLen = Math.Max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0; } static int last(SortedSet<int> S) { int ans = 0; foreach(int a in S) ans = a; return ans; } // Driver Code public static void Main(String[] args) { int []A = {1, 2, 3, 4, 5, 6, 7, 8}; int n = A.Length; Console.Write(LongestFibSubseq(A, n)); }} // This code is contributed by 29AjayKumar <script> // Javascript implementation of above approach // Function to return the max Length of// Fibonacci subsequencefunction LongestFibSubseq(A, n){ // Store all array elements in a hash // table var S = new Set(A); var maxLen = 0, x, y; for (var i = 0; i < n; ++i) { for (var j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; var length = 2; // check until next fib element is found while (S.has(y)) { // next element of fib subseq var z = x + y; x = y; y = z; maxLen = Math.max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0;} // Driver programvar A = [1, 2, 3, 4, 5, 6, 7, 8];var n = A.length;document.write( LongestFibSubseq(A, n)); // This code is contributed by famously.</script> 5 Time Complexity: O(N2 * log(M)), where N is the length of array and M is max(A).Efficient Approach: To optimize the above approach the idea is to implement Dynamic Programming. Initialize a dp table, dp[a, b] that represents the length of Fibonacci sequence ends up with (a, b). Then update the table as dp[a, b] = (dp[b – a, a] + 1 ) or 2 Below is the implementation of the above approach: C++ Python3 Javascript // CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return the max Length of// Fibonacci subsequenceint LongestFibSubseq(int A[], int n){ // Initialize the unordered map unordered_map<int, int> m; int N = n, res = 0; // Initialize dp table int dp[N][N]; // Iterate till N for (int j = 0; j < N; ++j) { m[A[j]] = j; for (int i = 0; i < j; ++i) { // Check if the current integer // forms a fibonacci sequence int k = m.find(A[j] - A[i]) == m.end() ? -1 : m[A[j] - A[i]]; // Update the dp table dp[i][j] = (A[j] - A[i] < A[i] && k >= 0) ? dp[k][i] + 1 : 2; res = max(res, dp[i][j]); } } // Return the answer return res > 2 ? res : 0;} // Driver programint main(){ int A[] = { 1, 3, 7, 11, 12, 14, 18 }; int n = sizeof(A) / sizeof(A[0]); cout << LongestFibSubseq(A, n); return 0;} # Python program for the above approach # Function to return the max Length of# Fibonacci subsequencedef LongestFibSubseq(A, n): # Initialize the unordered map m = {} N, res = n, 0 # Initialize dp table dp = [ [0 for i in range(N) ] for J in range(N) ] # Iterate till N for j in range(N): m[A[j]] = j for i in range(j): # Check if the current integer # forms a fibonacci sequence k = -1 if ((A[j] - A[i]) not in m) else m[A[j] - A[i]] # Update the dp table dp[i][j] = dp[k][i] + 1 if (A[j] - A[i] < A[i] and k >= 0) else 2 res = max(res, dp[i][j]) # Return the answer return res if res > 2 else 0 # Driver programA = [ 1, 3, 7, 11, 12, 14, 18 ]n = len(A)print(LongestFibSubseq(A, n)) # This code is contributed by shinjanpatra <script> // JavaScript program for the above approach // Function to return the max Length of// Fibonacci subsequencefunction LongestFibSubseq(A,n){ // Initialize the unordered map let m = new Map(); let N = n, res = 0; // Initialize dp table let dp = new Array(N); for(let i=0;i<N;i++){ dp[i] = new Array(N); } // Iterate till N for (let j = 0; j < N; ++j) { m.set(A[j],j); for (let i = 0; i < j; ++i) { // Check if the current integer // forms a fibonacci sequence let k = m.has(A[j] - A[i]) == false ? -1 : m.get(A[j] - A[i]); // Update the dp table dp[i][j] = (A[j] - A[i] < A[i] && k >= 0) ? dp[k][i] + 1 : 2; res = Math.max(res, dp[i][j]); } } // Return the answer return res > 2 ? res : 0;} // Driver program let A = [ 1, 3, 7, 11, 12, 14, 18 ];let n = A.length;document.write(LongestFibSubseq(A, n)); // code is contributed by shinjanpatra </script> 3 Time Complexity: O(N2), where N is the length of the array. rituraj_jain 29AjayKumar rishabhgaurav007 famously sagar0719kumar shinjanpatra Fibonacci Arrays Greedy Hash Mathematical Searching Arrays Searching Hash Greedy Mathematical Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26117, "s": 26089, "text": "\n05 Apr, 2022" }, { "code": null, "e": 26182, "s": 26117, "text": "Given a strictly increasing array A of positive integers where, " }, { "code": null, "e": 26311, "s": 26184, "text": ". The task is to find the length of the longest Fibonacci-like subsequence of A. If such subsequence does not exist, return 0." }, { "code": null, "e": 26321, "s": 26311, "text": "Examples:" }, { "code": null, "e": 26502, "s": 26321, "text": "Input: A = [1, 3, 7, 11, 12, 14, 18] Output: 3 Explanation: The longest subsequence that is Fibonacci-like: [1, 11, 12]. Other possible subsequences are [3, 11, 14] or [7, 11, 18]." }, { "code": null, "e": 26626, "s": 26502, "text": "Input: A = [1, 2, 3, 4, 5, 6, 7, 8] Output: 5 Explanation: The longest subsequence that is Fibonacci-like: [1, 2, 3, 5, 8]." }, { "code": null, "e": 26753, "s": 26626, "text": "Naive Approach: A Fibonacci-like sequence is such that it has each two adjacent terms that determine the next expected term. " }, { "code": null, "e": 26850, "s": 26753, "text": "For example, with 1, 1, we expect that the sequence must continue 2, 3, 5, 8, 13, ... and so on." }, { "code": null, "e": 27097, "s": 26850, "text": "Use Set or Map to determine quickly whether the next term of Fibonacci sequence is present in the array A or not. Because of the exponential growth of these terms, there will be not more than log(M) searches to get next element on each iteration." }, { "code": null, "e": 27341, "s": 27097, "text": "For each starting pair A[i], A[j], we maintain the next expected value y = A[i] + A[j] and the previously seen largest value x = A[j]. If y is in the array, then we can then update these values (x, y) -> (y, x+y) otherwise we stop immediately." }, { "code": null, "e": 27389, "s": 27341, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27393, "s": 27389, "text": "C++" }, { "code": null, "e": 27398, "s": 27393, "text": "Java" }, { "code": null, "e": 27406, "s": 27398, "text": "Python3" }, { "code": null, "e": 27409, "s": 27406, "text": "C#" }, { "code": null, "e": 27420, "s": 27409, "text": "Javascript" }, { "code": "// CPP implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to return the max Length of// Fibonacci subsequenceint LongestFibSubseq(int A[], int n){ // Store all array elements in a hash // table unordered_set<int> S(A, A + n); int maxLen = 0, x, y; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; int length = 2; // check until next fib element is found while (S.find(y) != S.end()) { // next element of fib subseq int z = x + y; x = y; y = z; maxLen = max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0;} // Driver programint main(){ int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = sizeof(A) / sizeof(A[0]); cout << LongestFibSubseq(A, n); return 0;} // This code is written by Sanjit_Prasad", "e": 28395, "s": 27420, "text": null }, { "code": "// Java implementation of above approachimport java.util.*;public class GFG { // Function to return the max Length of// Fibonacci subsequence static int LongestFibSubseq(int A[], int n) { // Store all array elements in a hash // table TreeSet<Integer> S = new TreeSet<>(); for (int t : A) { // Add each element into the set S.add(t); } int maxLen = 0, x, y; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; int length = 3; // check until next fib element is found while (S.contains(y) && (y != S.last())) { // next element of fib subseq int z = x + y; x = y; y = z; maxLen = Math.max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0; } // Driver program public static void main(String[] args) { int A[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = A.length; System.out.print(LongestFibSubseq(A, n)); }}// This code is contributed by 29AjayKumar", "e": 29610, "s": 28395, "text": null }, { "code": "# Python3 implementation of the# above approach # Function to return the max Length# of Fibonacci subsequencedef LongestFibSubseq(A, n): # Store all array elements in # a hash table S = set(A) maxLen = 0 for i in range(0, n): for j in range(i + 1, n): x = A[j] y = A[i] + A[j] length = 2 # check until next fib # element is found while y in S: # next element of fib subseq z = x + y x = y y = z length += 1 maxLen = max(maxLen, length) return maxLen if maxLen >= 3 else 0 # Driver Codeif __name__ == \"__main__\": A = [1, 2, 3, 4, 5, 6, 7, 8] n = len(A) print(LongestFibSubseq(A, n)) # This code is contributed# by Rituraj Jain", "e": 30449, "s": 29610, "text": null }, { "code": "// C# implementation of above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the max Length of // Fibonacci subsequence static int LongestFibSubseq(int []A, int n) { // Store all array elements in a hash // table SortedSet<int> S = new SortedSet<int>(); foreach (int t in A) { // Add each element into the set S.Add(t); } int maxLen = 0, x, y; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; int length = 3; // check until next fib element is found while (S.Contains(y) && y != last(S)) { // next element of fib subseq int z = x + y; x = y; y = z; maxLen = Math.Max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0; } static int last(SortedSet<int> S) { int ans = 0; foreach(int a in S) ans = a; return ans; } // Driver Code public static void Main(String[] args) { int []A = {1, 2, 3, 4, 5, 6, 7, 8}; int n = A.Length; Console.Write(LongestFibSubseq(A, n)); }} // This code is contributed by 29AjayKumar", "e": 31881, "s": 30449, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to return the max Length of// Fibonacci subsequencefunction LongestFibSubseq(A, n){ // Store all array elements in a hash // table var S = new Set(A); var maxLen = 0, x, y; for (var i = 0; i < n; ++i) { for (var j = i + 1; j < n; ++j) { x = A[j]; y = A[i] + A[j]; var length = 2; // check until next fib element is found while (S.has(y)) { // next element of fib subseq var z = x + y; x = y; y = z; maxLen = Math.max(maxLen, ++length); } } } return maxLen >= 3 ? maxLen : 0;} // Driver programvar A = [1, 2, 3, 4, 5, 6, 7, 8];var n = A.length;document.write( LongestFibSubseq(A, n)); // This code is contributed by famously.</script>", "e": 32765, "s": 31881, "text": null }, { "code": null, "e": 32767, "s": 32765, "text": "5" }, { "code": null, "e": 33108, "s": 32767, "text": "Time Complexity: O(N2 * log(M)), where N is the length of array and M is max(A).Efficient Approach: To optimize the above approach the idea is to implement Dynamic Programming. Initialize a dp table, dp[a, b] that represents the length of Fibonacci sequence ends up with (a, b). Then update the table as dp[a, b] = (dp[b – a, a] + 1 ) or 2 " }, { "code": null, "e": 33160, "s": 33108, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 33164, "s": 33160, "text": "C++" }, { "code": null, "e": 33172, "s": 33164, "text": "Python3" }, { "code": null, "e": 33183, "s": 33172, "text": "Javascript" }, { "code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return the max Length of// Fibonacci subsequenceint LongestFibSubseq(int A[], int n){ // Initialize the unordered map unordered_map<int, int> m; int N = n, res = 0; // Initialize dp table int dp[N][N]; // Iterate till N for (int j = 0; j < N; ++j) { m[A[j]] = j; for (int i = 0; i < j; ++i) { // Check if the current integer // forms a fibonacci sequence int k = m.find(A[j] - A[i]) == m.end() ? -1 : m[A[j] - A[i]]; // Update the dp table dp[i][j] = (A[j] - A[i] < A[i] && k >= 0) ? dp[k][i] + 1 : 2; res = max(res, dp[i][j]); } } // Return the answer return res > 2 ? res : 0;} // Driver programint main(){ int A[] = { 1, 3, 7, 11, 12, 14, 18 }; int n = sizeof(A) / sizeof(A[0]); cout << LongestFibSubseq(A, n); return 0;}", "e": 34236, "s": 33183, "text": null }, { "code": "# Python program for the above approach # Function to return the max Length of# Fibonacci subsequencedef LongestFibSubseq(A, n): # Initialize the unordered map m = {} N, res = n, 0 # Initialize dp table dp = [ [0 for i in range(N) ] for J in range(N) ] # Iterate till N for j in range(N): m[A[j]] = j for i in range(j): # Check if the current integer # forms a fibonacci sequence k = -1 if ((A[j] - A[i]) not in m) else m[A[j] - A[i]] # Update the dp table dp[i][j] = dp[k][i] + 1 if (A[j] - A[i] < A[i] and k >= 0) else 2 res = max(res, dp[i][j]) # Return the answer return res if res > 2 else 0 # Driver programA = [ 1, 3, 7, 11, 12, 14, 18 ]n = len(A)print(LongestFibSubseq(A, n)) # This code is contributed by shinjanpatra", "e": 35087, "s": 34236, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to return the max Length of// Fibonacci subsequencefunction LongestFibSubseq(A,n){ // Initialize the unordered map let m = new Map(); let N = n, res = 0; // Initialize dp table let dp = new Array(N); for(let i=0;i<N;i++){ dp[i] = new Array(N); } // Iterate till N for (let j = 0; j < N; ++j) { m.set(A[j],j); for (let i = 0; i < j; ++i) { // Check if the current integer // forms a fibonacci sequence let k = m.has(A[j] - A[i]) == false ? -1 : m.get(A[j] - A[i]); // Update the dp table dp[i][j] = (A[j] - A[i] < A[i] && k >= 0) ? dp[k][i] + 1 : 2; res = Math.max(res, dp[i][j]); } } // Return the answer return res > 2 ? res : 0;} // Driver program let A = [ 1, 3, 7, 11, 12, 14, 18 ];let n = A.length;document.write(LongestFibSubseq(A, n)); // code is contributed by shinjanpatra </script>", "e": 36172, "s": 35087, "text": null }, { "code": null, "e": 36174, "s": 36172, "text": "3" }, { "code": null, "e": 36235, "s": 36174, "text": "Time Complexity: O(N2), where N is the length of the array. " }, { "code": null, "e": 36248, "s": 36235, "text": "rituraj_jain" }, { "code": null, "e": 36260, "s": 36248, "text": "29AjayKumar" }, { "code": null, "e": 36277, "s": 36260, "text": "rishabhgaurav007" }, { "code": null, "e": 36286, "s": 36277, "text": "famously" }, { "code": null, "e": 36301, "s": 36286, "text": "sagar0719kumar" }, { "code": null, "e": 36314, "s": 36301, "text": "shinjanpatra" }, { "code": null, "e": 36324, "s": 36314, "text": "Fibonacci" }, { "code": null, "e": 36331, "s": 36324, "text": "Arrays" }, { "code": null, "e": 36338, "s": 36331, "text": "Greedy" }, { "code": null, "e": 36343, "s": 36338, "text": "Hash" }, { "code": null, "e": 36356, "s": 36343, "text": "Mathematical" }, { "code": null, "e": 36366, "s": 36356, "text": "Searching" }, { "code": null, "e": 36373, "s": 36366, "text": "Arrays" }, { "code": null, "e": 36383, "s": 36373, "text": "Searching" }, { "code": null, "e": 36388, "s": 36383, "text": "Hash" }, { "code": null, "e": 36395, "s": 36388, "text": "Greedy" }, { "code": null, "e": 36408, "s": 36395, "text": "Mathematical" }, { "code": null, "e": 36418, "s": 36408, "text": "Fibonacci" }, { "code": null, "e": 36516, "s": 36418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36539, "s": 36516, "text": "Introduction to Arrays" }, { "code": null, "e": 36571, "s": 36539, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36585, "s": 36571, "text": "Linear Search" }, { "code": null, "e": 36606, "s": 36585, "text": "Linked List vs Array" }, { "code": null, "e": 36691, "s": 36606, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 36742, "s": 36691, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 36793, "s": 36742, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 36851, "s": 36793, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 36911, "s": 36851, "text": "Write a program to print all permutations of a given string" } ]
Longest substring where all the characters appear at least K times | Set 3 - GeeksforGeeks
02 May, 2022 Given a string str and an integer K, the task is to find the length of the longest substring S such that every character in S appears at least K times. Examples: Input: str = “aabbba”, K = 3Output: 6Explanation: In substring “aabbba”, each character repeats at least k times and its length is 6. Input: str = “ababacb”, K = 3Output: 0Explanation: There is no substring where each character repeats at least k times. Naive Approach: The simplest approach to solve the given problem is discussed in Set 1. Time Complexity: O(N2)Auxiliary Space: O(26) Divide and Conquer Approach: The divide and conquer approach for the given problem is discussed in the Set 2. Time Complexity: O(N*log N)Auxiliary Space: O(26) Efficient Approach: The above two approaches can be optimized further by using Sliding Window technique. Follow the steps below to solve the problem: Store the number of unique characters in the string str in a variable, say unique. Initialize an array freq[] of size 26 with {0} and store the frequency of each character in this array. Iterate over the range [1, unique] using the variable curr_unique. In each iteration, curr_unique is the maximum number of unique characters that must be present in the window.Reinitialize the array freq[] with {0} to store the frequency of each character in this window.Initialize start and end as 0, to store the starting and the ending point of the window respectively.Use two variables cnt, for storing the number of unique characters and countK, for storing the number of characters with at least K repeating characters in the current window.Now, iterate a loop while end < N, and perform the following:If the value of cnt is less than or equals to curr_unique, then expand the window from the right by adding a character to the end of the window. And increment its frequency by 1 in freq[].Otherwise, reduce the window from the left by removing a character from start and decrementing its frequency by 1 in freq[].At every step, update the values of cnt and countK.If the value of cnt is same as curr_unique and each character occurs at least K times, then update the overall maximum length and store it in ans. Reinitialize the array freq[] with {0} to store the frequency of each character in this window. Initialize start and end as 0, to store the starting and the ending point of the window respectively. Use two variables cnt, for storing the number of unique characters and countK, for storing the number of characters with at least K repeating characters in the current window. Now, iterate a loop while end < N, and perform the following:If the value of cnt is less than or equals to curr_unique, then expand the window from the right by adding a character to the end of the window. And increment its frequency by 1 in freq[].Otherwise, reduce the window from the left by removing a character from start and decrementing its frequency by 1 in freq[].At every step, update the values of cnt and countK.If the value of cnt is same as curr_unique and each character occurs at least K times, then update the overall maximum length and store it in ans. If the value of cnt is less than or equals to curr_unique, then expand the window from the right by adding a character to the end of the window. And increment its frequency by 1 in freq[]. Otherwise, reduce the window from the left by removing a character from start and decrementing its frequency by 1 in freq[]. At every step, update the values of cnt and countK. If the value of cnt is same as curr_unique and each character occurs at least K times, then update the overall maximum length and store it in ans. After completing the above steps, print the value of ans as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of// the longest substringint longestSubstring(string s, int k){ // Store the required answer int ans = 0; // Create a frequency map of the // characters of the string int freq[26] = { 0 }; // Store the length of the string int n = s.size(); // Traverse the string, s for (int i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i] - 'a']++; // Stores count of unique characters int unique = 0; // Find the number of unique // characters in string for (int i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 memset(freq, 0, sizeof(freq)); // Stores the start and the // end of the window int start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times int cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { int ind = s[end] - 'a'; // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { int ind = s[start] - 'a'; // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = max(ans, end - start); } } // return the answer return ans;} // Driver Codeint main(){ string S = "aabbba"; int K = 3; cout << longestSubstring(S, K) << endl; return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the length of// the longest subStringstatic void longestSubString(char[] s, int k){ // Store the required answer int ans = 0; // Create a frequency map of the // characters of the String int freq[] = new int[26]; // Store the length of the String int n = s.length; // Traverse the String, s for (int i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i] - 'a']++; // Stores count of unique characters int unique = 0; // Find the number of unique // characters in String for (int i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 Arrays.fill(freq, 0); // Stores the start and the // end of the window int start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times int cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { int ind = s[end] - 'a'; // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { int ind = s[start] - 'a'; // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = Math.max(ans, end - start); } } // Print the answer System.out.print(ans);} // Driver Codepublic static void main(String[] args){ String S = "aabbba"; int K = 3; longestSubString(S.toCharArray(), K);}} // This code is contributed by 29AjayKumar # Python3 program for the above approach # Function to find the length of# the longest substringdef longestSubstring(s, k) : # Store the required answer ans = 0 # Create a frequency map of the # characters of the string freq = [0]*26 # Store the length of the string n = len(s) # Traverse the string, s for i in range(n) : # Increment the frequency of # the current character by 1 freq[ord(s[i]) - ord('a')] += 1 # Stores count of unique characters unique = 0 # Find the number of unique # characters in string for i in range(26) : if (freq[i] != 0) : unique += 1 # Iterate in range [1, unique] for curr_unique in range(1, unique + 1) : # Initialize frequency of all # characters as 0 Freq = [0]*26 # Stores the start and the # end of the window start, end = 0, 0 # Stores the current number of # unique characters and characters # occuring atleast K times cnt, count_k = 0, 0 while (end < n) : if (cnt <= curr_unique) : ind = ord(s[end]) - ord('a') # New unique character if (Freq[ind] == 0) : cnt += 1 Freq[ind] += 1 # New character which # occurs atleast k times if (Freq[ind] == k) : count_k += 1 # Expand window by # incrementing end by 1 end += 1 else : ind = ord(s[start]) - ord('a') # Check if this character # is present atleast k times if (Freq[ind] == k) : count_k -= 1 Freq[ind] -= 1 # Check if this character # is unique if (Freq[ind] == 0) : cnt -= 1 # Shrink the window by # incrementing start by 1 start += 1 # If there are curr_unique # characters and each character # is atleast k times if ((cnt == curr_unique) and (count_k == curr_unique)) : # Update the overall # maximum length ans = max(ans, end - start) # Print the answer print(ans) S = "aabbba"K = 3longestSubstring(S, K) # This code is contributed by divyesh072019. // C# program to implement// the above approachusing System; class GFG{ // Function to find the length of// the longest substringstatic void longestSubstring(string s, int k){ // Store the required answer int ans = 0; // Create a frequency map of the // characters of the string int[] freq = new int[26]; // Store the length of the string int n = s.Length; // Traverse the string, s for (int i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i] - 'a']++; // Stores count of unique characters int unique = 0; // Find the number of unique // characters in string for (int i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 for (int i = 0; i < freq.Length; i++) { freq[i] = 0; } // Stores the start and the // end of the window int start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times int cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { int ind = s[end] - 'a'; // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { int ind = s[start] - 'a'; // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = Math.Max(ans, end - start); } } // Print the answer Console.Write(ans);} // Driver Codepublic static void Main(){ string S = "aabbba"; int K = 3; longestSubstring(S, K);}} // This code is contributed by splevel62. <script> // Javascript program to implement // the above approach // Function to find the length of // the longest substring function longestSubstring(s, k) { // Store the required answer let ans = 0; // Create a frequency map of the // characters of the string let freq = new Array(26); freq.fill(0); // Store the length of the string let n = s.length; // Traverse the string, s for (let i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i].charCodeAt() - 'a'.charCodeAt()]++; // Stores count of unique characters let unique = 0; // Find the number of unique // characters in string for (let i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (let curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 for (let i = 0; i < freq.length; i++) { freq[i] = 0; } // Stores the start and the // end of the window let start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times let cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { let ind = s[end].charCodeAt() - 'a'.charCodeAt(); // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { let ind = s[start].charCodeAt() - 'a'.charCodeAt(); // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = Math.max(ans, end - start); } } // Print the answer document.write(ans); } let S = "aabbba"; let K = 3; longestSubstring(S, K); </script> 6 Time Complexity: O(N)Auxiliary Space: O(1) splevel62 29AjayKumar divyesh072019 suresh07 sagar0719kumar adityadas285 frequency-counting sliding-window substring Hash Searching Strings sliding-window Searching Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rearrange an array such that arr[i] = i Quadratic Probing in Hashing What are Hash Functions and How to choose a good Hash Function? Hashing in Java Index Mapping (or Trivial Hashing) with negatives allowed Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26401, "s": 26373, "text": "\n02 May, 2022" }, { "code": null, "e": 26553, "s": 26401, "text": "Given a string str and an integer K, the task is to find the length of the longest substring S such that every character in S appears at least K times." }, { "code": null, "e": 26563, "s": 26553, "text": "Examples:" }, { "code": null, "e": 26697, "s": 26563, "text": "Input: str = “aabbba”, K = 3Output: 6Explanation: In substring “aabbba”, each character repeats at least k times and its length is 6." }, { "code": null, "e": 26817, "s": 26697, "text": "Input: str = “ababacb”, K = 3Output: 0Explanation: There is no substring where each character repeats at least k times." }, { "code": null, "e": 26950, "s": 26817, "text": "Naive Approach: The simplest approach to solve the given problem is discussed in Set 1. Time Complexity: O(N2)Auxiliary Space: O(26)" }, { "code": null, "e": 27110, "s": 26950, "text": "Divide and Conquer Approach: The divide and conquer approach for the given problem is discussed in the Set 2. Time Complexity: O(N*log N)Auxiliary Space: O(26)" }, { "code": null, "e": 27260, "s": 27110, "text": "Efficient Approach: The above two approaches can be optimized further by using Sliding Window technique. Follow the steps below to solve the problem:" }, { "code": null, "e": 27343, "s": 27260, "text": "Store the number of unique characters in the string str in a variable, say unique." }, { "code": null, "e": 27447, "s": 27343, "text": "Initialize an array freq[] of size 26 with {0} and store the frequency of each character in this array." }, { "code": null, "e": 28565, "s": 27447, "text": "Iterate over the range [1, unique] using the variable curr_unique. In each iteration, curr_unique is the maximum number of unique characters that must be present in the window.Reinitialize the array freq[] with {0} to store the frequency of each character in this window.Initialize start and end as 0, to store the starting and the ending point of the window respectively.Use two variables cnt, for storing the number of unique characters and countK, for storing the number of characters with at least K repeating characters in the current window.Now, iterate a loop while end < N, and perform the following:If the value of cnt is less than or equals to curr_unique, then expand the window from the right by adding a character to the end of the window. And increment its frequency by 1 in freq[].Otherwise, reduce the window from the left by removing a character from start and decrementing its frequency by 1 in freq[].At every step, update the values of cnt and countK.If the value of cnt is same as curr_unique and each character occurs at least K times, then update the overall maximum length and store it in ans." }, { "code": null, "e": 28661, "s": 28565, "text": "Reinitialize the array freq[] with {0} to store the frequency of each character in this window." }, { "code": null, "e": 28763, "s": 28661, "text": "Initialize start and end as 0, to store the starting and the ending point of the window respectively." }, { "code": null, "e": 28939, "s": 28763, "text": "Use two variables cnt, for storing the number of unique characters and countK, for storing the number of characters with at least K repeating characters in the current window." }, { "code": null, "e": 29510, "s": 28939, "text": "Now, iterate a loop while end < N, and perform the following:If the value of cnt is less than or equals to curr_unique, then expand the window from the right by adding a character to the end of the window. And increment its frequency by 1 in freq[].Otherwise, reduce the window from the left by removing a character from start and decrementing its frequency by 1 in freq[].At every step, update the values of cnt and countK.If the value of cnt is same as curr_unique and each character occurs at least K times, then update the overall maximum length and store it in ans." }, { "code": null, "e": 29699, "s": 29510, "text": "If the value of cnt is less than or equals to curr_unique, then expand the window from the right by adding a character to the end of the window. And increment its frequency by 1 in freq[]." }, { "code": null, "e": 29824, "s": 29699, "text": "Otherwise, reduce the window from the left by removing a character from start and decrementing its frequency by 1 in freq[]." }, { "code": null, "e": 29876, "s": 29824, "text": "At every step, update the values of cnt and countK." }, { "code": null, "e": 30023, "s": 29876, "text": "If the value of cnt is same as curr_unique and each character occurs at least K times, then update the overall maximum length and store it in ans." }, { "code": null, "e": 30095, "s": 30023, "text": "After completing the above steps, print the value of ans as the result." }, { "code": null, "e": 30146, "s": 30095, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30150, "s": 30146, "text": "C++" }, { "code": null, "e": 30155, "s": 30150, "text": "Java" }, { "code": null, "e": 30163, "s": 30155, "text": "Python3" }, { "code": null, "e": 30166, "s": 30163, "text": "C#" }, { "code": null, "e": 30177, "s": 30166, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of// the longest substringint longestSubstring(string s, int k){ // Store the required answer int ans = 0; // Create a frequency map of the // characters of the string int freq[26] = { 0 }; // Store the length of the string int n = s.size(); // Traverse the string, s for (int i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i] - 'a']++; // Stores count of unique characters int unique = 0; // Find the number of unique // characters in string for (int i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 memset(freq, 0, sizeof(freq)); // Stores the start and the // end of the window int start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times int cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { int ind = s[end] - 'a'; // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { int ind = s[start] - 'a'; // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = max(ans, end - start); } } // return the answer return ans;} // Driver Codeint main(){ string S = \"aabbba\"; int K = 3; cout << longestSubstring(S, K) << endl; return 0;}", "e": 32851, "s": 30177, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the length of// the longest subStringstatic void longestSubString(char[] s, int k){ // Store the required answer int ans = 0; // Create a frequency map of the // characters of the String int freq[] = new int[26]; // Store the length of the String int n = s.length; // Traverse the String, s for (int i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i] - 'a']++; // Stores count of unique characters int unique = 0; // Find the number of unique // characters in String for (int i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 Arrays.fill(freq, 0); // Stores the start and the // end of the window int start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times int cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { int ind = s[end] - 'a'; // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { int ind = s[start] - 'a'; // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = Math.max(ans, end - start); } } // Print the answer System.out.print(ans);} // Driver Codepublic static void main(String[] args){ String S = \"aabbba\"; int K = 3; longestSubString(S.toCharArray(), K);}} // This code is contributed by 29AjayKumar", "e": 35617, "s": 32851, "text": null }, { "code": "# Python3 program for the above approach # Function to find the length of# the longest substringdef longestSubstring(s, k) : # Store the required answer ans = 0 # Create a frequency map of the # characters of the string freq = [0]*26 # Store the length of the string n = len(s) # Traverse the string, s for i in range(n) : # Increment the frequency of # the current character by 1 freq[ord(s[i]) - ord('a')] += 1 # Stores count of unique characters unique = 0 # Find the number of unique # characters in string for i in range(26) : if (freq[i] != 0) : unique += 1 # Iterate in range [1, unique] for curr_unique in range(1, unique + 1) : # Initialize frequency of all # characters as 0 Freq = [0]*26 # Stores the start and the # end of the window start, end = 0, 0 # Stores the current number of # unique characters and characters # occuring atleast K times cnt, count_k = 0, 0 while (end < n) : if (cnt <= curr_unique) : ind = ord(s[end]) - ord('a') # New unique character if (Freq[ind] == 0) : cnt += 1 Freq[ind] += 1 # New character which # occurs atleast k times if (Freq[ind] == k) : count_k += 1 # Expand window by # incrementing end by 1 end += 1 else : ind = ord(s[start]) - ord('a') # Check if this character # is present atleast k times if (Freq[ind] == k) : count_k -= 1 Freq[ind] -= 1 # Check if this character # is unique if (Freq[ind] == 0) : cnt -= 1 # Shrink the window by # incrementing start by 1 start += 1 # If there are curr_unique # characters and each character # is atleast k times if ((cnt == curr_unique) and (count_k == curr_unique)) : # Update the overall # maximum length ans = max(ans, end - start) # Print the answer print(ans) S = \"aabbba\"K = 3longestSubstring(S, K) # This code is contributed by divyesh072019.", "e": 38068, "s": 35617, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to find the length of// the longest substringstatic void longestSubstring(string s, int k){ // Store the required answer int ans = 0; // Create a frequency map of the // characters of the string int[] freq = new int[26]; // Store the length of the string int n = s.Length; // Traverse the string, s for (int i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i] - 'a']++; // Stores count of unique characters int unique = 0; // Find the number of unique // characters in string for (int i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 for (int i = 0; i < freq.Length; i++) { freq[i] = 0; } // Stores the start and the // end of the window int start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times int cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { int ind = s[end] - 'a'; // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { int ind = s[start] - 'a'; // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = Math.Max(ans, end - start); } } // Print the answer Console.Write(ans);} // Driver Codepublic static void Main(){ string S = \"aabbba\"; int K = 3; longestSubstring(S, K);}} // This code is contributed by splevel62.", "e": 40874, "s": 38068, "text": null }, { "code": "<script> // Javascript program to implement // the above approach // Function to find the length of // the longest substring function longestSubstring(s, k) { // Store the required answer let ans = 0; // Create a frequency map of the // characters of the string let freq = new Array(26); freq.fill(0); // Store the length of the string let n = s.length; // Traverse the string, s for (let i = 0; i < n; i++) // Increment the frequency of // the current character by 1 freq[s[i].charCodeAt() - 'a'.charCodeAt()]++; // Stores count of unique characters let unique = 0; // Find the number of unique // characters in string for (let i = 0; i < 26; i++) if (freq[i] != 0) unique++; // Iterate in range [1, unique] for (let curr_unique = 1; curr_unique <= unique; curr_unique++) { // Initialize frequency of all // characters as 0 for (let i = 0; i < freq.length; i++) { freq[i] = 0; } // Stores the start and the // end of the window let start = 0, end = 0; // Stores the current number of // unique characters and characters // occuring atleast K times let cnt = 0, count_k = 0; while (end < n) { if (cnt <= curr_unique) { let ind = s[end].charCodeAt() - 'a'.charCodeAt(); // New unique character if (freq[ind] == 0) cnt++; freq[ind]++; // New character which // occurs atleast k times if (freq[ind] == k) count_k++; // Expand window by // incrementing end by 1 end++; } else { let ind = s[start].charCodeAt() - 'a'.charCodeAt(); // Check if this character // is present atleast k times if (freq[ind] == k) count_k--; freq[ind]--; // Check if this character // is unique if (freq[ind] == 0) cnt--; // Shrink the window by // incrementing start by 1 start++; } // If there are curr_unique // characters and each character // is atleast k times if (cnt == curr_unique && count_k == curr_unique) // Update the overall // maximum length ans = Math.max(ans, end - start); } } // Print the answer document.write(ans); } let S = \"aabbba\"; let K = 3; longestSubstring(S, K); </script>", "e": 44097, "s": 40874, "text": null }, { "code": null, "e": 44100, "s": 44097, "text": "6\n" }, { "code": null, "e": 44144, "s": 44100, "text": "Time Complexity: O(N)Auxiliary Space: O(1) " }, { "code": null, "e": 44154, "s": 44144, "text": "splevel62" }, { "code": null, "e": 44166, "s": 44154, "text": "29AjayKumar" }, { "code": null, "e": 44180, "s": 44166, "text": "divyesh072019" }, { "code": null, "e": 44189, "s": 44180, "text": "suresh07" }, { "code": null, "e": 44204, "s": 44189, "text": "sagar0719kumar" }, { "code": null, "e": 44217, "s": 44204, "text": "adityadas285" }, { "code": null, "e": 44236, "s": 44217, "text": "frequency-counting" }, { "code": null, "e": 44251, "s": 44236, "text": "sliding-window" }, { "code": null, "e": 44261, "s": 44251, "text": "substring" }, { "code": null, "e": 44266, "s": 44261, "text": "Hash" }, { "code": null, "e": 44276, "s": 44266, "text": "Searching" }, { "code": null, "e": 44284, "s": 44276, "text": "Strings" }, { "code": null, "e": 44299, "s": 44284, "text": "sliding-window" }, { "code": null, "e": 44309, "s": 44299, "text": "Searching" }, { "code": null, "e": 44314, "s": 44309, "text": "Hash" }, { "code": null, "e": 44322, "s": 44314, "text": "Strings" }, { "code": null, "e": 44420, "s": 44322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44460, "s": 44420, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 44489, "s": 44460, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 44553, "s": 44489, "text": "What are Hash Functions and How to choose a good Hash Function?" }, { "code": null, "e": 44569, "s": 44553, "text": "Hashing in Java" }, { "code": null, "e": 44627, "s": 44569, "text": "Index Mapping (or Trivial Hashing) with negatives allowed" }, { "code": null, "e": 44641, "s": 44627, "text": "Binary Search" }, { "code": null, "e": 44709, "s": 44641, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 44723, "s": 44709, "text": "Linear Search" }, { "code": null, "e": 44771, "s": 44723, "text": "Search an element in a sorted and rotated array" } ]
Find all missing numbers from a given sorted array - GeeksforGeeks
08 Feb, 2022 Given a sorted array arr[] of N integers, The task is to find the multiple missing elements in the array between the ranges [arr[0], arr[N-1]]. Examples: Input: arr[] = {6, 7, 10, 11, 13}Output: 8 9 12 Explanation: The elements of the array are present in the range of the maximum and minimum array element [6, 13]. Therefore, the total values will be {6, 7, 8, 9, 10, 11, 12, 13}. The elements from the above range which are missing from the array are {8, 9, 12}. Input: arr[] = {1, 2, 4, 6}Output: 3 5 Naive Approach: The naive idea is to iterate over the difference between the consecutive pair of elements and the print all the numbers in this range if the difference is non-zero. Below are the steps: Initialize the variable diff which is equal to arr[0] – 0.Now traverse the array and see if the difference between arr[i] – i and diff is zero or not.If the difference is not equal to zero in the above steps, then the missing element is found.To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff.Now increment the diff as the difference is increased now.Repeat from step 2 until all the missing numbers are not found. Initialize the variable diff which is equal to arr[0] – 0. Now traverse the array and see if the difference between arr[i] – i and diff is zero or not. If the difference is not equal to zero in the above steps, then the missing element is found. To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff. Now increment the diff as the difference is increased now. Repeat from step 2 until all the missing numbers are not found. 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 find the missing elementsvoid printMissingElements(int arr[], int N){ // Initialize diff int diff = arr[0] - 0; for (int i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { cout << i + diff << " "; diff++; } } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = sizeof(arr) / sizeof(int); // Function Call printMissingElements(arr, N); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to find the missing elementsstatic void printMissingElements(int arr[], int N){ // Initialize diff int diff = arr[0] - 0; for(int i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { System.out.print((i + diff) + " "); diff++; } } }} // Driver Codepublic static void main (String[] args){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = arr.length; // Function call printMissingElements(arr, N);}} // This code is contributed by offbeat # Python3 program for the above approach # Function to find the missing elementsdef printMissingElements(arr, N): # Initialize diff diff = arr[0] for i in range(N): # Check if diff and arr[i]-i # both are equal or not if(arr[i] - i != diff): # Loop for consecutive # missing elements while(diff < arr[i] - i): print(i + diff, end = " ") diff += 1 # Driver Code # Given array arr[]arr = [ 6, 7, 10, 11, 13 ] N = len(arr) # Function callprintMissingElements(arr, N) # This code is contributed by Shivam Singh // C# program for the above approachusing System; class GFG{ // Function to find the missing elementsstatic void printMissingElements(int[] arr, int N){ // Initialize diff int diff = arr[0] - 0; for(int i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { Console.Write(i + diff + " "); diff++; } } }} // Driver codestatic void Main(){ // Given array arr[] int[] arr = { 6, 7, 10, 11, 13 }; int N = arr.Length; // Function call printMissingElements(arr, N);}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program to gather characters// of a string in minimum cost // Function to find the missing elementsfunction prletMissingElements(arr, N){ // Initialize diff let diff = arr[0] - 0; for(let i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { document.write((i + diff) + " "); diff++; } } }} // Driver Code // Given array arr[] let arr = [ 6, 7, 10, 11, 13 ]; let N = arr.length; // Function call prletMissingElements(arr, N); </script> 8 9 12 Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: The idea is to use Hashing to optimize the above approach. Create a boolean array(say b[]) of size equal to the maximum element in the array and mark only those positions in the array b[] which are present in the given array. Print all the index in the array b[] that are not marked. Below are the steps: Initialize a boolean array b[] with zero of size equals to the maximum element of the array.Iterate over the given array and mark for each element in the given array mark that index as true in the array b[].Now traverse the given array b[] from index arr[0] and print those index whose value is false as they are the element that is missing in the given array. Initialize a boolean array b[] with zero of size equals to the maximum element of the array. Iterate over the given array and mark for each element in the given array mark that index as true in the array b[]. Now traverse the given array b[] from index arr[0] and print those index whose value is false as they are the element that is missing in the given array. 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 find the missing elementsvoid printMissingElements(int arr[], int N){ // Initialize an array with zero // of size equals to the maximum // element in the array int b[arr[N - 1] + 1] = { 0 }; // Make b[i]=1 if i is present // in the array for (int i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for (int i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { cout << i << " "; } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = sizeof(arr) / sizeof(int); // Function Call printMissingElements(arr, N); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to find the missing elementsstatic void printMissingElements(int arr[], int N){ // Initialize an array with zero // of size equals to the maximum // element in the array int[] b = new int[arr[N - 1] + 1]; // Make b[i]=1 if i is present // in the array for(int i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for(int i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { System.out.print(i + " "); } }} // Driver Codepublic static void main (String[] args){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = arr.length; // Function call printMissingElements(arr, N);}} // This code is contributed by offbeat # Python3 program to implement# the above approach # Function to find the missing elementsdef printMissingElements(arr, N): # Initialize an array with zero # of size equals to the maximum # element in the array b = [0] * (arr[N - 1] + 1) # Make b[i]=1 if i is present # in the array for i in range(N): # If the element is present # make b[arr[i]]=1 b[arr[i]] = 1 # Print the indices where b[i]=0 for i in range(arr[0], arr[N - 1] + 1): if(b[i] == 0): print(i, end = " ") # Driver Code # Given array arr[]arr = [ 6, 7, 10, 11, 13 ] N = len(arr) # Function callprintMissingElements(arr, N) # This code is contributed by Shivam Singh // C# program for// the above approachusing System;class GFG{ // Function to find the missing elementsstatic void printMissingElements(int []arr, int N){ // Initialize an array with zero // of size equals to the maximum // element in the array int[] b = new int[arr[N - 1] + 1]; // Make b[i]=1 if i is present // in the array for(int i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for(int i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { Console.Write(i + " "); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {6, 7, 10, 11, 13}; int N = arr.Length; // Function call printMissingElements(arr, N);}} // This code is contributed by Princi Singh <script> // JavaScript program for the above approach // Function to find the missing elementsfunction printMissingElements(arr, N){ // Initialize an array with zero // of size equals to the maximum // element in the array let b = new Uint8Array(arr[N - 1] + 1); // Make b[i]=1 if i is present // in the array for (let i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for (let i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { document.write( i + " "); } }} // Driver Code // Given array arr[] let arr = [ 6, 7, 10, 11, 13 ]; let N = arr.length; // Function Call printMissingElements(arr, N); //This code is contributed by Mayank Tyagi</script> 8 9 12 Time Complexity: O(M), where M is the maximum element of the array. Auxiliary Space: O(M) Most Efficient And Simple Approach: In below approach simple we create a variable (cnt) this variable keeps the track of element present in array 1. We need to traverse the arr[0] to arr[N] to find missing number between it. 2. In for loop if arr[cnt] match to current element then we do not print that element and skip that element because it is present in array once we found element then we increment the cnt++ for pointing next element in array 3. In else part we just print the element which does not match or present in array C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the missing elementsvoid printMissingElements(int arr[], int N){ int cnt = 0; for (int i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number cout << i << " "; } }}// Driver Codeint main(){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call printMissingElements(arr, N); return 0;}//This code is contributed by Kuldeep Kushwaha //Java program for the above approachimport java.io.*;class GFG { // Function to find the missing elements public static void printMissingElements(int arr[], int N) { int cnt = 0; for (int i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number System.out.print(i + " "); } } } // Driver Code public static void main (String[] args) { // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = arr.length; // Function Call printMissingElements(arr, N); }} // This code is contributed by Shubham Singh # Python program for the above approach # Function to find the missing elementsdef printMissingElements(arr, N): cnt = 0 for i in range(arr[0], arr[N - 1]+1): # Check if number is equal to the first element in # given array if array element match skip it increment for next element if (arr[cnt] == i): # Increment the count to check next element cnt += 1 else: # Print missing number print(i , end = " ") # Driver Code# Given array arr[]arr = [ 6, 7, 10, 11, 13 ]N = len(arr) # Function CallprintMissingElements(arr, N) # This code is contributed by Shubham Singh //C# program for the above approachusing System;using System.Linq; public class GFG{ // Function to find the missing elements public static void printMissingElements(int[] arr, int N) { int cnt = 0; for (int i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number Console.Write(i + " "); } } } // Driver Code static public void Main () { // Given array arr[] int[] arr = { 6, 7, 10, 11, 13 }; int N = arr.Length; // Function Call printMissingElements(arr, N); }} // This code is contributed by Shubham Singh <script>// Javascript program for the above approach // Function to find the missing elementsfunction printMissingElements(arr, N){ var cnt = 0; for (var i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number document.write(i + " "); } }} // Driver Code // Given array arr[]var arr = [ 6, 7, 10, 11, 13 ];var N = arr.length; // Function CallprintMissingElements(arr, N); // This code is contributed by Shubham Singh</script> 8 9 12 Time Complexity: O(N), where N is the maximum element of the array. Auxiliary Space: O(1) Because of this method the overflow of hash or extra space will be saved. SHIVAMSINGH67 offbeat divyeshrabadiya07 princi singh chinmoy1997pal mayanktyagi1709 kushwahakuldeep321 SHUBHAMSINGH10 frequency-counting HashTable Arrays Greedy Hash Mathematical Arrays Hash Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26067, "s": 26039, "text": "\n08 Feb, 2022" }, { "code": null, "e": 26211, "s": 26067, "text": "Given a sorted array arr[] of N integers, The task is to find the multiple missing elements in the array between the ranges [arr[0], arr[N-1]]." }, { "code": null, "e": 26221, "s": 26211, "text": "Examples:" }, { "code": null, "e": 26534, "s": 26221, "text": "Input: arr[] = {6, 7, 10, 11, 13}Output: 8 9 12 Explanation: The elements of the array are present in the range of the maximum and minimum array element [6, 13]. Therefore, the total values will be {6, 7, 8, 9, 10, 11, 12, 13}. The elements from the above range which are missing from the array are {8, 9, 12}. " }, { "code": null, "e": 26573, "s": 26534, "text": "Input: arr[] = {1, 2, 4, 6}Output: 3 5" }, { "code": null, "e": 26775, "s": 26573, "text": "Naive Approach: The naive idea is to iterate over the difference between the consecutive pair of elements and the print all the numbers in this range if the difference is non-zero. Below are the steps:" }, { "code": null, "e": 27289, "s": 26775, "text": "Initialize the variable diff which is equal to arr[0] – 0.Now traverse the array and see if the difference between arr[i] – i and diff is zero or not.If the difference is not equal to zero in the above steps, then the missing element is found.To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff.Now increment the diff as the difference is increased now.Repeat from step 2 until all the missing numbers are not found." }, { "code": null, "e": 27348, "s": 27289, "text": "Initialize the variable diff which is equal to arr[0] – 0." }, { "code": null, "e": 27441, "s": 27348, "text": "Now traverse the array and see if the difference between arr[i] – i and diff is zero or not." }, { "code": null, "e": 27535, "s": 27441, "text": "If the difference is not equal to zero in the above steps, then the missing element is found." }, { "code": null, "e": 27685, "s": 27535, "text": "To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff." }, { "code": null, "e": 27744, "s": 27685, "text": "Now increment the diff as the difference is increased now." }, { "code": null, "e": 27808, "s": 27744, "text": "Repeat from step 2 until all the missing numbers are not found." }, { "code": null, "e": 27859, "s": 27808, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27863, "s": 27859, "text": "C++" }, { "code": null, "e": 27868, "s": 27863, "text": "Java" }, { "code": null, "e": 27876, "s": 27868, "text": "Python3" }, { "code": null, "e": 27879, "s": 27876, "text": "C#" }, { "code": null, "e": 27890, "s": 27879, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the missing elementsvoid printMissingElements(int arr[], int N){ // Initialize diff int diff = arr[0] - 0; for (int i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { cout << i + diff << \" \"; diff++; } } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = sizeof(arr) / sizeof(int); // Function Call printMissingElements(arr, N); return 0;}", "e": 28634, "s": 27890, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the missing elementsstatic void printMissingElements(int arr[], int N){ // Initialize diff int diff = arr[0] - 0; for(int i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { System.out.print((i + diff) + \" \"); diff++; } } }} // Driver Codepublic static void main (String[] args){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = arr.length; // Function call printMissingElements(arr, N);}} // This code is contributed by offbeat", "e": 29493, "s": 28634, "text": null }, { "code": "# Python3 program for the above approach # Function to find the missing elementsdef printMissingElements(arr, N): # Initialize diff diff = arr[0] for i in range(N): # Check if diff and arr[i]-i # both are equal or not if(arr[i] - i != diff): # Loop for consecutive # missing elements while(diff < arr[i] - i): print(i + diff, end = \" \") diff += 1 # Driver Code # Given array arr[]arr = [ 6, 7, 10, 11, 13 ] N = len(arr) # Function callprintMissingElements(arr, N) # This code is contributed by Shivam Singh", "e": 30097, "s": 29493, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the missing elementsstatic void printMissingElements(int[] arr, int N){ // Initialize diff int diff = arr[0] - 0; for(int i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { Console.Write(i + diff + \" \"); diff++; } } }} // Driver codestatic void Main(){ // Given array arr[] int[] arr = { 6, 7, 10, 11, 13 }; int N = arr.Length; // Function call printMissingElements(arr, N);}} // This code is contributed by divyeshrabadiya07", "e": 30956, "s": 30097, "text": null }, { "code": "<script> // Javascript program to gather characters// of a string in minimum cost // Function to find the missing elementsfunction prletMissingElements(arr, N){ // Initialize diff let diff = arr[0] - 0; for(let i = 0; i < N; i++) { // Check if diff and arr[i]-i // both are equal or not if (arr[i] - i != diff) { // Loop for consecutive // missing elements while (diff < arr[i] - i) { document.write((i + diff) + \" \"); diff++; } } }} // Driver Code // Given array arr[] let arr = [ 6, 7, 10, 11, 13 ]; let N = arr.length; // Function call prletMissingElements(arr, N); </script>", "e": 31713, "s": 30956, "text": null }, { "code": null, "e": 31721, "s": 31713, "text": "8 9 12 " }, { "code": null, "e": 31765, "s": 31721, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 32092, "s": 31765, "text": "Efficient Approach: The idea is to use Hashing to optimize the above approach. Create a boolean array(say b[]) of size equal to the maximum element in the array and mark only those positions in the array b[] which are present in the given array. Print all the index in the array b[] that are not marked. Below are the steps: " }, { "code": null, "e": 32453, "s": 32092, "text": "Initialize a boolean array b[] with zero of size equals to the maximum element of the array.Iterate over the given array and mark for each element in the given array mark that index as true in the array b[].Now traverse the given array b[] from index arr[0] and print those index whose value is false as they are the element that is missing in the given array." }, { "code": null, "e": 32546, "s": 32453, "text": "Initialize a boolean array b[] with zero of size equals to the maximum element of the array." }, { "code": null, "e": 32662, "s": 32546, "text": "Iterate over the given array and mark for each element in the given array mark that index as true in the array b[]." }, { "code": null, "e": 32816, "s": 32662, "text": "Now traverse the given array b[] from index arr[0] and print those index whose value is false as they are the element that is missing in the given array." }, { "code": null, "e": 32868, "s": 32816, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 32872, "s": 32868, "text": "C++" }, { "code": null, "e": 32877, "s": 32872, "text": "Java" }, { "code": null, "e": 32885, "s": 32877, "text": "Python3" }, { "code": null, "e": 32888, "s": 32885, "text": "C#" }, { "code": null, "e": 32899, "s": 32888, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the missing elementsvoid printMissingElements(int arr[], int N){ // Initialize an array with zero // of size equals to the maximum // element in the array int b[arr[N - 1] + 1] = { 0 }; // Make b[i]=1 if i is present // in the array for (int i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for (int i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { cout << i << \" \"; } }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = sizeof(arr) / sizeof(int); // Function Call printMissingElements(arr, N); return 0;}", "e": 33728, "s": 32899, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the missing elementsstatic void printMissingElements(int arr[], int N){ // Initialize an array with zero // of size equals to the maximum // element in the array int[] b = new int[arr[N - 1] + 1]; // Make b[i]=1 if i is present // in the array for(int i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for(int i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { System.out.print(i + \" \"); } }} // Driver Codepublic static void main (String[] args){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = arr.length; // Function call printMissingElements(arr, N);}} // This code is contributed by offbeat", "e": 34674, "s": 33728, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find the missing elementsdef printMissingElements(arr, N): # Initialize an array with zero # of size equals to the maximum # element in the array b = [0] * (arr[N - 1] + 1) # Make b[i]=1 if i is present # in the array for i in range(N): # If the element is present # make b[arr[i]]=1 b[arr[i]] = 1 # Print the indices where b[i]=0 for i in range(arr[0], arr[N - 1] + 1): if(b[i] == 0): print(i, end = \" \") # Driver Code # Given array arr[]arr = [ 6, 7, 10, 11, 13 ] N = len(arr) # Function callprintMissingElements(arr, N) # This code is contributed by Shivam Singh", "e": 35375, "s": 34674, "text": null }, { "code": "// C# program for// the above approachusing System;class GFG{ // Function to find the missing elementsstatic void printMissingElements(int []arr, int N){ // Initialize an array with zero // of size equals to the maximum // element in the array int[] b = new int[arr[N - 1] + 1]; // Make b[i]=1 if i is present // in the array for(int i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for(int i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { Console.Write(i + \" \"); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {6, 7, 10, 11, 13}; int N = arr.Length; // Function call printMissingElements(arr, N);}} // This code is contributed by Princi Singh", "e": 36234, "s": 35375, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the missing elementsfunction printMissingElements(arr, N){ // Initialize an array with zero // of size equals to the maximum // element in the array let b = new Uint8Array(arr[N - 1] + 1); // Make b[i]=1 if i is present // in the array for (let i = 0; i < N; i++) { // If the element is present // make b[arr[i]]=1 b[arr[i]] = 1; } // Print the indices where b[i]=0 for (let i = arr[0]; i <= arr[N - 1]; i++) { if (b[i] == 0) { document.write( i + \" \"); } }} // Driver Code // Given array arr[] let arr = [ 6, 7, 10, 11, 13 ]; let N = arr.length; // Function Call printMissingElements(arr, N); //This code is contributed by Mayank Tyagi</script>", "e": 37061, "s": 36234, "text": null }, { "code": null, "e": 37069, "s": 37061, "text": "8 9 12 " }, { "code": null, "e": 37159, "s": 37069, "text": "Time Complexity: O(M), where M is the maximum element of the array. Auxiliary Space: O(M)" }, { "code": null, "e": 37197, "s": 37159, "text": "Most Efficient And Simple Approach: " }, { "code": null, "e": 37307, "s": 37197, "text": "In below approach simple we create a variable (cnt) this variable keeps the track of element present in array" }, { "code": null, "e": 37386, "s": 37307, "text": "1. We need to traverse the arr[0] to arr[N] to find missing number between it." }, { "code": null, "e": 37526, "s": 37386, "text": "2. In for loop if arr[cnt] match to current element then we do not print that element and skip that element because it is present in array " }, { "code": null, "e": 37612, "s": 37526, "text": "once we found element then we increment the cnt++ for pointing next element in array " }, { "code": null, "e": 37695, "s": 37612, "text": "3. In else part we just print the element which does not match or present in array" }, { "code": null, "e": 37699, "s": 37695, "text": "C++" }, { "code": null, "e": 37704, "s": 37699, "text": "Java" }, { "code": null, "e": 37712, "s": 37704, "text": "Python3" }, { "code": null, "e": 37715, "s": 37712, "text": "C#" }, { "code": null, "e": 37726, "s": 37715, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the missing elementsvoid printMissingElements(int arr[], int N){ int cnt = 0; for (int i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number cout << i << \" \"; } }}// Driver Codeint main(){ // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call printMissingElements(arr, N); return 0;}//This code is contributed by Kuldeep Kushwaha", "e": 38541, "s": 37726, "text": null }, { "code": "//Java program for the above approachimport java.io.*;class GFG { // Function to find the missing elements public static void printMissingElements(int arr[], int N) { int cnt = 0; for (int i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number System.out.print(i + \" \"); } } } // Driver Code public static void main (String[] args) { // Given array arr[] int arr[] = { 6, 7, 10, 11, 13 }; int N = arr.length; // Function Call printMissingElements(arr, N); }} // This code is contributed by Shubham Singh", "e": 39367, "s": 38541, "text": null }, { "code": "# Python program for the above approach # Function to find the missing elementsdef printMissingElements(arr, N): cnt = 0 for i in range(arr[0], arr[N - 1]+1): # Check if number is equal to the first element in # given array if array element match skip it increment for next element if (arr[cnt] == i): # Increment the count to check next element cnt += 1 else: # Print missing number print(i , end = \" \") # Driver Code# Given array arr[]arr = [ 6, 7, 10, 11, 13 ]N = len(arr) # Function CallprintMissingElements(arr, N) # This code is contributed by Shubham Singh", "e": 40069, "s": 39367, "text": null }, { "code": "//C# program for the above approachusing System;using System.Linq; public class GFG{ // Function to find the missing elements public static void printMissingElements(int[] arr, int N) { int cnt = 0; for (int i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number Console.Write(i + \" \"); } } } // Driver Code static public void Main () { // Given array arr[] int[] arr = { 6, 7, 10, 11, 13 }; int N = arr.Length; // Function Call printMissingElements(arr, N); }} // This code is contributed by Shubham Singh", "e": 40898, "s": 40069, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the missing elementsfunction printMissingElements(arr, N){ var cnt = 0; for (var i = arr[0]; i <= arr[N - 1]; i++) { // Check if number is equal to the first element in // given array if array element match skip it increment for next element if (arr[cnt] == i) { // Increment the count to check next element cnt++; } else { // Print missing number document.write(i + \" \"); } }} // Driver Code // Given array arr[]var arr = [ 6, 7, 10, 11, 13 ];var N = arr.length; // Function CallprintMissingElements(arr, N); // This code is contributed by Shubham Singh</script>", "e": 41671, "s": 40898, "text": null }, { "code": null, "e": 41679, "s": 41671, "text": "8 9 12 " }, { "code": null, "e": 41748, "s": 41679, "text": "Time Complexity: O(N), where N is the maximum element of the array. " }, { "code": null, "e": 41844, "s": 41748, "text": "Auxiliary Space: O(1) Because of this method the overflow of hash or extra space will be saved." }, { "code": null, "e": 41858, "s": 41844, "text": "SHIVAMSINGH67" }, { "code": null, "e": 41866, "s": 41858, "text": "offbeat" }, { "code": null, "e": 41884, "s": 41866, "text": "divyeshrabadiya07" }, { "code": null, "e": 41897, "s": 41884, "text": "princi singh" }, { "code": null, "e": 41912, "s": 41897, "text": "chinmoy1997pal" }, { "code": null, "e": 41928, "s": 41912, "text": "mayanktyagi1709" }, { "code": null, "e": 41947, "s": 41928, "text": "kushwahakuldeep321" }, { "code": null, "e": 41962, "s": 41947, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 41981, "s": 41962, "text": "frequency-counting" }, { "code": null, "e": 41991, "s": 41981, "text": "HashTable" }, { "code": null, "e": 41998, "s": 41991, "text": "Arrays" }, { "code": null, "e": 42005, "s": 41998, "text": "Greedy" }, { "code": null, "e": 42010, "s": 42005, "text": "Hash" }, { "code": null, "e": 42023, "s": 42010, "text": "Mathematical" }, { "code": null, "e": 42030, "s": 42023, "text": "Arrays" }, { "code": null, "e": 42035, "s": 42030, "text": "Hash" }, { "code": null, "e": 42042, "s": 42035, "text": "Greedy" }, { "code": null, "e": 42055, "s": 42042, "text": "Mathematical" }, { "code": null, "e": 42153, "s": 42055, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42184, "s": 42153, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 42211, "s": 42184, "text": "Count pairs with given sum" }, { "code": null, "e": 42236, "s": 42211, "text": "Window Sliding Technique" }, { "code": null, "e": 42274, "s": 42236, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 42295, "s": 42274, "text": "Next Greater Element" }, { "code": null, "e": 42346, "s": 42295, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 42397, "s": 42346, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 42455, "s": 42397, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 42515, "s": 42455, "text": "Write a program to print all permutations of a given string" } ]
Adding Text to Plots in R programming - text() and mtext () Function - GeeksforGeeks
07 Dec, 2021 Text is defined as a way to describe data related to graphical representation. They work as labels to any pictorial or graphical representation. In this article, we will learn to add a text to a plot in R Programming Language by using the text() and mtext() functions. text () Function in R Programming Language is used to draw text elements to plots in Base R. Syntax: text(x, y, labels) Parameters: x and y: numeric values specifying the coordinates of the text to plot labels: the text to be written Returns: Added text to plot Example 1: R # R program to add text to plot # Calling data setd<-head(mtcars) # Plotting the graphplot(d[, 'wt'], d[, 'mpg'], main = " Car Weight vs. Milage ", xlab = "Miles", ylab = " Weight", pch = 19, col = "darkgreen") # Calling text() functiontext(d[, 'wt'], d[, 'mpg'], row.names(d), cex = 0.88, pos = 2, col = "darkgreen") Output: In the above example, the text is added to the plot of ‘mtcar’ dataset. Example 2: Implementation of text() to add a mathematical annotation to a plot R # R program to add text to plot # Plotting the graphplot(1:5, 1:5, main = "text() Function examples") # Calling text() functiontext(2, 3, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))text(3, 4, expression(bar(x) == sum(frac(x[i], n), i==1, n))) Output: In the above example, the text() function is used to add a mathematical annotation to a plot mtext() function in R Programming Language is used to add text to the margins of the plot. Syntax: mtext(text, side) Parameters: text: text to be written side: An integer specifying the side of the plot, such as: bottom, left, top, and right. Returns: Added text in the margins of the graph Example: R # R program to add text to a plot # Creating a plotplot(1:5, 1:5, main = "mtext examples") # Calling mtext() functionmtext("mtext() function", side = 3) Output: Here, in the above example, the side specifies the side of the plot such as the bottom, left, top, right. And in the given the side=3 i.e the top part of the plot. kumar_satyam R Plot-Function 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n07 Dec, 2021" }, { "code": null, "e": 26756, "s": 26487, "text": "Text is defined as a way to describe data related to graphical representation. They work as labels to any pictorial or graphical representation. In this article, we will learn to add a text to a plot in R Programming Language by using the text() and mtext() functions." }, { "code": null, "e": 26849, "s": 26756, "text": "text () Function in R Programming Language is used to draw text elements to plots in Base R." }, { "code": null, "e": 26876, "s": 26849, "text": "Syntax: text(x, y, labels)" }, { "code": null, "e": 26889, "s": 26876, "text": "Parameters: " }, { "code": null, "e": 26960, "s": 26889, "text": "x and y: numeric values specifying the coordinates of the text to plot" }, { "code": null, "e": 26991, "s": 26960, "text": "labels: the text to be written" }, { "code": null, "e": 27020, "s": 26991, "text": "Returns: Added text to plot " }, { "code": null, "e": 27032, "s": 27020, "text": "Example 1: " }, { "code": null, "e": 27034, "s": 27032, "text": "R" }, { "code": "# R program to add text to plot # Calling data setd<-head(mtcars) # Plotting the graphplot(d[, 'wt'], d[, 'mpg'], main = \" Car Weight vs. Milage \", xlab = \"Miles\", ylab = \" Weight\", pch = 19, col = \"darkgreen\") # Calling text() functiontext(d[, 'wt'], d[, 'mpg'], row.names(d), cex = 0.88, pos = 2, col = \"darkgreen\")", "e": 27369, "s": 27034, "text": null }, { "code": null, "e": 27378, "s": 27369, "text": "Output: " }, { "code": null, "e": 27450, "s": 27378, "text": "In the above example, the text is added to the plot of ‘mtcar’ dataset." }, { "code": null, "e": 27530, "s": 27450, "text": "Example 2: Implementation of text() to add a mathematical annotation to a plot " }, { "code": null, "e": 27532, "s": 27530, "text": "R" }, { "code": "# R program to add text to plot # Plotting the graphplot(1:5, 1:5, main = \"text() Function examples\") # Calling text() functiontext(2, 3, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))text(3, 4, expression(bar(x) == sum(frac(x[i], n), i==1, n)))", "e": 27787, "s": 27532, "text": null }, { "code": null, "e": 27795, "s": 27787, "text": "Output:" }, { "code": null, "e": 27888, "s": 27795, "text": "In the above example, the text() function is used to add a mathematical annotation to a plot" }, { "code": null, "e": 27980, "s": 27888, "text": "mtext() function in R Programming Language is used to add text to the margins of the plot. " }, { "code": null, "e": 28006, "s": 27980, "text": "Syntax: mtext(text, side)" }, { "code": null, "e": 28019, "s": 28006, "text": "Parameters: " }, { "code": null, "e": 28044, "s": 28019, "text": "text: text to be written" }, { "code": null, "e": 28133, "s": 28044, "text": "side: An integer specifying the side of the plot, such as: bottom, left, top, and right." }, { "code": null, "e": 28182, "s": 28133, "text": "Returns: Added text in the margins of the graph " }, { "code": null, "e": 28192, "s": 28182, "text": "Example: " }, { "code": null, "e": 28194, "s": 28192, "text": "R" }, { "code": "# R program to add text to a plot # Creating a plotplot(1:5, 1:5, main = \"mtext examples\") # Calling mtext() functionmtext(\"mtext() function\", side = 3)", "e": 28351, "s": 28194, "text": null }, { "code": null, "e": 28359, "s": 28351, "text": "Output:" }, { "code": null, "e": 28523, "s": 28359, "text": "Here, in the above example, the side specifies the side of the plot such as the bottom, left, top, right. And in the given the side=3 i.e the top part of the plot." }, { "code": null, "e": 28536, "s": 28523, "text": "kumar_satyam" }, { "code": null, "e": 28552, "s": 28536, "text": "R Plot-Function" }, { "code": null, "e": 28563, "s": 28552, "text": "R Language" }, { "code": null, "e": 28661, "s": 28563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28713, "s": 28661, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28748, "s": 28713, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28786, "s": 28748, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28844, "s": 28786, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28887, "s": 28844, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28936, "s": 28887, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28973, "s": 28936, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28999, "s": 28973, "text": "Time Series Analysis in R" }, { "code": null, "e": 29016, "s": 28999, "text": "R - if statement" } ]
Find unique elements in linked list - GeeksforGeeks
25 Jun, 2021 Given a linked list. We need to find unique elements in the linked list i.e, those elements which are not repeated in the linked list or those elements whose frequency is 1. If No such elements are present in list so Print ” No Unique Elements”.Examples: Input : 1 -> 4 -> 4 -> 2 -> 3 -> 5 -> 3 -> 4 -> 5 Output :1 2 Input :4 -> 5 -> 2 -> 5 -> 1 -> 4 -> 1 -> 2 Output :No Unique Elements Method 1 (Using Two Loops) This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and inner loop compares the picked element with rest of the elements. If Element is not equal to other elements than Print that Element. Time Complexity : O(N * n)Method 2 (Sorting) : Sort the elements using Merge Sort. O(n Log n). Now Traverse List in linear time and check if current element is not equal to previous element then Print O(N) Please note that this method doesn’t preserve the original order of elements.Time Complexity: O(NLogN) Method 3 (Hashing) We use the concept of Hash table Here, We traverse the link list from head to end. For every newly encountered element, we put it in the hash table after that we again traverse list and Print those elements whose frequency is 1.Time Complexity : O(N) Below is the Implementation of this C++ Java Python3 C# Javascript // C++ Program to Find the Unique elements in// linked lists#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node { int data; struct Node* next;}; /* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} // function to Find the unique elements in linked listsvoid uniqueElements(struct Node* head){ // Initialize hash array that store the // frequency of each element of list unordered_map<int, int> hash; for (Node *temp=head; temp!=NULL; temp=temp->next) hash[temp->data]++; int count = 0; for (Node *temp=head; temp!=NULL; temp=temp->next) { // Check whether the frequency of current // element is 1 or not if (hash[temp->data] == 1) { cout << temp->data << " "; count++; } } // If No unique element in list if (count == 0) cout << " No Unique Elements ";} // Driver program to test aboveint main(){ struct Node* head = NULL; // creating linked list push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 5); push(&head, 3); push(&head, 2); push(&head, 4); push(&head, 4); push(&head, 1); uniqueElements(head); return 0;} // Java Program to Find the Unique elements// in linked listsimport java.util.*;class GFG{ /* Linked list node */static class Node{ int data; Node next;};static Node head; /* Function to insert a node at thebeginning of the linked list */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} // function to Find the unique elements// in linked listsstatic void uniqueElements(Node head){ // Initialize hash array that store the // frequency of each element of list HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(); for (Node temp = head; temp != null; temp = temp.next) { if(hash.containsKey(temp.data)) { hash.put(temp.data, hash.get(temp.data) + 1); } else { hash.put(temp.data, 1); } } int count = 0; for (Node temp = head; temp != null; temp = temp.next) { // Check whether the frequency of current // element is 1 or not if (hash.get(temp.data) == 1) { System.out.print(temp.data + " "); count++; } } // If No unique element in list if (count == 0) System.out.print(" No Unique Elements ");} // Driver Codepublic static void main(String[] args){ head = null; // creating linked list push(head, 5); push(head, 4); push(head, 3); push(head, 5); push(head, 3); push(head, 2); push(head, 4); push(head, 4); push(head, 1); uniqueElements(head);}} // This code is contributed by Rajput-Ji # Python3 Program to Find the Unique elements in# linked listsimport sysimport math # Linked list nodeclass Node: def __init__(self,data): self.data = data self.next = None # Function to insert a node at the beginning of# the linked listdef push(head,data): if not head: return Node(data) temp = Node(data) temp.next = head head = temp return head # function to Find the unique elements in linked listsdef uniqueElements(head): # Initialize hash array that store the # frequency of each element of list _map = {} temp = head while(temp): d = temp.data if d in _map: _map[d]=_map.get(d)+1 else: _map[d] = 1 temp = temp.next count = 0 for i in _map: # Check whether the frequency of current # element is 1 or not if _map.get(i) == 1: count += 1 print("{} ".format(i),end="") # If No unique element in list if count == 0: print("No Unique Elements") # Driver program to test aboveif __name__=='__main__': # creating linked list head = None head = push(head,5) head = push(head,4) head = push(head,3) head = push(head,5) head = push(head,3) head = push(head,2) head = push(head,4) head = push(head,4) head = push(head,1) uniqueElements(head) # This code is Contributed by Vikash Kumar 37 // C# Program to Find the Unique elements// in linked listsusing System;using System.Collections.Generic; class GFG{ /* Linked list node */public class Node{ public int data; public Node next;};static Node head; /* Function to insert a node at thebeginning of the linked list */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} // function to Find the unique elements// in linked listsstatic void uniqueElements(Node head){ // Initialize hash array that store the // frequency of each element of list Dictionary<int, int> hash = new Dictionary<int, int>(); for (Node temp = head; temp != null; temp = temp.next) { if(hash.ContainsKey(temp.data)) { hash[temp.data] = hash[temp.data] + 1; } else { hash.Add(temp.data, 1); } } int count = 0; for (Node temp = head; temp != null; temp = temp.next) { // Check whether the frequency of // current element is 1 or not if (hash[temp.data] == 1) { Console.Write(temp.data + " "); count++; } } // If No unique element in list if (count == 0) Console.Write(" No Unique Elements ");} // Driver Codepublic static void Main(String[] args){ head = null; // creating linked list push(head, 5); push(head, 4); push(head, 3); push(head, 5); push(head, 3); push(head, 2); push(head, 4); push(head, 4); push(head, 1); uniqueElements(head);}} // This code is contributed by 29AjayKumar <script> // JavaScript Program to Find the Unique elements // in linked lists /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Function to insert a node at thebeginning of the linked list */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref; } // function to Find the unique elements // in linked lists function uniqueElements(head) { // Initialize hash array that store the // frequency of each element of list var hash = {}; for (var temp = head; temp != null; temp = temp.next) { if (hash.hasOwnProperty(temp.data)) { hash[temp.data] = hash[temp.data] + 1; } else { hash[temp.data] = 1; } } var count = 0; for (var temp = head; temp != null; temp = temp.next) { // Check whether the frequency of // current element is 1 or not if (hash[temp.data] == 1) { document.write(temp.data + " "); count++; } } // If No unique element in list if (count == 0) document.write(" No Unique Elements "); } // Driver Code head = null; // creating linked list push(head, 5); push(head, 4); push(head, 3); push(head, 5); push(head, 3); push(head, 2); push(head, 4); push(head, 4); push(head, 1); uniqueElements(head); // This code is contributed by rdtank. </script> 1 2 Time Complexity : O(N) Auxiliary Space : O(N) Vikash Kumar 37 Rajput-Ji 29AjayKumar rdtank cpp-unordered_map Hash Linked List Technical Scripter Linked List Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hashing | Set 2 (Separate Chaining) Sort string of characters Counting frequencies of array elements Most frequent element in an array Sorting a Map by value in C++ STL Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) LinkedList in Java
[ { "code": null, "e": 26441, "s": 26413, "text": "\n25 Jun, 2021" }, { "code": null, "e": 26698, "s": 26441, "text": "Given a linked list. We need to find unique elements in the linked list i.e, those elements which are not repeated in the linked list or those elements whose frequency is 1. If No such elements are present in list so Print ” No Unique Elements”.Examples: " }, { "code": null, "e": 26833, "s": 26698, "text": "Input : 1 -> 4 -> 4 -> 2 -> 3 -> 5 -> 3 -> 4 -> 5\nOutput :1 2 \n\nInput :4 -> 5 -> 2 -> 5 -> 1 -> 4 -> 1 -> 2\nOutput :No Unique Elements" }, { "code": null, "e": 27715, "s": 26835, "text": "Method 1 (Using Two Loops) This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and inner loop compares the picked element with rest of the elements. If Element is not equal to other elements than Print that Element. Time Complexity : O(N * n)Method 2 (Sorting) : Sort the elements using Merge Sort. O(n Log n). Now Traverse List in linear time and check if current element is not equal to previous element then Print O(N) Please note that this method doesn’t preserve the original order of elements.Time Complexity: O(NLogN) Method 3 (Hashing) We use the concept of Hash table Here, We traverse the link list from head to end. For every newly encountered element, we put it in the hash table after that we again traverse list and Print those elements whose frequency is 1.Time Complexity : O(N) Below is the Implementation of this " }, { "code": null, "e": 27719, "s": 27715, "text": "C++" }, { "code": null, "e": 27724, "s": 27719, "text": "Java" }, { "code": null, "e": 27732, "s": 27724, "text": "Python3" }, { "code": null, "e": 27735, "s": 27732, "text": "C#" }, { "code": null, "e": 27746, "s": 27735, "text": "Javascript" }, { "code": "// C++ Program to Find the Unique elements in// linked lists#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node { int data; struct Node* next;}; /* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node;} // function to Find the unique elements in linked listsvoid uniqueElements(struct Node* head){ // Initialize hash array that store the // frequency of each element of list unordered_map<int, int> hash; for (Node *temp=head; temp!=NULL; temp=temp->next) hash[temp->data]++; int count = 0; for (Node *temp=head; temp!=NULL; temp=temp->next) { // Check whether the frequency of current // element is 1 or not if (hash[temp->data] == 1) { cout << temp->data << \" \"; count++; } } // If No unique element in list if (count == 0) cout << \" No Unique Elements \";} // Driver program to test aboveint main(){ struct Node* head = NULL; // creating linked list push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 5); push(&head, 3); push(&head, 2); push(&head, 4); push(&head, 4); push(&head, 1); uniqueElements(head); return 0;}", "e": 29127, "s": 27746, "text": null }, { "code": "// Java Program to Find the Unique elements// in linked listsimport java.util.*;class GFG{ /* Linked list node */static class Node{ int data; Node next;};static Node head; /* Function to insert a node at thebeginning of the linked list */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} // function to Find the unique elements// in linked listsstatic void uniqueElements(Node head){ // Initialize hash array that store the // frequency of each element of list HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(); for (Node temp = head; temp != null; temp = temp.next) { if(hash.containsKey(temp.data)) { hash.put(temp.data, hash.get(temp.data) + 1); } else { hash.put(temp.data, 1); } } int count = 0; for (Node temp = head; temp != null; temp = temp.next) { // Check whether the frequency of current // element is 1 or not if (hash.get(temp.data) == 1) { System.out.print(temp.data + \" \"); count++; } } // If No unique element in list if (count == 0) System.out.print(\" No Unique Elements \");} // Driver Codepublic static void main(String[] args){ head = null; // creating linked list push(head, 5); push(head, 4); push(head, 3); push(head, 5); push(head, 3); push(head, 2); push(head, 4); push(head, 4); push(head, 1); uniqueElements(head);}} // This code is contributed by Rajput-Ji", "e": 30856, "s": 29127, "text": null }, { "code": "# Python3 Program to Find the Unique elements in# linked listsimport sysimport math # Linked list nodeclass Node: def __init__(self,data): self.data = data self.next = None # Function to insert a node at the beginning of# the linked listdef push(head,data): if not head: return Node(data) temp = Node(data) temp.next = head head = temp return head # function to Find the unique elements in linked listsdef uniqueElements(head): # Initialize hash array that store the # frequency of each element of list _map = {} temp = head while(temp): d = temp.data if d in _map: _map[d]=_map.get(d)+1 else: _map[d] = 1 temp = temp.next count = 0 for i in _map: # Check whether the frequency of current # element is 1 or not if _map.get(i) == 1: count += 1 print(\"{} \".format(i),end=\"\") # If No unique element in list if count == 0: print(\"No Unique Elements\") # Driver program to test aboveif __name__=='__main__': # creating linked list head = None head = push(head,5) head = push(head,4) head = push(head,3) head = push(head,5) head = push(head,3) head = push(head,2) head = push(head,4) head = push(head,4) head = push(head,1) uniqueElements(head) # This code is Contributed by Vikash Kumar 37", "e": 32250, "s": 30856, "text": null }, { "code": "// C# Program to Find the Unique elements// in linked listsusing System;using System.Collections.Generic; class GFG{ /* Linked list node */public class Node{ public int data; public Node next;};static Node head; /* Function to insert a node at thebeginning of the linked list */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} // function to Find the unique elements// in linked listsstatic void uniqueElements(Node head){ // Initialize hash array that store the // frequency of each element of list Dictionary<int, int> hash = new Dictionary<int, int>(); for (Node temp = head; temp != null; temp = temp.next) { if(hash.ContainsKey(temp.data)) { hash[temp.data] = hash[temp.data] + 1; } else { hash.Add(temp.data, 1); } } int count = 0; for (Node temp = head; temp != null; temp = temp.next) { // Check whether the frequency of // current element is 1 or not if (hash[temp.data] == 1) { Console.Write(temp.data + \" \"); count++; } } // If No unique element in list if (count == 0) Console.Write(\" No Unique Elements \");} // Driver Codepublic static void Main(String[] args){ head = null; // creating linked list push(head, 5); push(head, 4); push(head, 3); push(head, 5); push(head, 3); push(head, 2); push(head, 4); push(head, 4); push(head, 1); uniqueElements(head);}} // This code is contributed by 29AjayKumar", "e": 34009, "s": 32250, "text": null }, { "code": "<script> // JavaScript Program to Find the Unique elements // in linked lists /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Function to insert a node at thebeginning of the linked list */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref; } // function to Find the unique elements // in linked lists function uniqueElements(head) { // Initialize hash array that store the // frequency of each element of list var hash = {}; for (var temp = head; temp != null; temp = temp.next) { if (hash.hasOwnProperty(temp.data)) { hash[temp.data] = hash[temp.data] + 1; } else { hash[temp.data] = 1; } } var count = 0; for (var temp = head; temp != null; temp = temp.next) { // Check whether the frequency of // current element is 1 or not if (hash[temp.data] == 1) { document.write(temp.data + \" \"); count++; } } // If No unique element in list if (count == 0) document.write(\" No Unique Elements \"); } // Driver Code head = null; // creating linked list push(head, 5); push(head, 4); push(head, 3); push(head, 5); push(head, 3); push(head, 2); push(head, 4); push(head, 4); push(head, 1); uniqueElements(head); // This code is contributed by rdtank. </script>", "e": 35719, "s": 34009, "text": null }, { "code": null, "e": 35723, "s": 35719, "text": "1 2" }, { "code": null, "e": 35773, "s": 35725, "text": "Time Complexity : O(N) Auxiliary Space : O(N) " }, { "code": null, "e": 35789, "s": 35773, "text": "Vikash Kumar 37" }, { "code": null, "e": 35799, "s": 35789, "text": "Rajput-Ji" }, { "code": null, "e": 35811, "s": 35799, "text": "29AjayKumar" }, { "code": null, "e": 35818, "s": 35811, "text": "rdtank" }, { "code": null, "e": 35836, "s": 35818, "text": "cpp-unordered_map" }, { "code": null, "e": 35841, "s": 35836, "text": "Hash" }, { "code": null, "e": 35853, "s": 35841, "text": "Linked List" }, { "code": null, "e": 35872, "s": 35853, "text": "Technical Scripter" }, { "code": null, "e": 35884, "s": 35872, "text": "Linked List" }, { "code": null, "e": 35889, "s": 35884, "text": "Hash" }, { "code": null, "e": 35987, "s": 35889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36023, "s": 35987, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 36049, "s": 36023, "text": "Sort string of characters" }, { "code": null, "e": 36088, "s": 36049, "text": "Counting frequencies of array elements" }, { "code": null, "e": 36122, "s": 36088, "text": "Most frequent element in an array" }, { "code": null, "e": 36156, "s": 36122, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 36191, "s": 36156, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 36230, "s": 36191, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 36278, "s": 36230, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36316, "s": 36278, "text": "Linked List | Set 3 (Deleting a node)" } ]
How to Delete a Firebase User from Android App? - GeeksforGeeks
12 Mar, 2021 We have seen in many of the apps that if have the choice to delete the user or can say your account permanently. Here we are going to see how we can implement that in our app and can delete our account permanently from the firebase authentication. Here while writing our code we will remove the user but before that, we will reAuthenticate the user. Step 1: If you are new to Firebase then you can Refer to User authentication using Firebase in Android. Step 2: Follow all the steps and “Login In” to your android app. Then create a mainmenu.xml file as following XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menulogout" android:title="Logout" /> <item android:id="@+id/delete" android:title="Delete User" /> </menu> Step 3: Create a new empty activity and name the activity as DeleteUser. Step 4: Then Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Java import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.widget.Toast;import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar;import androidx.viewpager.widget.ViewPager;import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.tabs.TabLayout;import com.google.firebase.auth.AuthCredential;import com.google.firebase.auth.EmailAuthProvider;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class MainActivity extends AppCompatActivity { private FirebaseAuth mAuth; private ViewPager mviewPager; private FirebaseAuth firebaseAuth; private Toolbar mtoolbar; private SectionsPagerAdapter mSectionsPagerAdapter; private TabLayout mTabLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAuth = FirebaseAuth.getInstance(); mtoolbar = (Toolbar)findViewById(R.id.main_page_toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.mainmenu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.menulogout) { FirebaseAuth.getInstance().signOut(); senttostart(); } if (item.getItemId() == R.id.delete) { startActivity(new Intent(MainActivity.this, DeleteUser.class)); } return true; }} Step 5: Working with the activity_deleteuser.xml file Navigate to the app > res > layout > activity_deleteuser.xml and add the below code to that file. Below is the code for the activity_deleteuser.xml file. We will create two simple EditText and a Button. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".DeleteUser"> <EditText android:id="@+id/email" android:layout_width="267dp" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="36dp" android:layout_marginTop="120dp" android:ems="10" android:hint="Email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/logpass" android:layout_width="259dp" android:layout_height="58dp" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="32dp" android:layout_marginTop="161dp" android:ems="10" android:hint="Password" android:inputType="textPassword" /> <Button android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="192dp" android:layout_marginTop="227dp" android:background="@color/colorPrimary" android:text="Submit Here" android:textSize="15dp" /> </RelativeLayout> Step 4: Working with the DeleteUser.java file Go to the DeleteUser.java file and refer to the following code. Below is the code for the DeleteUser.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthCredential;import com.google.firebase.auth.EmailAuthProvider;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class DeleteUser extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete_user); final EditText email = findViewById(R.id.email); final EditText password = findViewById(R.id.logpass); Button submit = findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteuser(email.getText().toString(), password.getText().toString()); } }); } private void deleteuser(String email, String password) { final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); // Get auth credentials from the user for re-authentication. The example below shows // email and password credentials but there are multiple possible providers, // such as GoogleAuthProvider or FacebookAuthProvider. AuthCredential credential = EmailAuthProvider.getCredential(email, password); // Prompt the user to re-provide their sign-in credentials if (user != null) { user.reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { user.delete() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d("TAG", "User account deleted."); startActivity(new Intent(DeleteUser.this, StartActivity.class)); Toast.makeText(DeleteUser.this, "Deleted User Successfully,", Toast.LENGTH_LONG).show(); } } }); } }); } }} Output: Firebase Android Java 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? How to Post Data to API using Retrofit 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 Arrays.sort() in Java with examples
[ { "code": null, "e": 26405, "s": 26377, "text": "\n12 Mar, 2021" }, { "code": null, "e": 26755, "s": 26405, "text": "We have seen in many of the apps that if have the choice to delete the user or can say your account permanently. Here we are going to see how we can implement that in our app and can delete our account permanently from the firebase authentication. Here while writing our code we will remove the user but before that, we will reAuthenticate the user." }, { "code": null, "e": 26859, "s": 26755, "text": "Step 1: If you are new to Firebase then you can Refer to User authentication using Firebase in Android." }, { "code": null, "e": 26969, "s": 26859, "text": "Step 2: Follow all the steps and “Login In” to your android app. Then create a mainmenu.xml file as following" }, { "code": null, "e": 26973, "s": 26969, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\"> <item android:id=\"@+id/menulogout\" android:title=\"Logout\" /> <item android:id=\"@+id/delete\" android:title=\"Delete User\" /> </menu>", "e": 27308, "s": 26973, "text": null }, { "code": null, "e": 27382, "s": 27308, "text": "Step 3: Create a new empty activity and name the activity as DeleteUser. " }, { "code": null, "e": 27511, "s": 27382, "text": "Step 4: Then Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file." }, { "code": null, "e": 27516, "s": 27511, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.widget.Toast;import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar;import androidx.viewpager.widget.ViewPager;import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.tabs.TabLayout;import com.google.firebase.auth.AuthCredential;import com.google.firebase.auth.EmailAuthProvider;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class MainActivity extends AppCompatActivity { private FirebaseAuth mAuth; private ViewPager mviewPager; private FirebaseAuth firebaseAuth; private Toolbar mtoolbar; private SectionsPagerAdapter mSectionsPagerAdapter; private TabLayout mTabLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAuth = FirebaseAuth.getInstance(); mtoolbar = (Toolbar)findViewById(R.id.main_page_toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.mainmenu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.menulogout) { FirebaseAuth.getInstance().signOut(); senttostart(); } if (item.getItemId() == R.id.delete) { startActivity(new Intent(MainActivity.this, DeleteUser.class)); } return true; }}", "e": 29342, "s": 27516, "text": null }, { "code": null, "e": 29396, "s": 29342, "text": "Step 5: Working with the activity_deleteuser.xml file" }, { "code": null, "e": 29599, "s": 29396, "text": "Navigate to the app > res > layout > activity_deleteuser.xml and add the below code to that file. Below is the code for the activity_deleteuser.xml file. We will create two simple EditText and a Button." }, { "code": null, "e": 29603, "s": 29599, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".DeleteUser\"> <EditText android:id=\"@+id/email\" android:layout_width=\"267dp\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"36dp\" android:layout_marginTop=\"120dp\" android:ems=\"10\" android:hint=\"Email\" android:inputType=\"textEmailAddress\" /> <EditText android:id=\"@+id/logpass\" android:layout_width=\"259dp\" android:layout_height=\"58dp\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"161dp\" android:ems=\"10\" android:hint=\"Password\" android:inputType=\"textPassword\" /> <Button android:id=\"@+id/submit\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"192dp\" android:layout_marginTop=\"227dp\" android:background=\"@color/colorPrimary\" android:text=\"Submit Here\" android:textSize=\"15dp\" /> </RelativeLayout>", "e": 31170, "s": 29603, "text": null }, { "code": null, "e": 31216, "s": 31170, "text": "Step 4: Working with the DeleteUser.java file" }, { "code": null, "e": 31402, "s": 31216, "text": "Go to the DeleteUser.java file and refer to the following code. Below is the code for the DeleteUser.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31407, "s": 31402, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthCredential;import com.google.firebase.auth.EmailAuthProvider;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class DeleteUser extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete_user); final EditText email = findViewById(R.id.email); final EditText password = findViewById(R.id.logpass); Button submit = findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteuser(email.getText().toString(), password.getText().toString()); } }); } private void deleteuser(String email, String password) { final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); // Get auth credentials from the user for re-authentication. The example below shows // email and password credentials but there are multiple possible providers, // such as GoogleAuthProvider or FacebookAuthProvider. AuthCredential credential = EmailAuthProvider.getCredential(email, password); // Prompt the user to re-provide their sign-in credentials if (user != null) { user.reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { user.delete() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(\"TAG\", \"User account deleted.\"); startActivity(new Intent(DeleteUser.this, StartActivity.class)); Toast.makeText(DeleteUser.this, \"Deleted User Successfully,\", Toast.LENGTH_LONG).show(); } } }); } }); } }}", "e": 34255, "s": 31407, "text": null }, { "code": null, "e": 34264, "s": 34255, "text": "Output: " }, { "code": null, "e": 34273, "s": 34264, "text": "Firebase" }, { "code": null, "e": 34281, "s": 34273, "text": "Android" }, { "code": null, "e": 34286, "s": 34281, "text": "Java" }, { "code": null, "e": 34291, "s": 34286, "text": "Java" }, { "code": null, "e": 34299, "s": 34291, "text": "Android" }, { "code": null, "e": 34397, "s": 34299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34435, "s": 34397, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 34474, "s": 34435, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34524, "s": 34474, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 34575, "s": 34524, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 34617, "s": 34575, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 34632, "s": 34617, "text": "Arrays in Java" }, { "code": null, "e": 34676, "s": 34632, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34698, "s": 34676, "text": "For-each loop in Java" }, { "code": null, "e": 34749, "s": 34698, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
ISRO | ISRO CS 2018 | Question 76 - GeeksforGeeks
04 Jul, 2018 Let us assume that transaction T1 has arrived before transaction T2. Consider the schedule S=r1(A); r2(B) ; w2(A); w1(B) Which of the following is true?(A) Allowed under basic timestamp protocol.(B) Not allowed under basic timestamp protocols because T1 is rolled back(C) Not allowed under basic timestamp protocols because T2 is rolled back(D) None of theseAnswer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post ISRO Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ISRO | ISRO CS 2016 | Question 29 ISRO | ISRO CS 2017 - May | Question 17 ISRO | ISRO CS 2017 | Question 54 ISRO | ISRO CS 2007 | Question 55 ISRO | ISRO CS 2017 - May | Question 40 ISRO | ISRO CS 2007 | Question 80 ISRO | ISRO CS 2017 - May | Question 13 ISRO | ISRO CS 2013 | Question 54 ISRO | ISRO CS 2013 | Question 51 ISRO | ISRO CS 2014 | Question 31
[ { "code": null, "e": 25729, "s": 25701, "text": "\n04 Jul, 2018" }, { "code": null, "e": 25820, "s": 25729, "text": "Let us assume that transaction T1 has arrived before transaction T2. Consider the schedule" }, { "code": null, "e": 25851, "s": 25820, "text": "S=r1(A); r2(B) ; w2(A); w1(B) " }, { "code": null, "e": 26198, "s": 25851, "text": "Which of the following is true?(A) Allowed under basic timestamp protocol.(B) Not allowed under basic timestamp protocols because T1 is rolled back(C) Not allowed under basic timestamp protocols because T2 is rolled back(D) None of theseAnswer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post" }, { "code": null, "e": 26203, "s": 26198, "text": "ISRO" }, { "code": null, "e": 26301, "s": 26203, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26335, "s": 26301, "text": "ISRO | ISRO CS 2016 | Question 29" }, { "code": null, "e": 26375, "s": 26335, "text": "ISRO | ISRO CS 2017 - May | Question 17" }, { "code": null, "e": 26409, "s": 26375, "text": "ISRO | ISRO CS 2017 | Question 54" }, { "code": null, "e": 26443, "s": 26409, "text": "ISRO | ISRO CS 2007 | Question 55" }, { "code": null, "e": 26483, "s": 26443, "text": "ISRO | ISRO CS 2017 - May | Question 40" }, { "code": null, "e": 26517, "s": 26483, "text": "ISRO | ISRO CS 2007 | Question 80" }, { "code": null, "e": 26557, "s": 26517, "text": "ISRO | ISRO CS 2017 - May | Question 13" }, { "code": null, "e": 26591, "s": 26557, "text": "ISRO | ISRO CS 2013 | Question 54" }, { "code": null, "e": 26625, "s": 26591, "text": "ISRO | ISRO CS 2013 | Question 51" } ]
Program to check if matrix is lower triangular - GeeksforGeeks
26 Apr, 2021 Given a square matrix and the task is to check the matrix is in lower triangular form or not. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Examples: Input : mat[4][4] = {{1, 0, 0, 0}, {1, 4, 0, 0}, {4, 6, 2, 0}, {0, 4, 7, 6}}; Output : Matrix is in lower triangular form. Input : mat[4][4] = {{1, 0, 0, 0}, {4, 3, 0, 1}, {7, 9, 2, 0}, {8, 5, 3, 6}}; Output : Matrix is not in lower triangular form. C++ Java Python3 C# PHP Javascript // Program to check lower// triangular matrix.#include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix is in// lower triangular form or not.bool isLowerTriangularMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true;} // Driver function.int main(){ int mat[N][N] = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (isLowerTriangularMatrix(mat)) cout << "Yes"; else cout << "No"; return 0;} // Java Program to check for// a lower triangular matrix.import java.io.*; class Lower_triangular{ int N = 4; // Function to check matrix is // in lower triangular form or not. boolean isLowerTriangularMatrix(int mat[][]) { for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. public static void main(String args[]) { Lower_triangular ob = new Lower_triangular(); int mat[][] = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (ob.isLowerTriangularMatrix(mat)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Anshika Goyal. # Python3 Program to check# lower triangular matrix. # Function to check matrix# is in lower triangulardef islowertriangular(M): for i in range(0, len(M)): for j in range(i + 1, len(M)): if(M[i][j] != 0): return False return True # Driver function.M = [[1,0,0,0], [1,4,0,0], [4,6,2,0], [0,4,7,6]] if islowertriangular(M): print ("Yes")else: print ("No") # This code is contributed by Anurag Rawat // C# program to check for// a lower triangular matrix.using System; class Lower_triangular{ int N = 4; // Function to check matrix is // in lower triangular form or not. bool isLowerTriangularMatrix(int[, ] mat) { for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (mat[i, j] != 0) return false; return true; } // Driver function. public static void Main() { Lower_triangular ob = new Lower_triangular(); int[, ] mat = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (ob.isLowerTriangularMatrix(mat)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m. <?php// PHP Program to check lower// triangular matrix.$N = 4; // Function to check matrix is in// lower triangular form or not.function isLowerTriangularMatrix($mat){ global $N; for ($i = 0; $i < $N; $i++) for ($j = $i + 1; $j < $N; $j++) if ($mat[$i][$j] != 0) return false; return true;} // Driver Code$mat = array(array( 1, 0, 0, 0 ), array( 1, 4, 0, 0 ), array( 4, 6, 2, 0 ), array( 0, 4, 7, 6 )); // Function callif (isLowerTriangularMatrix($mat)) echo("Yes");else echo("No"); // This code is contributed by Ajit.?> <script>// Java script Program to check for// a lower triangular matrix. let N = 4; // Function to check matrix is // in lower triangular form or not. function isLowerTriangularMatrix(mat) { for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. let mat = [[ 1, 0, 0, 0 ], [ 1, 4, 0, 0 ], [ 4, 6, 2, 0 ], [ 0, 4, 7, 6 ]]; // Function call if (isLowerTriangularMatrix(mat)) document.write("Yes"); else document.write("No"); // contributed by sravan kumar</script> Output: Yes jit_t sravankumar8128 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Count all possible paths from top left to bottom right of a mXn matrix Program to multiply two matrices Min Cost Path | DP-6 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26408, "s": 26380, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26600, "s": 26408, "text": "Given a square matrix and the task is to check the matrix is in lower triangular form or not. A square matrix is called lower triangular if all the entries above the main diagonal are zero. " }, { "code": null, "e": 26612, "s": 26600, "text": "Examples: " }, { "code": null, "e": 26989, "s": 26612, "text": "Input : mat[4][4] = {{1, 0, 0, 0},\n {1, 4, 0, 0},\n {4, 6, 2, 0},\n {0, 4, 7, 6}};\nOutput : Matrix is in lower triangular form.\n\nInput : mat[4][4] = {{1, 0, 0, 0},\n {4, 3, 0, 1},\n {7, 9, 2, 0},\n {8, 5, 3, 6}};\nOutput : Matrix is not in lower triangular form." }, { "code": null, "e": 26997, "s": 26993, "text": "C++" }, { "code": null, "e": 27002, "s": 26997, "text": "Java" }, { "code": null, "e": 27010, "s": 27002, "text": "Python3" }, { "code": null, "e": 27013, "s": 27010, "text": "C#" }, { "code": null, "e": 27017, "s": 27013, "text": "PHP" }, { "code": null, "e": 27028, "s": 27017, "text": "Javascript" }, { "code": "// Program to check lower// triangular matrix.#include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix is in// lower triangular form or not.bool isLowerTriangularMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true;} // Driver function.int main(){ int mat[N][N] = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (isLowerTriangularMatrix(mat)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 27691, "s": 27028, "text": null }, { "code": "// Java Program to check for// a lower triangular matrix.import java.io.*; class Lower_triangular{ int N = 4; // Function to check matrix is // in lower triangular form or not. boolean isLowerTriangularMatrix(int mat[][]) { for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. public static void main(String args[]) { Lower_triangular ob = new Lower_triangular(); int mat[][] = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (ob.isLowerTriangularMatrix(mat)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Anshika Goyal.", "e": 28617, "s": 27691, "text": null }, { "code": "# Python3 Program to check# lower triangular matrix. # Function to check matrix# is in lower triangulardef islowertriangular(M): for i in range(0, len(M)): for j in range(i + 1, len(M)): if(M[i][j] != 0): return False return True # Driver function.M = [[1,0,0,0], [1,4,0,0], [4,6,2,0], [0,4,7,6]] if islowertriangular(M): print (\"Yes\")else: print (\"No\") # This code is contributed by Anurag Rawat", "e": 29083, "s": 28617, "text": null }, { "code": "// C# program to check for// a lower triangular matrix.using System; class Lower_triangular{ int N = 4; // Function to check matrix is // in lower triangular form or not. bool isLowerTriangularMatrix(int[, ] mat) { for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if (mat[i, j] != 0) return false; return true; } // Driver function. public static void Main() { Lower_triangular ob = new Lower_triangular(); int[, ] mat = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (ob.isLowerTriangularMatrix(mat)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.", "e": 29952, "s": 29083, "text": null }, { "code": "<?php// PHP Program to check lower// triangular matrix.$N = 4; // Function to check matrix is in// lower triangular form or not.function isLowerTriangularMatrix($mat){ global $N; for ($i = 0; $i < $N; $i++) for ($j = $i + 1; $j < $N; $j++) if ($mat[$i][$j] != 0) return false; return true;} // Driver Code$mat = array(array( 1, 0, 0, 0 ), array( 1, 4, 0, 0 ), array( 4, 6, 2, 0 ), array( 0, 4, 7, 6 )); // Function callif (isLowerTriangularMatrix($mat)) echo(\"Yes\");else echo(\"No\"); // This code is contributed by Ajit.?>", "e": 30563, "s": 29952, "text": null }, { "code": "<script>// Java script Program to check for// a lower triangular matrix. let N = 4; // Function to check matrix is // in lower triangular form or not. function isLowerTriangularMatrix(mat) { for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. let mat = [[ 1, 0, 0, 0 ], [ 1, 4, 0, 0 ], [ 4, 6, 2, 0 ], [ 0, 4, 7, 6 ]]; // Function call if (isLowerTriangularMatrix(mat)) document.write(\"Yes\"); else document.write(\"No\"); // contributed by sravan kumar</script>", "e": 31352, "s": 30563, "text": null }, { "code": null, "e": 31362, "s": 31352, "text": "Output: " }, { "code": null, "e": 31366, "s": 31362, "text": "Yes" }, { "code": null, "e": 31374, "s": 31368, "text": "jit_t" }, { "code": null, "e": 31390, "s": 31374, "text": "sravankumar8128" }, { "code": null, "e": 31397, "s": 31390, "text": "Matrix" }, { "code": null, "e": 31416, "s": 31397, "text": "School Programming" }, { "code": null, "e": 31423, "s": 31416, "text": "Matrix" }, { "code": null, "e": 31521, "s": 31423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31545, "s": 31521, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 31607, "s": 31545, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 31678, "s": 31607, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 31711, "s": 31678, "text": "Program to multiply two matrices" }, { "code": null, "e": 31732, "s": 31711, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 31750, "s": 31732, "text": "Python Dictionary" }, { "code": null, "e": 31766, "s": 31750, "text": "Arrays in C/C++" }, { "code": null, "e": 31785, "s": 31766, "text": "Inheritance in C++" }, { "code": null, "e": 31810, "s": 31785, "text": "Reverse a string in Java" } ]
JavaScript parseFloat() Function - GeeksforGeeks
09 Dec, 2021 Below is the example of the parseFloat() function. Example:javascriptjavascript<script> var v2 = parseFloat("3.14"); document.write('Using parseFloat("3.14") = ' + v2 + "<br>");</script> javascript <script> var v2 = parseFloat("3.14"); document.write('Using parseFloat("3.14") = ' + v2 + "<br>");</script> Output:Using parseFloat("3.14") = 3.14 Using parseFloat("3.14") = 3.14 The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating-point number parsed up to that point where it encounters a character that is not a Number. Syntax: parseFloat(Value) Parameters: This function accept a single parameter as mentioned above and described below: value This parameter obtains a string which is converted to a floating-point number. Return value: It returns a floating-point Number and if the first character of a string cannot be converted to a number then the function returns NaN i.e, not a number. Below examples illustrate the parseFloat() function in JavaScript: Example 1: The parseFloat() function ignores leading and trailing spaces and returns the floating point Number of the string.Input : var n = parseFloat(" 2018 "); Output: n=2018 (floating point Number) Input : var n = parseFloat(" 2018 "); Output: n=2018 (floating point Number) Example 2:Input: var a = parseFloat("1000.04"); Output:now a = 1000.04(floating point Number)More example codes for the above function are as follows:Program 1:javascriptjavascript<!DOCTYPE html><html> <body><script> // It ignores leading and trailing spaces. a = parseFloat(" 100 ") document.write('parseFloat(" 100 ") = ' +a +"<br>"); // It returns floating point Number until // it encounters Not a Number character b = parseFloat("2018@geeksforgeeks") document.write('parseFloat("2018@geeksforgeeks") = ' +b +"<br>"); // It returns NaN on Non numeral character c = parseFloat("geeksforgeeks@2018") document.write('parseFloat("geeksforgeeks@2018") = ' +c +"<br>"); d = parseFloat("3.14") document.write('parseFloat("3.14") = ' +d +"<br>"); // It returns only first Number it encounters e = parseFloat("22 7 2018") document.write('parseFloat("22 7 2018") = ' +e +"<br>"); </script> </body></html>Output:parseFloat(" 100 ") = 100 parseFloat("2018@geeksforgeeks") = 2018 parseFloat("geeksforgeeks@2018") = NaN parseFloat("3.14") = 3.14 parseFloat("22 7 2018") = 22Program 2: Using isNaN() function to test that converted values are valid number or not.javascriptjavascript<!DOCTYPE html><html> <body><script> var x = parseFloat("3.14"); if (isNaN(x)) document.write("x is not a number" + "<br>"); else document.write("x is a number" + "<br>"); var y = parseFloat("geeksforgeeks"); if (isNaN(y)) document.write("y is not a number" + "<br>"); else document.write("y is a number" + "<br>"); // Difference between parseInt() and parseFloat() var v1 = parseInt("3.14"); var v2 = parseFloat("3.14"); document.write('Using parseInt("3.14") = ' + v1 + "<br>"); document.write('Using parseFloat("3.14") = ' + v2 + "<br>");</script> </body></html> Output:x is a number y is not a number Using parseInt("3.14") = 3 Using parseFloat("3.14") = 3.14Supported Browsers:Google Chrome 1 and aboveEdge 12 and aboveFirefox 1 and aboveInternet Explorer 3 and aboveSafari 1 and aboveOpera 3 and aboveMy Personal Notes arrow_drop_upSave Input: var a = parseFloat("1000.04"); Output:now a = 1000.04(floating point Number) More example codes for the above function are as follows: Program 1: javascript <!DOCTYPE html><html> <body><script> // It ignores leading and trailing spaces. a = parseFloat(" 100 ") document.write('parseFloat(" 100 ") = ' +a +"<br>"); // It returns floating point Number until // it encounters Not a Number character b = parseFloat("2018@geeksforgeeks") document.write('parseFloat("2018@geeksforgeeks") = ' +b +"<br>"); // It returns NaN on Non numeral character c = parseFloat("geeksforgeeks@2018") document.write('parseFloat("geeksforgeeks@2018") = ' +c +"<br>"); d = parseFloat("3.14") document.write('parseFloat("3.14") = ' +d +"<br>"); // It returns only first Number it encounters e = parseFloat("22 7 2018") document.write('parseFloat("22 7 2018") = ' +e +"<br>"); </script> </body></html> parseFloat(" 100 ") = 100 parseFloat("2018@geeksforgeeks") = 2018 parseFloat("geeksforgeeks@2018") = NaN parseFloat("3.14") = 3.14 parseFloat("22 7 2018") = 22 Program 2: Using isNaN() function to test that converted values are valid number or not. javascript <!DOCTYPE html><html> <body><script> var x = parseFloat("3.14"); if (isNaN(x)) document.write("x is not a number" + "<br>"); else document.write("x is a number" + "<br>"); var y = parseFloat("geeksforgeeks"); if (isNaN(y)) document.write("y is not a number" + "<br>"); else document.write("y is a number" + "<br>"); // Difference between parseInt() and parseFloat() var v1 = parseInt("3.14"); var v2 = parseFloat("3.14"); document.write('Using parseInt("3.14") = ' + v1 + "<br>"); document.write('Using parseFloat("3.14") = ' + v2 + "<br>");</script> </body></html> x is a number y is not a number Using parseInt("3.14") = 3 Using parseFloat("3.14") = 3.14 Supported Browsers: Google Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 3 and above Safari 1 and above Opera 3 and above saurabh1990aror ysachin2314 javascript-functions JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request JavaScript | console.log() with Examples How to read a local text file using JavaScript? How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 25475, "s": 25447, "text": "\n09 Dec, 2021" }, { "code": null, "e": 25526, "s": 25475, "text": "Below is the example of the parseFloat() function." }, { "code": null, "e": 25674, "s": 25526, "text": "Example:javascriptjavascript<script> var v2 = parseFloat(\"3.14\"); document.write('Using parseFloat(\"3.14\") = ' + v2 + \"<br>\");</script>" }, { "code": null, "e": 25685, "s": 25674, "text": "javascript" }, { "code": "<script> var v2 = parseFloat(\"3.14\"); document.write('Using parseFloat(\"3.14\") = ' + v2 + \"<br>\");</script>", "e": 25805, "s": 25685, "text": null }, { "code": null, "e": 25844, "s": 25805, "text": "Output:Using parseFloat(\"3.14\") = 3.14" }, { "code": null, "e": 25876, "s": 25844, "text": "Using parseFloat(\"3.14\") = 3.14" }, { "code": null, "e": 26240, "s": 25876, "text": "The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating-point number parsed up to that point where it encounters a character that is not a Number." }, { "code": null, "e": 26248, "s": 26240, "text": "Syntax:" }, { "code": null, "e": 26266, "s": 26248, "text": "parseFloat(Value)" }, { "code": null, "e": 26358, "s": 26266, "text": "Parameters: This function accept a single parameter as mentioned above and described below:" }, { "code": null, "e": 26443, "s": 26358, "text": "value This parameter obtains a string which is converted to a floating-point number." }, { "code": null, "e": 26612, "s": 26443, "text": "Return value: It returns a floating-point Number and if the first character of a string cannot be converted to a number then the function returns NaN i.e, not a number." }, { "code": null, "e": 26679, "s": 26612, "text": "Below examples illustrate the parseFloat() function in JavaScript:" }, { "code": null, "e": 26883, "s": 26679, "text": "Example 1: The parseFloat() function ignores leading and trailing spaces and returns the floating point Number of the string.Input : var n = parseFloat(\" 2018 \");\nOutput: n=2018 (floating point Number)" }, { "code": null, "e": 26962, "s": 26883, "text": "Input : var n = parseFloat(\" 2018 \");\nOutput: n=2018 (floating point Number)" }, { "code": null, "e": 29140, "s": 26962, "text": "Example 2:Input: var a = parseFloat(\"1000.04\");\nOutput:now a = 1000.04(floating point Number)More example codes for the above function are as follows:Program 1:javascriptjavascript<!DOCTYPE html><html> <body><script> // It ignores leading and trailing spaces. a = parseFloat(\" 100 \") document.write('parseFloat(\" 100 \") = ' +a +\"<br>\"); // It returns floating point Number until // it encounters Not a Number character b = parseFloat(\"2018@geeksforgeeks\") document.write('parseFloat(\"2018@geeksforgeeks\") = ' +b +\"<br>\"); // It returns NaN on Non numeral character c = parseFloat(\"geeksforgeeks@2018\") document.write('parseFloat(\"geeksforgeeks@2018\") = ' +c +\"<br>\"); d = parseFloat(\"3.14\") document.write('parseFloat(\"3.14\") = ' +d +\"<br>\"); // It returns only first Number it encounters e = parseFloat(\"22 7 2018\") document.write('parseFloat(\"22 7 2018\") = ' +e +\"<br>\"); </script> </body></html>Output:parseFloat(\" 100 \") = 100\nparseFloat(\"2018@geeksforgeeks\") = 2018\nparseFloat(\"geeksforgeeks@2018\") = NaN\nparseFloat(\"3.14\") = 3.14\nparseFloat(\"22 7 2018\") = 22Program 2: Using isNaN() function to test that converted values are valid number or not.javascriptjavascript<!DOCTYPE html><html> <body><script> var x = parseFloat(\"3.14\"); if (isNaN(x)) document.write(\"x is not a number\" + \"<br>\"); else document.write(\"x is a number\" + \"<br>\"); var y = parseFloat(\"geeksforgeeks\"); if (isNaN(y)) document.write(\"y is not a number\" + \"<br>\"); else document.write(\"y is a number\" + \"<br>\"); // Difference between parseInt() and parseFloat() var v1 = parseInt(\"3.14\"); var v2 = parseFloat(\"3.14\"); document.write('Using parseInt(\"3.14\") = ' + v1 + \"<br>\"); document.write('Using parseFloat(\"3.14\") = ' + v2 + \"<br>\");</script> </body></html> Output:x is a number\ny is not a number\nUsing parseInt(\"3.14\") = 3\nUsing parseFloat(\"3.14\") = 3.14Supported Browsers:Google Chrome 1 and aboveEdge 12 and aboveFirefox 1 and aboveInternet Explorer 3 and aboveSafari 1 and aboveOpera 3 and aboveMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29224, "s": 29140, "text": "Input: var a = parseFloat(\"1000.04\");\nOutput:now a = 1000.04(floating point Number)" }, { "code": null, "e": 29282, "s": 29224, "text": "More example codes for the above function are as follows:" }, { "code": null, "e": 29293, "s": 29282, "text": "Program 1:" }, { "code": null, "e": 29304, "s": 29293, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body><script> // It ignores leading and trailing spaces. a = parseFloat(\" 100 \") document.write('parseFloat(\" 100 \") = ' +a +\"<br>\"); // It returns floating point Number until // it encounters Not a Number character b = parseFloat(\"2018@geeksforgeeks\") document.write('parseFloat(\"2018@geeksforgeeks\") = ' +b +\"<br>\"); // It returns NaN on Non numeral character c = parseFloat(\"geeksforgeeks@2018\") document.write('parseFloat(\"geeksforgeeks@2018\") = ' +c +\"<br>\"); d = parseFloat(\"3.14\") document.write('parseFloat(\"3.14\") = ' +d +\"<br>\"); // It returns only first Number it encounters e = parseFloat(\"22 7 2018\") document.write('parseFloat(\"22 7 2018\") = ' +e +\"<br>\"); </script> </body></html>", "e": 30099, "s": 29304, "text": null }, { "code": null, "e": 30259, "s": 30099, "text": "parseFloat(\" 100 \") = 100\nparseFloat(\"2018@geeksforgeeks\") = 2018\nparseFloat(\"geeksforgeeks@2018\") = NaN\nparseFloat(\"3.14\") = 3.14\nparseFloat(\"22 7 2018\") = 22" }, { "code": null, "e": 30348, "s": 30259, "text": "Program 2: Using isNaN() function to test that converted values are valid number or not." }, { "code": null, "e": 30359, "s": 30348, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body><script> var x = parseFloat(\"3.14\"); if (isNaN(x)) document.write(\"x is not a number\" + \"<br>\"); else document.write(\"x is a number\" + \"<br>\"); var y = parseFloat(\"geeksforgeeks\"); if (isNaN(y)) document.write(\"y is not a number\" + \"<br>\"); else document.write(\"y is a number\" + \"<br>\"); // Difference between parseInt() and parseFloat() var v1 = parseInt(\"3.14\"); var v2 = parseFloat(\"3.14\"); document.write('Using parseInt(\"3.14\") = ' + v1 + \"<br>\"); document.write('Using parseFloat(\"3.14\") = ' + v2 + \"<br>\");</script> </body></html> ", "e": 31013, "s": 30359, "text": null }, { "code": null, "e": 31104, "s": 31013, "text": "x is a number\ny is not a number\nUsing parseInt(\"3.14\") = 3\nUsing parseFloat(\"3.14\") = 3.14" }, { "code": null, "e": 31124, "s": 31104, "text": "Supported Browsers:" }, { "code": null, "e": 31150, "s": 31124, "text": "Google Chrome 1 and above" }, { "code": null, "e": 31168, "s": 31150, "text": "Edge 12 and above" }, { "code": null, "e": 31188, "s": 31168, "text": "Firefox 1 and above" }, { "code": null, "e": 31218, "s": 31188, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 31237, "s": 31218, "text": "Safari 1 and above" }, { "code": null, "e": 31255, "s": 31237, "text": "Opera 3 and above" }, { "code": null, "e": 31271, "s": 31255, "text": "saurabh1990aror" }, { "code": null, "e": 31283, "s": 31271, "text": "ysachin2314" }, { "code": null, "e": 31304, "s": 31283, "text": "javascript-functions" }, { "code": null, "e": 31315, "s": 31304, "text": "JavaScript" }, { "code": null, "e": 31413, "s": 31315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31453, "s": 31413, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31498, "s": 31453, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31559, "s": 31498, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31631, "s": 31559, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31683, "s": 31631, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31729, "s": 31683, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 31770, "s": 31729, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31811, "s": 31770, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 31859, "s": 31811, "text": "How to read a local text file using JavaScript?" } ]
How to animate jQuery addClass/removeClass functions ? - GeeksforGeeks
21 May, 2021 In this article, we will learn to animate using jQuery addClass() and removeClass() functions. We are going to use jQuery and jQuery UI. jQuery UI (User Interface) is free and open-source software that is built on top of the core powerful jQuery library. If you want to use jQuery UI, you must include jQuery too. jQuery UI provides more features like add Class, color animation and easing, etc. We are going to use some jQuery UI addClass() and removeClass() methods. addClass() method: It is used to add specified classes to each of the targeted elements while animating all style changes.Syntax:.addClass(className, [duration], [easing], [callback]) addClass() method: It is used to add specified classes to each of the targeted elements while animating all style changes. Syntax: .addClass(className, [duration], [easing], [callback]) removeClass() method: It is used to remove the classes from the element while animating all style changes.Syntax:.removeClass(className, [duration], [easing], [callback]) removeClass() method: It is used to remove the classes from the element while animating all style changes. Syntax: .removeClass(className, [duration], [easing], [callback]) Example: The following example demonstrates animation using the above classes. We are using setTimeout to remove the class after the animation. HTML <!DOCTYPE html><html><head> <style> #btn { padding: 10px 8px; color: green; background-color: rgba(122, 122, 122, 0.322); border-radius: 12px; } .geeks { font-size: 40px; color: green; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; text-shadow: 2px 2px 4px #880a0a; letter-spacing: 2px; } </style> <!-- JQuery CDN --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> <!-- JQuery UI CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function () { $("#btn").click(function () { $("h2").addClass("geeks", 2000, myCallback); }); function myCallback() { setTimeout(function () { $("h2").removeClass("geeks"); }, 3000); } }); </script></head><body><h2>Welcome to GeeksForGeeks.</h2><button id="btn"> Click to see the effect</button></body></html> Output: animation effect jQuery-Methods jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26978, "s": 26950, "text": "\n21 May, 2021" }, { "code": null, "e": 27073, "s": 26978, "text": "In this article, we will learn to animate using jQuery addClass() and removeClass() functions." }, { "code": null, "e": 27376, "s": 27073, "text": "We are going to use jQuery and jQuery UI. jQuery UI (User Interface) is free and open-source software that is built on top of the core powerful jQuery library. If you want to use jQuery UI, you must include jQuery too. jQuery UI provides more features like add Class, color animation and easing, etc." }, { "code": null, "e": 27449, "s": 27376, "text": "We are going to use some jQuery UI addClass() and removeClass() methods." }, { "code": null, "e": 27633, "s": 27449, "text": "addClass() method: It is used to add specified classes to each of the targeted elements while animating all style changes.Syntax:.addClass(className, [duration], [easing], [callback])" }, { "code": null, "e": 27756, "s": 27633, "text": "addClass() method: It is used to add specified classes to each of the targeted elements while animating all style changes." }, { "code": null, "e": 27764, "s": 27756, "text": "Syntax:" }, { "code": null, "e": 27819, "s": 27764, "text": ".addClass(className, [duration], [easing], [callback])" }, { "code": null, "e": 27990, "s": 27819, "text": "removeClass() method: It is used to remove the classes from the element while animating all style changes.Syntax:.removeClass(className, [duration], [easing], [callback])" }, { "code": null, "e": 28097, "s": 27990, "text": "removeClass() method: It is used to remove the classes from the element while animating all style changes." }, { "code": null, "e": 28105, "s": 28097, "text": "Syntax:" }, { "code": null, "e": 28163, "s": 28105, "text": ".removeClass(className, [duration], [easing], [callback])" }, { "code": null, "e": 28307, "s": 28163, "text": "Example: The following example demonstrates animation using the above classes. We are using setTimeout to remove the class after the animation." }, { "code": null, "e": 28312, "s": 28307, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style> #btn { padding: 10px 8px; color: green; background-color: rgba(122, 122, 122, 0.322); border-radius: 12px; } .geeks { font-size: 40px; color: green; font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif; text-shadow: 2px 2px 4px #880a0a; letter-spacing: 2px; } </style> <!-- JQuery CDN --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script> <!-- JQuery UI CDN --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function () { $(\"#btn\").click(function () { $(\"h2\").addClass(\"geeks\", 2000, myCallback); }); function myCallback() { setTimeout(function () { $(\"h2\").removeClass(\"geeks\"); }, 3000); } }); </script></head><body><h2>Welcome to GeeksForGeeks.</h2><button id=\"btn\"> Click to see the effect</button></body></html>", "e": 29491, "s": 28312, "text": null }, { "code": null, "e": 29499, "s": 29491, "text": "Output:" }, { "code": null, "e": 29516, "s": 29499, "text": "animation effect" }, { "code": null, "e": 29531, "s": 29516, "text": "jQuery-Methods" }, { "code": null, "e": 29548, "s": 29531, "text": "jQuery-Questions" }, { "code": null, "e": 29555, "s": 29548, "text": "Picked" }, { "code": null, "e": 29562, "s": 29555, "text": "JQuery" }, { "code": null, "e": 29579, "s": 29562, "text": "Web Technologies" }, { "code": null, "e": 29677, "s": 29579, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29732, "s": 29677, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 29805, "s": 29732, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 29828, "s": 29805, "text": "jQuery | ajax() Method" }, { "code": null, "e": 29864, "s": 29828, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 29921, "s": 29864, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 29961, "s": 29921, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29994, "s": 29961, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30039, "s": 29994, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30082, "s": 30039, "text": "How to fetch data from an API in ReactJS ?" } ]
Check if a given array can represent Preorder Traversal of Binary Search Tree - GeeksforGeeks
20 Jan, 2022 Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n). Examples: Input: pre[] = {2, 4, 3} Output: true Given array can represent preorder traversal of below tree 2 \ 4 / 3 Input: pre[] = {2, 4, 1} Output: false Given array cannot represent preorder traversal of a Binary Search Tree. Input: pre[] = {40, 30, 35, 80, 100} Output: true Given array can represent preorder traversal of below tree 40 / \ 30 80 \ \ 35 100 Input: pre[] = {40, 30, 35, 20, 80, 100} Output: false Given array cannot represent preorder traversal of a Binary Search Tree. A Simple Solution is to do following for every node pre[i] starting from first one. 1) Find the first greater value on right side of current node. Let the index of this node be j. Return true if following conditions hold. Else return false (i) All values after the above found greater value are greater than current node. (ii) Recursive calls for the subarrays pre[i+1..j-1] and pre[j+1..n-1] also return true. Time Complexity of the above solution is O(n2) An Efficient Solution can solve this problem in O(n) time. The idea is to use a stack. This problem is similar to Next (or closest) Greater Element problem. Here we find the next greater element and after finding next greater, if we find a smaller element, then return false. 1) Create an empty stack. 2) Initialize root as INT_MIN. 3) Do following for every element pre[i] a) If pre[i] is smaller than current root, return false. b) Keep removing elements from stack while pre[i] is greater then stack top. Make the last removed item as new root (to be compared next). At this point, pre[i] is greater than the removed root (That is why if we see a smaller element in step a), we return false) c) push pre[i] to stack (All elements in stack are in decreasing order) Below is the implementation of above idea. C++ Java Python3 C# Javascript // C++ program for an efficient solution to check if// a given array can represent Preorder traversal of// a Binary Search Tree#include<bits/stdc++.h>using namespace std; bool canRepresentBST(int pre[], int n){ // Create an empty stack stack<int> s; // Initialize current root as minimum possible // value int root = INT_MIN; // Traverse given array for (int i=0; i<n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) return false; // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (!s.empty() && s.top()<pre[i]) { root = s.top(); s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true;} // Driver programint main(){ int pre1[] = {40, 30, 35, 80, 100}; int n = sizeof(pre1)/sizeof(pre1[0]); canRepresentBST(pre1, n)? cout << "true\n": cout << "false\n"; int pre2[] = {40, 30, 35, 20, 80, 100}; n = sizeof(pre2)/sizeof(pre2[0]); canRepresentBST(pre2, n)? cout << "true\n": cout << "false\n"; return 0;} // Java program for an efficient solution to check if// a given array can represent Preorder traversal of// a Binary Search Treeimport java.util.Stack; class BinarySearchTree { boolean canRepresentBST(int pre[], int n) { // Create an empty stack Stack<Integer> s = new Stack<Integer>(); // Initialize current root as minimum possible // value int root = Integer.MIN_VALUE; // Traverse given array for (int i = 0; i < n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) { return false; } // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (!s.empty() && s.peek() < pre[i]) { root = s.peek(); s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true; } public static void main(String args[]) { BinarySearchTree bst = new BinarySearchTree(); int[] pre1 = new int[]{40, 30, 35, 80, 100}; int n = pre1.length; if (bst.canRepresentBST(pre1, n) == true) { System.out.println("true"); } else { System.out.println("false"); } int[] pre2 = new int[]{40, 30, 35, 20, 80, 100}; int n1 = pre2.length; if (bst.canRepresentBST(pre2, n) == true) { System.out.println("true"); } else { System.out.println("false"); } }} //This code is contributed by Mayank Jaiswal # Python program for an efficient solution to check if# a given array can represent Preorder traversal of# a Binary Search Tree INT_MIN = -2**32 def canRepresentBST(pre): # Create an empty stack s = [] # Initialize current root as minimum possible value root = INT_MIN # Traverse given array for value in pre: #NOTE:value is equal to pre[i] according to the #given algo # If we find a node who is on the right side # and smaller than root, return False if value < root : return False # If value(pre[i]) is in right subtree of stack top, # Keep removing items smaller than value # and make the last removed items as new root while(len(s) > 0 and s[-1] < value) : root = s.pop() # At this point either stack is empty or value # is smaller than root, push value s.append(value) return True # Driver Programpre1 = [40 , 30 , 35 , 80 , 100]print ("true" if canRepresentBST(pre1) == True else "false")pre2 = [40 , 30 , 35 , 20 , 80 , 100]print ("true" if canRepresentBST(pre2) == True else "false") # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program for an efficient solution// to check if a given array can represent // Preorder traversal of a Binary Search Treeusing System;using System.Collections.Generic; class GFG{ public virtual bool canRepresentBST(int[] pre, int n){ // Create an empty stack Stack<int> s = new Stack<int>(); // Initialize current root as minimum // possible value int root = int.MinValue; // Traverse given array for (int i = 0; i < n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) { return false; } // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (s.Count > 0 && s.Peek() < pre[i]) { root = s.Peek(); s.Pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.Push(pre[i]); } return true;} // Driver Codepublic static void Main(string[] args){ GFG bst = new GFG(); int[] pre1 = new int[]{40, 30, 35, 80, 100}; int n = pre1.Length; if (bst.canRepresentBST(pre1, n) == true) { Console.WriteLine("true"); } else { Console.WriteLine("false"); } int[] pre2 = new int[]{40, 30, 35, 20, 80, 100}; int n1 = pre2.Length; if (bst.canRepresentBST(pre2, n) == true) { Console.WriteLine("true"); } else { Console.WriteLine("false"); }}} // This code is contributed by Shrikant13 <script> // Javascript program for an efficient// solution to check if a given array// can represent Preorder traversal of// a Binary Search Treefunction canRepresentBST(pre, n){ // Create an empty stack var s = []; // Initialize current root as minimum possible // value var root = -1000000000; // Traverse given array for(var i = 0; i < n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) return false; // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (s.length != 0 && s[s.length - 1] < pre[i]) { root = s[s.length - 1]; s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true;} // Driver codevar pre1 = [ 40, 30, 35, 80, 100 ];var n = pre1.length;canRepresentBST(pre1, n) ? document.write("true<br>"): document.write("false<br>");var pre2 = [ 40, 30, 35, 20, 80, 100 ];n = pre2.length;canRepresentBST(pre2, n) ? document.write("true"): document.write("false"); // This code is contributed by importantly </script> true false Another approach: We can check if the given preorder traversal is valid or not for a BST without using stack. The idea is to use the similar concept of “Building a BST using narrowing bound algorithm”. We will recursively visit all nodes, but we will not build the nodes. In the end, if the complete array is not traversed, then that means that array can not represent the preorder traversal of any binary tree. Below is the implementation of the above idea: C++ Java Python3 C# Javascript // C++ program to illustrate if a given array can represent// a preorder traversal of a BST or not #include <bits/stdc++.h>using namespace std; // We are actually not building the treevoid buildBST_helper(int& preIndex, int n, int pre[], int min, int max){ if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(preIndex, n, pre, min, rootData); // build right subtree buildBST_helper(preIndex, n, pre, rootData, max); } // else // return NULL;} bool canRepresentBST(int arr[], int N){ // code here int min = INT_MIN, max = INT_MAX; int preIndex = 0; buildBST_helper(preIndex, N, arr, min, max); return preIndex == N;} // Driver Codeint main(){ int preorder1[] = { 2, 4, 3 }; /* 2 \ 4 / 3 */ int n1 = sizeof(preorder1) / sizeof(preorder1[0]); if (canRepresentBST(preorder1, n1)) cout << "\npreorder1 can represent BST"; else cout << "\npreorder1 can not represent BST :("; int preorder2[] = { 5, 3, 4, 1, 6, 10 }; int n2 = sizeof(preorder2) / sizeof(preorder2[0]); /* 5 / \ 3 1 \ / \ 4 6 10 */ if (canRepresentBST(preorder2, n2)) cout << "\npreorder2 can represent BST"; else cout << "\npreorder2 can not represent BST :("; int preorder3[] = { 5, 3, 4, 8, 6, 10 }; int n3 = sizeof(preorder3) / sizeof(preorder3[0]); /* 5 / \ 3 8 \ / \ 4 6 10 */ if (canRepresentBST(preorder3, n3)) cout << "\npreorder3 can represent BST"; else cout << "\npreorder3 can not represent BST :("; return 0;} // This code is contributed by Sourashis Mondal // Java program to illustrate if a given array can represent// a preorder traversal of a BST or notpublic class Main{ static int preIndex = 0; // We are actually not building the tree static void buildBST_helper(int n, int[] pre, int min, int max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(n, pre, min, rootData); // build right subtree buildBST_helper(n, pre, rootData, max); } // else // return NULL; } static boolean canRepresentBST(int[] arr, int N) { // code here int min = Integer.MIN_VALUE, max = Integer.MAX_VALUE; buildBST_helper(N, arr, min, max); return preIndex == N; } public static void main(String[] args) { int[] preorder1 = { 2, 4, 3 }; /* 2 \ 4 / 3 */ int n1 = preorder1.length; System.out.println(); if (canRepresentBST(preorder1, n1)) System.out.print("preorder1 can represent BST"); else System.out.print("preorder1 can not represent BST :("); int[] preorder2 = { 5, 3, 4, 1, 6, 10 }; int n2 = preorder2.length; System.out.println(); /* 5 / \ 3 1 \ / \ 4 6 10 */ if (!canRepresentBST(preorder2, n2)) System.out.print("preorder2 can represent BST"); else System.out.print("preorder2 can not represent BST :("); int[] preorder3 = { 5, 3, 4, 8, 6, 10 }; int n3 = preorder3.length; System.out.println(); /* 5 / \ 3 8 \ / \ 4 6 10 */ if (canRepresentBST(preorder3, n3)) System.out.print("preorder3 can represent BST"); else System.out.print("preorder3 can not represent BST :("); }} // This code is contributed by mukesh07. # Python3 program to illustrate if a given array can represent# a preorder traversal of a BST or notimport sys preIndex = 0 # We are actually not building the treedef buildBST_helper(n, pre, Min, Max): global preIndex if (preIndex >= n): return if (Min <= pre[preIndex] and pre[preIndex] <= Max): # build node rootData = pre[preIndex] preIndex+=1 # build left subtree buildBST_helper(n, pre, Min, rootData) # build right subtree buildBST_helper(n, pre, rootData, Max) # else # return NULL def canRepresentBST(arr, N): global preIndex # code here Min, Max = sys.maxsize, -sys.maxsize buildBST_helper(N, arr, Min, Max) if preIndex == N: return True return False preorder1 = [ 2, 4, 3 ]""" 2 \ 4 / 3 """n1 = len(preorder1) if (not canRepresentBST(preorder1, n1)): print("preorder1 can represent BST");else: print("preorder1 can not represent BST :(") preorder2 = [ 5, 3, 4, 1, 6, 10 ]n2 = len(preorder2)""" 5 / \ 3 1 \ / \ 4 6 10 """if (canRepresentBST(preorder2, n2)): print("preorder2 can represent BST")else: print("preorder2 can not represent BST :(") preorder3 = [ 5, 3, 4, 8, 6, 10 ]n3 = len(preorder3)""" 5 / \ 3 8 \ / \ 4 6 10"""if (not canRepresentBST(preorder3, n3)): print("preorder3 can represent BST")else: print("preorder3 can not represent BST :(") // C# program to illustrate if a given array can represent// a preorder traversal of a BST or notusing System;class GFG { static int preIndex = 0; // We are actually not building the tree static void buildBST_helper(int n, int[] pre, int min, int max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(n, pre, min, rootData); // build right subtree buildBST_helper(n, pre, rootData, max); } // else // return NULL; } static bool canRepresentBST(int[] arr, int N) { // code here int min = Int32.MinValue, max = Int32.MaxValue; buildBST_helper(N, arr, min, max); return preIndex == N; } static void Main() { int[] preorder1 = { 2, 4, 3 }; /* 2 \ 4 / 3 */ int n1 = preorder1.Length; Console.WriteLine(); if (canRepresentBST(preorder1, n1)) Console.Write("preorder1 can represent BST"); else Console.Write("preorder1 can not represent BST :("); int[] preorder2 = { 5, 3, 4, 1, 6, 10 }; int n2 = preorder2.Length; Console.WriteLine(); /* 5 / \ 3 1 \ / \ 4 6 10 */ if (!canRepresentBST(preorder2, n2)) Console.Write("preorder2 can represent BST"); else Console.Write("preorder2 can not represent BST :("); int[] preorder3 = { 5, 3, 4, 8, 6, 10 }; int n3 = preorder3.Length; Console.WriteLine(); /* 5 / \ 3 8 \ / \ 4 6 10 */ if (canRepresentBST(preorder3, n3)) Console.Write("preorder3 can represent BST"); else Console.Write("preorder3 can not represent BST :("); }} // This code is contributed by rameshtravel07. <script> // Javascript program to illustrate if a given array can represent // a preorder traversal of a BST or not let preIndex = 0; // We are actually not building the tree function buildBST_helper(n, pre, min, max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node let rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(n, pre, min, rootData); // build right subtree buildBST_helper(n, pre, rootData, max); } // else // return NULL; } function canRepresentBST(arr, N) { // code here let min = Number.MIN_VALUE, max = Number.MAX_VALUE; buildBST_helper(N, arr, min, max); return preIndex == N; } let preorder1 = [ 2, 4, 3 ]; /* 2 \ 4 / 3 */ let n1 = preorder1.length; if (canRepresentBST(preorder1, n1)) document.write("</br>" + "preorder1 can represent BST"); else document.write("</br>" + "preorder1 can not represent BST :("); let preorder2 = [ 5, 3, 4, 1, 6, 10 ]; let n2 = preorder2.length; /* 5 / \ 3 1 \ / \ 4 6 10 */ if (!canRepresentBST(preorder2, n2)) document.write("</br>" + "preorder2 can represent BST"); else document.write("</br>" + "preorder2 can not represent BST :("); let preorder3 = [ 5, 3, 4, 8, 6, 10 ]; let n3 = preorder3.length; /* 5 / \ 3 8 \ / \ 4 6 10 */ if (canRepresentBST(preorder3, n3)) document.write("</br>" + "preorder3 can represent BST"); else document.write("</br>" + "preorder3 can not represent BST :("); // This code is contributed by decode2207.</script> preorder1 can represent BST preorder2 can not represent BST :( preorder3 can represent BST Time complexity: O(N)Auxiliary Space: O(height of the possible binary tree) YouTubeGeeksforGeeks507K subscribersCheck if a given array can represent Preorder Traversal of Binary Search Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fH3XUXdinCs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Romil Punetha. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 DimpleSama auspicious_boy importantly sourashis69 decode2207 divyeshrabadiya07 rameshtravel07 mukesh07 amartyaghoshgfg Adobe Amazon Linkedin Binary Search Tree Stack Tree Amazon Adobe Linkedin Stack Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Red-Black Tree | Set 2 (Insert) Optimal Binary Search Tree | DP-24 Find the node with minimum value in a Binary Search Tree Advantages of BST over Hash Table Difference between Binary Tree and Binary Search Tree Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Queue using Stacks
[ { "code": null, "e": 26549, "s": 26521, "text": "\n20 Jan, 2022" }, { "code": null, "e": 26714, "s": 26549, "text": "Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n)." }, { "code": null, "e": 26724, "s": 26714, "text": "Examples:" }, { "code": null, "e": 27265, "s": 26724, "text": "Input: pre[] = {2, 4, 3}\nOutput: true\nGiven array can represent preorder traversal\nof below tree\n 2\n \\\n 4\n /\n 3\n\nInput: pre[] = {2, 4, 1}\nOutput: false\nGiven array cannot represent preorder traversal\nof a Binary Search Tree.\n\nInput: pre[] = {40, 30, 35, 80, 100}\nOutput: true\nGiven array can represent preorder traversal\nof below tree\n 40\n / \\\n 30 80 \n \\ \\\n 35 100 \n\n\nInput: pre[] = {40, 30, 35, 20, 80, 100}\nOutput: false\nGiven array cannot represent preorder traversal\nof a Binary Search Tree." }, { "code": null, "e": 27350, "s": 27265, "text": "A Simple Solution is to do following for every node pre[i] starting from first one. " }, { "code": null, "e": 27715, "s": 27350, "text": "1) Find the first greater value on right side of current node. \n Let the index of this node be j. Return true if following \n conditions hold. Else return false\n (i) All values after the above found greater value are \n greater than current node.\n (ii) Recursive calls for the subarrays pre[i+1..j-1] and \n pre[j+1..n-1] also return true. " }, { "code": null, "e": 27762, "s": 27715, "text": "Time Complexity of the above solution is O(n2)" }, { "code": null, "e": 28038, "s": 27762, "text": "An Efficient Solution can solve this problem in O(n) time. The idea is to use a stack. This problem is similar to Next (or closest) Greater Element problem. Here we find the next greater element and after finding next greater, if we find a smaller element, then return false." }, { "code": null, "e": 28595, "s": 28038, "text": "1) Create an empty stack.\n2) Initialize root as INT_MIN.\n3) Do following for every element pre[i]\n a) If pre[i] is smaller than current root, return false.\n b) Keep removing elements from stack while pre[i] is greater\n then stack top. Make the last removed item as new root (to\n be compared next).\n At this point, pre[i] is greater than the removed root\n (That is why if we see a smaller element in step a), we \n return false)\n c) push pre[i] to stack (All elements in stack are in decreasing\n order) " }, { "code": null, "e": 28638, "s": 28595, "text": "Below is the implementation of above idea." }, { "code": null, "e": 28642, "s": 28638, "text": "C++" }, { "code": null, "e": 28647, "s": 28642, "text": "Java" }, { "code": null, "e": 28655, "s": 28647, "text": "Python3" }, { "code": null, "e": 28658, "s": 28655, "text": "C#" }, { "code": null, "e": 28669, "s": 28658, "text": "Javascript" }, { "code": "// C++ program for an efficient solution to check if// a given array can represent Preorder traversal of// a Binary Search Tree#include<bits/stdc++.h>using namespace std; bool canRepresentBST(int pre[], int n){ // Create an empty stack stack<int> s; // Initialize current root as minimum possible // value int root = INT_MIN; // Traverse given array for (int i=0; i<n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) return false; // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (!s.empty() && s.top()<pre[i]) { root = s.top(); s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true;} // Driver programint main(){ int pre1[] = {40, 30, 35, 80, 100}; int n = sizeof(pre1)/sizeof(pre1[0]); canRepresentBST(pre1, n)? cout << \"true\\n\": cout << \"false\\n\"; int pre2[] = {40, 30, 35, 20, 80, 100}; n = sizeof(pre2)/sizeof(pre2[0]); canRepresentBST(pre2, n)? cout << \"true\\n\": cout << \"false\\n\"; return 0;}", "e": 30036, "s": 28669, "text": null }, { "code": "// Java program for an efficient solution to check if// a given array can represent Preorder traversal of// a Binary Search Treeimport java.util.Stack; class BinarySearchTree { boolean canRepresentBST(int pre[], int n) { // Create an empty stack Stack<Integer> s = new Stack<Integer>(); // Initialize current root as minimum possible // value int root = Integer.MIN_VALUE; // Traverse given array for (int i = 0; i < n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) { return false; } // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (!s.empty() && s.peek() < pre[i]) { root = s.peek(); s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true; } public static void main(String args[]) { BinarySearchTree bst = new BinarySearchTree(); int[] pre1 = new int[]{40, 30, 35, 80, 100}; int n = pre1.length; if (bst.canRepresentBST(pre1, n) == true) { System.out.println(\"true\"); } else { System.out.println(\"false\"); } int[] pre2 = new int[]{40, 30, 35, 20, 80, 100}; int n1 = pre2.length; if (bst.canRepresentBST(pre2, n) == true) { System.out.println(\"true\"); } else { System.out.println(\"false\"); } }} //This code is contributed by Mayank Jaiswal", "e": 31813, "s": 30036, "text": null }, { "code": "# Python program for an efficient solution to check if# a given array can represent Preorder traversal of# a Binary Search Tree INT_MIN = -2**32 def canRepresentBST(pre): # Create an empty stack s = [] # Initialize current root as minimum possible value root = INT_MIN # Traverse given array for value in pre: #NOTE:value is equal to pre[i] according to the #given algo # If we find a node who is on the right side # and smaller than root, return False if value < root : return False # If value(pre[i]) is in right subtree of stack top, # Keep removing items smaller than value # and make the last removed items as new root while(len(s) > 0 and s[-1] < value) : root = s.pop() # At this point either stack is empty or value # is smaller than root, push value s.append(value) return True # Driver Programpre1 = [40 , 30 , 35 , 80 , 100]print (\"true\" if canRepresentBST(pre1) == True else \"false\")pre2 = [40 , 30 , 35 , 20 , 80 , 100]print (\"true\" if canRepresentBST(pre2) == True else \"false\") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 33022, "s": 31813, "text": null }, { "code": "// C# program for an efficient solution// to check if a given array can represent // Preorder traversal of a Binary Search Treeusing System;using System.Collections.Generic; class GFG{ public virtual bool canRepresentBST(int[] pre, int n){ // Create an empty stack Stack<int> s = new Stack<int>(); // Initialize current root as minimum // possible value int root = int.MinValue; // Traverse given array for (int i = 0; i < n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) { return false; } // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (s.Count > 0 && s.Peek() < pre[i]) { root = s.Peek(); s.Pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.Push(pre[i]); } return true;} // Driver Codepublic static void Main(string[] args){ GFG bst = new GFG(); int[] pre1 = new int[]{40, 30, 35, 80, 100}; int n = pre1.Length; if (bst.canRepresentBST(pre1, n) == true) { Console.WriteLine(\"true\"); } else { Console.WriteLine(\"false\"); } int[] pre2 = new int[]{40, 30, 35, 20, 80, 100}; int n1 = pre2.Length; if (bst.canRepresentBST(pre2, n) == true) { Console.WriteLine(\"true\"); } else { Console.WriteLine(\"false\"); }}} // This code is contributed by Shrikant13", "e": 34629, "s": 33022, "text": null }, { "code": "<script> // Javascript program for an efficient// solution to check if a given array// can represent Preorder traversal of// a Binary Search Treefunction canRepresentBST(pre, n){ // Create an empty stack var s = []; // Initialize current root as minimum possible // value var root = -1000000000; // Traverse given array for(var i = 0; i < n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) return false; // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (s.length != 0 && s[s.length - 1] < pre[i]) { root = s[s.length - 1]; s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true;} // Driver codevar pre1 = [ 40, 30, 35, 80, 100 ];var n = pre1.length;canRepresentBST(pre1, n) ? document.write(\"true<br>\"): document.write(\"false<br>\");var pre2 = [ 40, 30, 35, 20, 80, 100 ];n = pre2.length;canRepresentBST(pre2, n) ? document.write(\"true\"): document.write(\"false\"); // This code is contributed by importantly </script>", "e": 35997, "s": 34629, "text": null }, { "code": null, "e": 36008, "s": 35997, "text": "true\nfalse" }, { "code": null, "e": 36027, "s": 36008, "text": "Another approach: " }, { "code": null, "e": 36421, "s": 36027, "text": "We can check if the given preorder traversal is valid or not for a BST without using stack. The idea is to use the similar concept of “Building a BST using narrowing bound algorithm”. We will recursively visit all nodes, but we will not build the nodes. In the end, if the complete array is not traversed, then that means that array can not represent the preorder traversal of any binary tree." }, { "code": null, "e": 36469, "s": 36421, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 36473, "s": 36469, "text": "C++" }, { "code": null, "e": 36478, "s": 36473, "text": "Java" }, { "code": null, "e": 36486, "s": 36478, "text": "Python3" }, { "code": null, "e": 36489, "s": 36486, "text": "C#" }, { "code": null, "e": 36500, "s": 36489, "text": "Javascript" }, { "code": "// C++ program to illustrate if a given array can represent// a preorder traversal of a BST or not #include <bits/stdc++.h>using namespace std; // We are actually not building the treevoid buildBST_helper(int& preIndex, int n, int pre[], int min, int max){ if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(preIndex, n, pre, min, rootData); // build right subtree buildBST_helper(preIndex, n, pre, rootData, max); } // else // return NULL;} bool canRepresentBST(int arr[], int N){ // code here int min = INT_MIN, max = INT_MAX; int preIndex = 0; buildBST_helper(preIndex, N, arr, min, max); return preIndex == N;} // Driver Codeint main(){ int preorder1[] = { 2, 4, 3 }; /* 2 \\ 4 / 3 */ int n1 = sizeof(preorder1) / sizeof(preorder1[0]); if (canRepresentBST(preorder1, n1)) cout << \"\\npreorder1 can represent BST\"; else cout << \"\\npreorder1 can not represent BST :(\"; int preorder2[] = { 5, 3, 4, 1, 6, 10 }; int n2 = sizeof(preorder2) / sizeof(preorder2[0]); /* 5 / \\ 3 1 \\ / \\ 4 6 10 */ if (canRepresentBST(preorder2, n2)) cout << \"\\npreorder2 can represent BST\"; else cout << \"\\npreorder2 can not represent BST :(\"; int preorder3[] = { 5, 3, 4, 8, 6, 10 }; int n3 = sizeof(preorder3) / sizeof(preorder3[0]); /* 5 / \\ 3 8 \\ / \\ 4 6 10 */ if (canRepresentBST(preorder3, n3)) cout << \"\\npreorder3 can represent BST\"; else cout << \"\\npreorder3 can not represent BST :(\"; return 0;} // This code is contributed by Sourashis Mondal", "e": 38460, "s": 36500, "text": null }, { "code": "// Java program to illustrate if a given array can represent// a preorder traversal of a BST or notpublic class Main{ static int preIndex = 0; // We are actually not building the tree static void buildBST_helper(int n, int[] pre, int min, int max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(n, pre, min, rootData); // build right subtree buildBST_helper(n, pre, rootData, max); } // else // return NULL; } static boolean canRepresentBST(int[] arr, int N) { // code here int min = Integer.MIN_VALUE, max = Integer.MAX_VALUE; buildBST_helper(N, arr, min, max); return preIndex == N; } public static void main(String[] args) { int[] preorder1 = { 2, 4, 3 }; /* 2 \\ 4 / 3 */ int n1 = preorder1.length; System.out.println(); if (canRepresentBST(preorder1, n1)) System.out.print(\"preorder1 can represent BST\"); else System.out.print(\"preorder1 can not represent BST :(\"); int[] preorder2 = { 5, 3, 4, 1, 6, 10 }; int n2 = preorder2.length; System.out.println(); /* 5 / \\ 3 1 \\ / \\ 4 6 10 */ if (!canRepresentBST(preorder2, n2)) System.out.print(\"preorder2 can represent BST\"); else System.out.print(\"preorder2 can not represent BST :(\"); int[] preorder3 = { 5, 3, 4, 8, 6, 10 }; int n3 = preorder3.length; System.out.println(); /* 5 / \\ 3 8 \\ / \\ 4 6 10 */ if (canRepresentBST(preorder3, n3)) System.out.print(\"preorder3 can represent BST\"); else System.out.print(\"preorder3 can not represent BST :(\"); }} // This code is contributed by mukesh07.", "e": 40743, "s": 38460, "text": null }, { "code": "# Python3 program to illustrate if a given array can represent# a preorder traversal of a BST or notimport sys preIndex = 0 # We are actually not building the treedef buildBST_helper(n, pre, Min, Max): global preIndex if (preIndex >= n): return if (Min <= pre[preIndex] and pre[preIndex] <= Max): # build node rootData = pre[preIndex] preIndex+=1 # build left subtree buildBST_helper(n, pre, Min, rootData) # build right subtree buildBST_helper(n, pre, rootData, Max) # else # return NULL def canRepresentBST(arr, N): global preIndex # code here Min, Max = sys.maxsize, -sys.maxsize buildBST_helper(N, arr, Min, Max) if preIndex == N: return True return False preorder1 = [ 2, 4, 3 ]\"\"\" 2 \\ 4 / 3 \"\"\"n1 = len(preorder1) if (not canRepresentBST(preorder1, n1)): print(\"preorder1 can represent BST\");else: print(\"preorder1 can not represent BST :(\") preorder2 = [ 5, 3, 4, 1, 6, 10 ]n2 = len(preorder2)\"\"\" 5 / \\ 3 1 \\ / \\ 4 6 10 \"\"\"if (canRepresentBST(preorder2, n2)): print(\"preorder2 can represent BST\")else: print(\"preorder2 can not represent BST :(\") preorder3 = [ 5, 3, 4, 8, 6, 10 ]n3 = len(preorder3)\"\"\" 5 / \\ 3 8 \\ / \\ 4 6 10\"\"\"if (not canRepresentBST(preorder3, n3)): print(\"preorder3 can represent BST\")else: print(\"preorder3 can not represent BST :(\")", "e": 42324, "s": 40743, "text": null }, { "code": "// C# program to illustrate if a given array can represent// a preorder traversal of a BST or notusing System;class GFG { static int preIndex = 0; // We are actually not building the tree static void buildBST_helper(int n, int[] pre, int min, int max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(n, pre, min, rootData); // build right subtree buildBST_helper(n, pre, rootData, max); } // else // return NULL; } static bool canRepresentBST(int[] arr, int N) { // code here int min = Int32.MinValue, max = Int32.MaxValue; buildBST_helper(N, arr, min, max); return preIndex == N; } static void Main() { int[] preorder1 = { 2, 4, 3 }; /* 2 \\ 4 / 3 */ int n1 = preorder1.Length; Console.WriteLine(); if (canRepresentBST(preorder1, n1)) Console.Write(\"preorder1 can represent BST\"); else Console.Write(\"preorder1 can not represent BST :(\"); int[] preorder2 = { 5, 3, 4, 1, 6, 10 }; int n2 = preorder2.Length; Console.WriteLine(); /* 5 / \\ 3 1 \\ / \\ 4 6 10 */ if (!canRepresentBST(preorder2, n2)) Console.Write(\"preorder2 can represent BST\"); else Console.Write(\"preorder2 can not represent BST :(\"); int[] preorder3 = { 5, 3, 4, 8, 6, 10 }; int n3 = preorder3.Length; Console.WriteLine(); /* 5 / \\ 3 8 \\ / \\ 4 6 10 */ if (canRepresentBST(preorder3, n3)) Console.Write(\"preorder3 can represent BST\"); else Console.Write(\"preorder3 can not represent BST :(\"); }} // This code is contributed by rameshtravel07.", "e": 44372, "s": 42324, "text": null }, { "code": "<script> // Javascript program to illustrate if a given array can represent // a preorder traversal of a BST or not let preIndex = 0; // We are actually not building the tree function buildBST_helper(n, pre, min, max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node let rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(n, pre, min, rootData); // build right subtree buildBST_helper(n, pre, rootData, max); } // else // return NULL; } function canRepresentBST(arr, N) { // code here let min = Number.MIN_VALUE, max = Number.MAX_VALUE; buildBST_helper(N, arr, min, max); return preIndex == N; } let preorder1 = [ 2, 4, 3 ]; /* 2 \\ 4 / 3 */ let n1 = preorder1.length; if (canRepresentBST(preorder1, n1)) document.write(\"</br>\" + \"preorder1 can represent BST\"); else document.write(\"</br>\" + \"preorder1 can not represent BST :(\"); let preorder2 = [ 5, 3, 4, 1, 6, 10 ]; let n2 = preorder2.length; /* 5 / \\ 3 1 \\ / \\ 4 6 10 */ if (!canRepresentBST(preorder2, n2)) document.write(\"</br>\" + \"preorder2 can represent BST\"); else document.write(\"</br>\" + \"preorder2 can not represent BST :(\"); let preorder3 = [ 5, 3, 4, 8, 6, 10 ]; let n3 = preorder3.length; /* 5 / \\ 3 8 \\ / \\ 4 6 10 */ if (canRepresentBST(preorder3, n3)) document.write(\"</br>\" + \"preorder3 can represent BST\"); else document.write(\"</br>\" + \"preorder3 can not represent BST :(\"); // This code is contributed by decode2207.</script>", "e": 46399, "s": 44372, "text": null }, { "code": null, "e": 46491, "s": 46399, "text": "preorder1 can represent BST\npreorder2 can not represent BST :(\npreorder3 can represent BST" }, { "code": null, "e": 46568, "s": 46491, "text": "Time complexity: O(N)Auxiliary Space: O(height of the possible binary tree) " }, { "code": null, "e": 47446, "s": 46570, "text": "YouTubeGeeksforGeeks507K subscribersCheck if a given array can represent Preorder Traversal of Binary Search Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:11•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fH3XUXdinCs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 47617, "s": 47446, "text": "This article is contributed by Romil Punetha. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 47629, "s": 47617, "text": "shrikanth13" }, { "code": null, "e": 47640, "s": 47629, "text": "DimpleSama" }, { "code": null, "e": 47655, "s": 47640, "text": "auspicious_boy" }, { "code": null, "e": 47667, "s": 47655, "text": "importantly" }, { "code": null, "e": 47679, "s": 47667, "text": "sourashis69" }, { "code": null, "e": 47690, "s": 47679, "text": "decode2207" }, { "code": null, "e": 47708, "s": 47690, "text": "divyeshrabadiya07" }, { "code": null, "e": 47723, "s": 47708, "text": "rameshtravel07" }, { "code": null, "e": 47732, "s": 47723, "text": "mukesh07" }, { "code": null, "e": 47748, "s": 47732, "text": "amartyaghoshgfg" }, { "code": null, "e": 47754, "s": 47748, "text": "Adobe" }, { "code": null, "e": 47761, "s": 47754, "text": "Amazon" }, { "code": null, "e": 47770, "s": 47761, "text": "Linkedin" }, { "code": null, "e": 47789, "s": 47770, "text": "Binary Search Tree" }, { "code": null, "e": 47795, "s": 47789, "text": "Stack" }, { "code": null, "e": 47800, "s": 47795, "text": "Tree" }, { "code": null, "e": 47807, "s": 47800, "text": "Amazon" }, { "code": null, "e": 47813, "s": 47807, "text": "Adobe" }, { "code": null, "e": 47822, "s": 47813, "text": "Linkedin" }, { "code": null, "e": 47828, "s": 47822, "text": "Stack" }, { "code": null, "e": 47847, "s": 47828, "text": "Binary Search Tree" }, { "code": null, "e": 47852, "s": 47847, "text": "Tree" }, { "code": null, "e": 47950, "s": 47852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47982, "s": 47950, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 48017, "s": 47982, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 48074, "s": 48017, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 48108, "s": 48074, "text": "Advantages of BST over Hash Table" }, { "code": null, "e": 48162, "s": 48108, "text": "Difference between Binary Tree and Binary Search Tree" }, { "code": null, "e": 48210, "s": 48162, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 48230, "s": 48210, "text": "Stack Class in Java" }, { "code": null, "e": 48246, "s": 48230, "text": "Stack in Python" }, { "code": null, "e": 48321, "s": 48246, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Difference between AI and Soft Computing - GeeksforGeeks
25 Mar, 2020 Artificial Intelligence:AI manages more comprehensive issues of automating a system. This computerization should be possible by utilizing any field such as image processing, cognitive science, neural systems, machine learning etc. AI manages the making of machines, frameworks and different gadgets savvy by enabling them to think and do errands as all people generally do. Soft Computing:Soft Computing could be a computing model evolved to resolve the non-linear issues that involve unsure, imprecise and approximate solutions of a tangle. These sorts of issues square measure thought of as real-life issues wherever the human-like intelligence is needed to resolve it. Difference between AI and Soft Computing: 1. Reasoning 2. Perception 3. Natural language processing 1. Fuzzy systems 2. Evolutionary computation 3. Artificial neural computing Difference Between Machine Learning Machine Learning 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 IPv4 and IPv6 Difference Between Method Overloading and Method Overriding in Java Difference between Process and Thread Difference between Clustered and Non-clustered index Naive Bayes Classifiers Linear Regression (Python Implementation) ML | Linear Regression Reinforcement learning Removing stop words with NLTK in Python
[ { "code": null, "e": 26167, "s": 26139, "text": "\n25 Mar, 2020" }, { "code": null, "e": 26541, "s": 26167, "text": "Artificial Intelligence:AI manages more comprehensive issues of automating a system. This computerization should be possible by utilizing any field such as image processing, cognitive science, neural systems, machine learning etc. AI manages the making of machines, frameworks and different gadgets savvy by enabling them to think and do errands as all people generally do." }, { "code": null, "e": 26839, "s": 26541, "text": "Soft Computing:Soft Computing could be a computing model evolved to resolve the non-linear issues that involve unsure, imprecise and approximate solutions of a tangle. These sorts of issues square measure thought of as real-life issues wherever the human-like intelligence is needed to resolve it." }, { "code": null, "e": 26881, "s": 26839, "text": "Difference between AI and Soft Computing:" }, { "code": null, "e": 26941, "s": 26881, "text": "1. Reasoning\n2. Perception\n3. Natural language processing " }, { "code": null, "e": 27019, "s": 26941, "text": "1. Fuzzy systems\n2. Evolutionary computation\n3. Artificial neural computing " }, { "code": null, "e": 27038, "s": 27019, "text": "Difference Between" }, { "code": null, "e": 27055, "s": 27038, "text": "Machine Learning" }, { "code": null, "e": 27072, "s": 27055, "text": "Machine Learning" }, { "code": null, "e": 27170, "s": 27072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27231, "s": 27170, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27265, "s": 27231, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27333, "s": 27265, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27371, "s": 27333, "text": "Difference between Process and Thread" }, { "code": null, "e": 27424, "s": 27371, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27448, "s": 27424, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 27490, "s": 27448, "text": "Linear Regression (Python Implementation)" }, { "code": null, "e": 27513, "s": 27490, "text": "ML | Linear Regression" }, { "code": null, "e": 27536, "s": 27513, "text": "Reinforcement learning" } ]
Animated modal using react, framer-motion & styled-components - GeeksforGeeks
12 Mar, 2021 In this article, we are going to learn how to create an animated modal using react, framer-motion & styled-components. Prerequisites: Knowledge of JavaScript (ES6).Arrow function (ES6)Ternary operatordocument.body.styleKnowledge of HTML/CSS.Basic knowledge of ReactJS.React useState Knowledge of JavaScript (ES6).Arrow function (ES6)Ternary operatordocument.body.style Arrow function (ES6) Ternary operator document.body.style Knowledge of HTML/CSS. Basic knowledge of ReactJS.React useState React useState Framer-motion: The components and attributes we are going to make use of in this tutorial. https://www.framer.com/api/motion/component/https://www.framer.com/api/motion/animate-presence/ https://www.framer.com/api/motion/component/ https://www.framer.com/api/motion/animate-presence/ Creating React Application And Installing Module : Step 1: Now, you will start a new project using create-react-app so open your terminal and type. npx create-react-app toggle-modal Step 2: After creating your project folder i.e. toggle-modal, move to it using the following command. cd toggle-modal Step 3: Add the npm packages you will need during the project. npm install framer-motion styled-components //For yarn yarn add framer-motion styled-components Step 5: Now open your newly created project with your favorite code editor, I am using Visual Studio Code and will recommend you to use the same. Open the src folder and delete the following files: logo.svgserviceWorker.jssetupTests.jsindex.cssApp.test.js (if any) logo.svg serviceWorker.js setupTests.js index.css App.test.js (if any) Create a file named Styles.js. Project structure: Your folder structure tree should look like this. Project structure Approach: We are going to create a Modal component with ‘showModal’ prop only to manage its state of visibility and animated using framer-motion AnimatePresence. AnimatePresence allows components to animate out when they’re removed from the React tree and to enable exit animations. To give spring animation to modal container we will use framer-motion spring animation with stiffness = 300. Content of modal is geeksforgeeks image which is also animated using framer-motion motion.div. React useState hook to manage the state of ‘showModal’ i.e. responsible to toggle the modal container. ‘displayModal’ utility function to set the ‘showModal’ value opposite of its last value to toggle modal. Event listener for document body so that on clicking outside or on the modal, ‘showModal’ is set to false and in turn modal is disappeared. ToggleBtn is also animated using framer-motion motion.button. Example: Styles.js import styled from "styled-components";import { motion } from "framer-motion"; export const ModalBox = styled(motion.div)` position: relative; z-index: 2; width: 400px; height: 200px; display: flex; justify-content: center; align-items: center; background: #fff;`; export const ModalContent = styled(motion.div)` padding: 5px;`; export const ModalContainer = styled.div` height: 100vh; background: #111; display: flex; flex-direction: column; align-items: center;`; export const ToggleBtn = styled(motion.button)` cursor: pointer; font-size: 20px; color: #fff; padding: 0.5rem 0.8rem; margin-top: 3rem; background: #3bb75e; text-decoration: none; border: none; border-radius: 50px;`; App.js import React, { useState } from "react";import { AnimatePresence } from "framer-motion";import { ToggleBtn, ModalBox, ModalContent, ModalContainer } from "./Styles";import "./App.css"; // Modal component with 'showModal' prop only// to manage its state of visibility and// animated using framer-motionconst Modal = ({ showModal }) => { return ( <ModalContainer> <AnimatePresence> {showModal && ( <ModalBox initial={{ opacity: 0, y: 60, scale: 0.5 }} animate={{ opacity: 1, y: 0, scale: 1, // making use of framer-motion spring animation // with stiffness = 300 transition: { type: "spring", stiffness: 300 } }} exit={{ opacity: 0, scale: 0.5, transition: { duration: 0.6 } }}> <ModalContent initial={{ y: -30, opacity: 0 }} animate={{ y: 0, opacity: 1, transition: { delay: 0.5 } }}> {/* Modal content is geeksforgeeks image */} <img src="Modal image link" alt="geeksforgeeks" /> </ModalContent> </ModalBox> )} </AnimatePresence> </ModalContainer> );}; const App = () => { // React useState hook to manage the state of 'showModal' // i.e. responsible to toggle the modal container const [showModal, setShowModal] = useState(false); // utility function to set the showModal value // opposite of its last value // to toggle modal const displayModal = () => { setShowModal(!showModal); document.getElementById("btn").style.visibility = "hidden"; }; // event listener for document body // so that on clicking outside the modal, // 'showModal' is set to false. document.body.addEventListener("click", () => { if (showModal) { setShowModal(false); } }); return ( <ModalContainer> <ToggleBtn id="btn" initial={{ x: -700 }} animate={{ x: 0, transition: { duration: 0.1 } }} // event listener for the toggle button // to display modal on click onClick={displayModal}> Toggle Modal </ToggleBtn> {/* passing 'showModal' as a prop to Modal component */} <Modal showModal={showModal} /> </ModalContainer> );}; export default App; index.js import React from "react";import ReactDOM from "react-dom";import App from "./App"; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById("root")); App.css * { margin: 0; box-sizing: border-box;} img { padding: 5px; width: 400px; overflow: hidden;} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Framer-motion React-Questions Styled-components ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n12 Mar, 2021" }, { "code": null, "e": 26190, "s": 26071, "text": "In this article, we are going to learn how to create an animated modal using react, framer-motion & styled-components." }, { "code": null, "e": 26205, "s": 26190, "text": "Prerequisites:" }, { "code": null, "e": 26354, "s": 26205, "text": "Knowledge of JavaScript (ES6).Arrow function (ES6)Ternary operatordocument.body.styleKnowledge of HTML/CSS.Basic knowledge of ReactJS.React useState" }, { "code": null, "e": 26440, "s": 26354, "text": "Knowledge of JavaScript (ES6).Arrow function (ES6)Ternary operatordocument.body.style" }, { "code": null, "e": 26461, "s": 26440, "text": "Arrow function (ES6)" }, { "code": null, "e": 26478, "s": 26461, "text": "Ternary operator" }, { "code": null, "e": 26498, "s": 26478, "text": "document.body.style" }, { "code": null, "e": 26521, "s": 26498, "text": "Knowledge of HTML/CSS." }, { "code": null, "e": 26563, "s": 26521, "text": "Basic knowledge of ReactJS.React useState" }, { "code": null, "e": 26578, "s": 26563, "text": "React useState" }, { "code": null, "e": 26669, "s": 26578, "text": "Framer-motion: The components and attributes we are going to make use of in this tutorial." }, { "code": null, "e": 26765, "s": 26669, "text": "https://www.framer.com/api/motion/component/https://www.framer.com/api/motion/animate-presence/" }, { "code": null, "e": 26810, "s": 26765, "text": "https://www.framer.com/api/motion/component/" }, { "code": null, "e": 26862, "s": 26810, "text": "https://www.framer.com/api/motion/animate-presence/" }, { "code": null, "e": 26913, "s": 26862, "text": "Creating React Application And Installing Module :" }, { "code": null, "e": 27010, "s": 26913, "text": "Step 1: Now, you will start a new project using create-react-app so open your terminal and type." }, { "code": null, "e": 27044, "s": 27010, "text": "npx create-react-app toggle-modal" }, { "code": null, "e": 27146, "s": 27044, "text": "Step 2: After creating your project folder i.e. toggle-modal, move to it using the following command." }, { "code": null, "e": 27162, "s": 27146, "text": "cd toggle-modal" }, { "code": null, "e": 27225, "s": 27162, "text": "Step 3: Add the npm packages you will need during the project." }, { "code": null, "e": 27321, "s": 27225, "text": "npm install framer-motion styled-components\n//For yarn\nyarn add framer-motion styled-components" }, { "code": null, "e": 27467, "s": 27321, "text": "Step 5: Now open your newly created project with your favorite code editor, I am using Visual Studio Code and will recommend you to use the same." }, { "code": null, "e": 27519, "s": 27467, "text": "Open the src folder and delete the following files:" }, { "code": null, "e": 27586, "s": 27519, "text": "logo.svgserviceWorker.jssetupTests.jsindex.cssApp.test.js (if any)" }, { "code": null, "e": 27595, "s": 27586, "text": "logo.svg" }, { "code": null, "e": 27612, "s": 27595, "text": "serviceWorker.js" }, { "code": null, "e": 27626, "s": 27612, "text": "setupTests.js" }, { "code": null, "e": 27636, "s": 27626, "text": "index.css" }, { "code": null, "e": 27657, "s": 27636, "text": "App.test.js (if any)" }, { "code": null, "e": 27688, "s": 27657, "text": "Create a file named Styles.js." }, { "code": null, "e": 27757, "s": 27688, "text": "Project structure: Your folder structure tree should look like this." }, { "code": null, "e": 27775, "s": 27757, "text": "Project structure" }, { "code": null, "e": 27785, "s": 27775, "text": "Approach:" }, { "code": null, "e": 27937, "s": 27785, "text": "We are going to create a Modal component with ‘showModal’ prop only to manage its state of visibility and animated using framer-motion AnimatePresence." }, { "code": null, "e": 28058, "s": 27937, "text": "AnimatePresence allows components to animate out when they’re removed from the React tree and to enable exit animations." }, { "code": null, "e": 28167, "s": 28058, "text": "To give spring animation to modal container we will use framer-motion spring animation with stiffness = 300." }, { "code": null, "e": 28262, "s": 28167, "text": "Content of modal is geeksforgeeks image which is also animated using framer-motion motion.div." }, { "code": null, "e": 28365, "s": 28262, "text": "React useState hook to manage the state of ‘showModal’ i.e. responsible to toggle the modal container." }, { "code": null, "e": 28470, "s": 28365, "text": "‘displayModal’ utility function to set the ‘showModal’ value opposite of its last value to toggle modal." }, { "code": null, "e": 28610, "s": 28470, "text": "Event listener for document body so that on clicking outside or on the modal, ‘showModal’ is set to false and in turn modal is disappeared." }, { "code": null, "e": 28672, "s": 28610, "text": "ToggleBtn is also animated using framer-motion motion.button." }, { "code": null, "e": 28681, "s": 28672, "text": "Example:" }, { "code": null, "e": 28691, "s": 28681, "text": "Styles.js" }, { "code": "import styled from \"styled-components\";import { motion } from \"framer-motion\"; export const ModalBox = styled(motion.div)` position: relative; z-index: 2; width: 400px; height: 200px; display: flex; justify-content: center; align-items: center; background: #fff;`; export const ModalContent = styled(motion.div)` padding: 5px;`; export const ModalContainer = styled.div` height: 100vh; background: #111; display: flex; flex-direction: column; align-items: center;`; export const ToggleBtn = styled(motion.button)` cursor: pointer; font-size: 20px; color: #fff; padding: 0.5rem 0.8rem; margin-top: 3rem; background: #3bb75e; text-decoration: none; border: none; border-radius: 50px;`;", "e": 29402, "s": 28691, "text": null }, { "code": null, "e": 29409, "s": 29402, "text": "App.js" }, { "code": "import React, { useState } from \"react\";import { AnimatePresence } from \"framer-motion\";import { ToggleBtn, ModalBox, ModalContent, ModalContainer } from \"./Styles\";import \"./App.css\"; // Modal component with 'showModal' prop only// to manage its state of visibility and// animated using framer-motionconst Modal = ({ showModal }) => { return ( <ModalContainer> <AnimatePresence> {showModal && ( <ModalBox initial={{ opacity: 0, y: 60, scale: 0.5 }} animate={{ opacity: 1, y: 0, scale: 1, // making use of framer-motion spring animation // with stiffness = 300 transition: { type: \"spring\", stiffness: 300 } }} exit={{ opacity: 0, scale: 0.5, transition: { duration: 0.6 } }}> <ModalContent initial={{ y: -30, opacity: 0 }} animate={{ y: 0, opacity: 1, transition: { delay: 0.5 } }}> {/* Modal content is geeksforgeeks image */} <img src=\"Modal image link\" alt=\"geeksforgeeks\" /> </ModalContent> </ModalBox> )} </AnimatePresence> </ModalContainer> );}; const App = () => { // React useState hook to manage the state of 'showModal' // i.e. responsible to toggle the modal container const [showModal, setShowModal] = useState(false); // utility function to set the showModal value // opposite of its last value // to toggle modal const displayModal = () => { setShowModal(!showModal); document.getElementById(\"btn\").style.visibility = \"hidden\"; }; // event listener for document body // so that on clicking outside the modal, // 'showModal' is set to false. document.body.addEventListener(\"click\", () => { if (showModal) { setShowModal(false); } }); return ( <ModalContainer> <ToggleBtn id=\"btn\" initial={{ x: -700 }} animate={{ x: 0, transition: { duration: 0.1 } }} // event listener for the toggle button // to display modal on click onClick={displayModal}> Toggle Modal </ToggleBtn> {/* passing 'showModal' as a prop to Modal component */} <Modal showModal={showModal} /> </ModalContainer> );}; export default App;", "e": 31852, "s": 29409, "text": null }, { "code": null, "e": 31861, "s": 31852, "text": "index.js" }, { "code": "import React from \"react\";import ReactDOM from \"react-dom\";import App from \"./App\"; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById(\"root\"));", "e": 32051, "s": 31861, "text": null }, { "code": null, "e": 32059, "s": 32051, "text": "App.css" }, { "code": "* { margin: 0; box-sizing: border-box;} img { padding: 5px; width: 400px; overflow: hidden;}", "e": 32158, "s": 32059, "text": null }, { "code": null, "e": 32271, "s": 32158, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 32281, "s": 32271, "text": "npm start" }, { "code": null, "e": 32380, "s": 32281, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 32394, "s": 32380, "text": "Framer-motion" }, { "code": null, "e": 32410, "s": 32394, "text": "React-Questions" }, { "code": null, "e": 32428, "s": 32410, "text": "Styled-components" }, { "code": null, "e": 32436, "s": 32428, "text": "ReactJS" }, { "code": null, "e": 32453, "s": 32436, "text": "Web Technologies" }, { "code": null, "e": 32551, "s": 32453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32578, "s": 32551, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 32620, "s": 32578, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 32658, "s": 32620, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 32693, "s": 32658, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 32751, "s": 32693, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 32791, "s": 32751, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32824, "s": 32791, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32869, "s": 32824, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32931, "s": 32869, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Python - Extract selective keys' values Including Nested Keys - GeeksforGeeks
04 Jan, 2022 Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys’ values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys’ values. Let’s discuss certain way in which this task can be solved. Input : test_dict = {‘gfg’: {‘geeks’: {‘best’ : 3}}} key_list = [‘best’, ‘geeks’] Output : {‘geeks’: {‘best’: 3}, ‘best’: 3}Input : test_dict = {‘gfg’: {‘geek’: {‘good’ : 3}}} key_list = [‘best’, ‘geeks’] Output : {} Method : Using recursion + loop + yield The combination of above functionalities can be used to solve this problem. In this, we perform the task of checking for key using conditional statements and check for nestings using recursion. The yield operator is used to dynamically return the key for assignment as it occurs. Python3 # Python3 code to demonstrate working of# Extract selective keys' values [ Including Nested Keys ]# Using recursion + loop + yield def get_vals(test_dict, key_list): for i, j in test_dict.items(): if i in key_list: yield (i, j) yield from [] if not isinstance(j, dict) else get_vals(j, key_list) # initializing dictionarytest_dict = {'gfg': {'is': {'best' : 3}}, 'for': {'all' : 4}, 'geeks': 5} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing keys listkey_list = ['best', 'geeks'] # Extract selective keys' values [ Including Nested Keys ]# Using recursion + loop + yieldres = dict(get_vals(test_dict, key_list)) # printing resultprint("The extracted values : " + str(res)) The original dictionary is : {'gfg': {'is': {'best': 3}}, 'for': {'all': 4}, 'geeks': 5} The extracted values : {'best': 3, 'geeks': 5} nnr223442 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25837, "s": 25809, "text": "\n04 Jan, 2022" }, { "code": null, "e": 26225, "s": 25837, "text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys’ values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys’ values. Let’s discuss certain way in which this task can be solved. " }, { "code": null, "e": 26444, "s": 26225, "text": "Input : test_dict = {‘gfg’: {‘geeks’: {‘best’ : 3}}} key_list = [‘best’, ‘geeks’] Output : {‘geeks’: {‘best’: 3}, ‘best’: 3}Input : test_dict = {‘gfg’: {‘geek’: {‘good’ : 3}}} key_list = [‘best’, ‘geeks’] Output : {} " }, { "code": null, "e": 26765, "s": 26444, "text": "Method : Using recursion + loop + yield The combination of above functionalities can be used to solve this problem. In this, we perform the task of checking for key using conditional statements and check for nestings using recursion. The yield operator is used to dynamically return the key for assignment as it occurs. " }, { "code": null, "e": 26773, "s": 26765, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Extract selective keys' values [ Including Nested Keys ]# Using recursion + loop + yield def get_vals(test_dict, key_list): for i, j in test_dict.items(): if i in key_list: yield (i, j) yield from [] if not isinstance(j, dict) else get_vals(j, key_list) # initializing dictionarytest_dict = {'gfg': {'is': {'best' : 3}}, 'for': {'all' : 4}, 'geeks': 5} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing keys listkey_list = ['best', 'geeks'] # Extract selective keys' values [ Including Nested Keys ]# Using recursion + loop + yieldres = dict(get_vals(test_dict, key_list)) # printing resultprint(\"The extracted values : \" + str(res))", "e": 27517, "s": 26773, "text": null }, { "code": null, "e": 27653, "s": 27517, "text": "The original dictionary is : {'gfg': {'is': {'best': 3}}, 'for': {'all': 4}, 'geeks': 5}\nThe extracted values : {'best': 3, 'geeks': 5}" }, { "code": null, "e": 27665, "s": 27655, "text": "nnr223442" }, { "code": null, "e": 27692, "s": 27665, "text": "Python dictionary-programs" }, { "code": null, "e": 27699, "s": 27692, "text": "Python" }, { "code": null, "e": 27715, "s": 27699, "text": "Python Programs" }, { "code": null, "e": 27813, "s": 27715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27831, "s": 27813, "text": "Python Dictionary" }, { "code": null, "e": 27866, "s": 27831, "text": "Read a file line by line in Python" }, { "code": null, "e": 27898, "s": 27866, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27920, "s": 27898, "text": "Enumerate() in Python" }, { "code": null, "e": 27962, "s": 27920, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28005, "s": 27962, "text": "Python program to convert a list to string" }, { "code": null, "e": 28027, "s": 28005, "text": "Defaultdict in Python" }, { "code": null, "e": 28073, "s": 28027, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28111, "s": 28073, "text": "Python | Convert a list to dictionary" } ]
JQuery | Set the value of an input text field - GeeksforGeeks
03 Aug, 2021 There is a Input Element, the task is to set its value using JQuery. Here are a few examples discussed.To understand example first few methods to know.JQuery val() method:This method return/set the value attribute of selected elements.If we use this method to return value, it will return the value of the FIRST selected element.If we use this method to set value, it will set one or more than one value attribute for set of selected elements.Syntax: Return the value attribute:$(selector).val() $(selector).val() Set the value attribute:$(selector).val(value) $(selector).val(value) Set the value attribute using function:$(selector).val(function(index, curValue)) $(selector).val(function(index, curValue)) Parameters: value:This parameter is required. It specifies the value of value attribute. function(index, currentValue):This parameter is optional. It specifies the function that returns the value to set.index: It returns the position of index of element in set.currentValue: It returns the current value attribute of the selected elements. index: It returns the position of index of element in set. currentValue: It returns the current value attribute of the selected elements. Example 1: In this example the value of the input element is set by val() method by selecting the input element from its ID. <!DOCTYPE HTML><html> <head> <title> JQuery | Set value of input text. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksForGeeks </h1> Input Box: <input id="input" type="text" class="Disable" value="" /> <br> <br> <button id="setText"> setText </button> <script> $("#setText").click(function(event) { $('#input').val("GeeksForGeeks"); }); </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example the value of the input element is set by val() method by selecting the input element from its parent element < body > and then selecting the < input > element. <!DOCTYPE HTML><html> <head> <title> JQuery | Set value of input text. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksForGeeks </h1> Input Box: <input id="input" type="text" class="Disable" value="" /> <br> <br> <button id="setText"> setText </button> <script> $("#setText").click( function(event) { $('body input').val( "GeeksForGeeks"); }); </script></body> </html> Output: Before clicking on the button: After clicking on the button: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Basics JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. jQuery | children() with Examples How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26602, "s": 26574, "text": "\n03 Aug, 2021" }, { "code": null, "e": 27053, "s": 26602, "text": "There is a Input Element, the task is to set its value using JQuery. Here are a few examples discussed.To understand example first few methods to know.JQuery val() method:This method return/set the value attribute of selected elements.If we use this method to return value, it will return the value of the FIRST selected element.If we use this method to set value, it will set one or more than one value attribute for set of selected elements.Syntax:" }, { "code": null, "e": 27099, "s": 27053, "text": "Return the value attribute:$(selector).val()\n" }, { "code": null, "e": 27118, "s": 27099, "text": "$(selector).val()\n" }, { "code": null, "e": 27166, "s": 27118, "text": "Set the value attribute:$(selector).val(value)\n" }, { "code": null, "e": 27190, "s": 27166, "text": "$(selector).val(value)\n" }, { "code": null, "e": 27273, "s": 27190, "text": "Set the value attribute using function:$(selector).val(function(index, curValue))\n" }, { "code": null, "e": 27317, "s": 27273, "text": "$(selector).val(function(index, curValue))\n" }, { "code": null, "e": 27329, "s": 27317, "text": "Parameters:" }, { "code": null, "e": 27406, "s": 27329, "text": "value:This parameter is required. It specifies the value of value attribute." }, { "code": null, "e": 27657, "s": 27406, "text": "function(index, currentValue):This parameter is optional. It specifies the function that returns the value to set.index: It returns the position of index of element in set.currentValue: It returns the current value attribute of the selected elements." }, { "code": null, "e": 27716, "s": 27657, "text": "index: It returns the position of index of element in set." }, { "code": null, "e": 27795, "s": 27716, "text": "currentValue: It returns the current value attribute of the selected elements." }, { "code": null, "e": 27920, "s": 27795, "text": "Example 1: In this example the value of the input element is set by val() method by selecting the input element from its ID." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Set value of input text. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksForGeeks </h1> Input Box: <input id=\"input\" type=\"text\" class=\"Disable\" value=\"\" /> <br> <br> <button id=\"setText\"> setText </button> <script> $(\"#setText\").click(function(event) { $('#input').val(\"GeeksForGeeks\"); }); </script></body> </html>", "e": 28544, "s": 27920, "text": null }, { "code": null, "e": 28552, "s": 28544, "text": "Output:" }, { "code": null, "e": 28583, "s": 28552, "text": "Before clicking on the button:" }, { "code": null, "e": 28613, "s": 28583, "text": "After clicking on the button:" }, { "code": null, "e": 28800, "s": 28613, "text": "Example 2: In this example the value of the input element is set by val() method by selecting the input element from its parent element < body > and then selecting the < input > element." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Set value of input text. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksForGeeks </h1> Input Box: <input id=\"input\" type=\"text\" class=\"Disable\" value=\"\" /> <br> <br> <button id=\"setText\"> setText </button> <script> $(\"#setText\").click( function(event) { $('body input').val( \"GeeksForGeeks\"); }); </script></body> </html>", "e": 29456, "s": 28800, "text": null }, { "code": null, "e": 29464, "s": 29456, "text": "Output:" }, { "code": null, "e": 29495, "s": 29464, "text": "Before clicking on the button:" }, { "code": null, "e": 29525, "s": 29495, "text": "After clicking on the button:" }, { "code": null, "e": 29793, "s": 29525, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 29807, "s": 29793, "text": "jQuery-Basics" }, { "code": null, "e": 29814, "s": 29807, "text": "JQuery" }, { "code": null, "e": 29831, "s": 29814, "text": "Web Technologies" }, { "code": null, "e": 29929, "s": 29831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29963, "s": 29929, "text": "jQuery | children() with Examples" }, { "code": null, "e": 30018, "s": 29963, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 30091, "s": 30018, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30114, "s": 30091, "text": "jQuery | ajax() Method" }, { "code": null, "e": 30150, "s": 30114, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 30190, "s": 30150, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30223, "s": 30190, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30268, "s": 30223, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30311, "s": 30268, "text": "How to fetch data from an API in ReactJS ?" } ]
insmod command in Linux with examples - GeeksforGeeks
22 May, 2019 insmod command in Linux systems is used to insert modules into the kernel. Linux is an Operating System which allows the user to load kernel modules on run time to extend the kernel functionalities. LKMs(Loadable Kernel Modules) are usually used to add support for new hardware (as device drivers) and/or filesystems, or for adding system calls. This command here inserts the kernel object file (.ko) into the kernel with/without arguments, along with a few additional options. Syntax: insmod [file name] [module-options...] Options: insmod command with help option: The insmod command throws an error if no options, filename or arguments are passed. So, when we use the -h option, it gives the general syntax along with the various options that can be used with the insmod command.insmod -h insmod -h insmod command with version option: This is used to view the version of the insmod command.insmod -V insmod -V Examples: insmod + file name: This command is used to insert the LKM file (.ko) into the Linux Kernel. The working directory is changed to the one with the LKM file, and then the command is executed. Root privilege is needed to run this instruction.Note: The LKM file used here is present in the desktop(which is the working directory), and doesn’t take any arguments, and prints a message to the system log. This message can be viewed by using the dmesg command.sudo insmod geeksforgeeks.ko Example: Note: The LKM file used here is present in the desktop(which is the working directory), and doesn’t take any arguments, and prints a message to the system log. This message can be viewed by using the dmesg command. sudo insmod geeksforgeeks.ko Example: insmod + file directory + file name: Like the previous command, insmod works when you specify the file directory along with the LKM file’s name. This is illustrated below.Example:sudo insmod /home/mukkesh/Desktop/geeksforgeeks.ko Example: sudo insmod /home/mukkesh/Desktop/geeksforgeeks.ko Passing parameters to the module using insmod: LKM files can have parameters/arguments passed to them through the insmod command. These arguments essentially act as inputs for the LKMs. Depending on how the LKM is written, the arguments are used.Note:The LKM used here takes the string parameter “user” and prints a message which includes the passed parameter.Example:sudo insmod geeks4geeks.ko user="Mukkesh" Note:The LKM used here takes the string parameter “user” and prints a message which includes the passed parameter. Example: sudo insmod geeks4geeks.ko user="Mukkesh" linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 26061, "s": 26033, "text": "\n22 May, 2019" }, { "code": null, "e": 26539, "s": 26061, "text": "insmod command in Linux systems is used to insert modules into the kernel. Linux is an Operating System which allows the user to load kernel modules on run time to extend the kernel functionalities. LKMs(Loadable Kernel Modules) are usually used to add support for new hardware (as device drivers) and/or filesystems, or for adding system calls. This command here inserts the kernel object file (.ko) into the kernel with/without arguments, along with a few additional options." }, { "code": null, "e": 26547, "s": 26539, "text": "Syntax:" }, { "code": null, "e": 26586, "s": 26547, "text": "insmod [file name] [module-options...]" }, { "code": null, "e": 26595, "s": 26586, "text": "Options:" }, { "code": null, "e": 26854, "s": 26595, "text": "insmod command with help option: The insmod command throws an error if no options, filename or arguments are passed. So, when we use the -h option, it gives the general syntax along with the various options that can be used with the insmod command.insmod -h\n" }, { "code": null, "e": 26865, "s": 26854, "text": "insmod -h\n" }, { "code": null, "e": 26967, "s": 26865, "text": "insmod command with version option: This is used to view the version of the insmod command.insmod -V\n" }, { "code": null, "e": 26978, "s": 26967, "text": "insmod -V\n" }, { "code": null, "e": 26988, "s": 26978, "text": "Examples:" }, { "code": null, "e": 27479, "s": 26988, "text": "insmod + file name: This command is used to insert the LKM file (.ko) into the Linux Kernel. The working directory is changed to the one with the LKM file, and then the command is executed. Root privilege is needed to run this instruction.Note: The LKM file used here is present in the desktop(which is the working directory), and doesn’t take any arguments, and prints a message to the system log. This message can be viewed by using the dmesg command.sudo insmod geeksforgeeks.ko\nExample:" }, { "code": null, "e": 27694, "s": 27479, "text": "Note: The LKM file used here is present in the desktop(which is the working directory), and doesn’t take any arguments, and prints a message to the system log. This message can be viewed by using the dmesg command." }, { "code": null, "e": 27724, "s": 27694, "text": "sudo insmod geeksforgeeks.ko\n" }, { "code": null, "e": 27733, "s": 27724, "text": "Example:" }, { "code": null, "e": 27964, "s": 27733, "text": "insmod + file directory + file name: Like the previous command, insmod works when you specify the file directory along with the LKM file’s name. This is illustrated below.Example:sudo insmod /home/mukkesh/Desktop/geeksforgeeks.ko\n" }, { "code": null, "e": 27973, "s": 27964, "text": "Example:" }, { "code": null, "e": 28025, "s": 27973, "text": "sudo insmod /home/mukkesh/Desktop/geeksforgeeks.ko\n" }, { "code": null, "e": 28436, "s": 28025, "text": "Passing parameters to the module using insmod: LKM files can have parameters/arguments passed to them through the insmod command. These arguments essentially act as inputs for the LKMs. Depending on how the LKM is written, the arguments are used.Note:The LKM used here takes the string parameter “user” and prints a message which includes the passed parameter.Example:sudo insmod geeks4geeks.ko user=\"Mukkesh\"\n" }, { "code": null, "e": 28551, "s": 28436, "text": "Note:The LKM used here takes the string parameter “user” and prints a message which includes the passed parameter." }, { "code": null, "e": 28560, "s": 28551, "text": "Example:" }, { "code": null, "e": 28603, "s": 28560, "text": "sudo insmod geeks4geeks.ko user=\"Mukkesh\"\n" }, { "code": null, "e": 28617, "s": 28603, "text": "linux-command" }, { "code": null, "e": 28639, "s": 28617, "text": "Linux-system-commands" }, { "code": null, "e": 28646, "s": 28639, "text": "Picked" }, { "code": null, "e": 28657, "s": 28646, "text": "Linux-Unix" }, { "code": null, "e": 28755, "s": 28657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28793, "s": 28755, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28828, "s": 28793, "text": "tar command in Linux with examples" }, { "code": null, "e": 28864, "s": 28828, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28902, "s": 28864, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28935, "s": 28902, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 28971, "s": 28935, "text": "diff command in Linux with examples" }, { "code": null, "e": 29009, "s": 28971, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 29045, "s": 29009, "text": "Tail command in Linux with examples" }, { "code": null, "e": 29080, "s": 29045, "text": "Cat command in Linux with examples" } ]
How to set title for action bar in android?
This example demonstrates How to set title for action bar in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken text view to show status bar tittle. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.app.ActivityManager; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); getSupportActionBar().setTitle("Home"); getSupportActionBar().setSubtitle("sairam"); textView.setText(" tittle is Home"); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1132, "s": 1062, "text": "This example demonstrates How to set title for action bar in android." }, { "code": null, "e": 1261, "s": 1132, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1326, "s": 1261, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1886, "s": 1326, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1956, "s": 1886, "text": "In the above code, we have taken text view to show status bar tittle." }, { "code": null, "e": 2013, "s": 1956, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2943, "s": 2013, "text": "package com.example.myapplication;\nimport android.app.ActivityManager;\nimport android.app.admin.DevicePolicyManager;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n getSupportActionBar().setTitle(\"Home\");\n getSupportActionBar().setSubtitle(\"sairam\");\n textView.setText(\" tittle is Home\");\n }\n}" }, { "code": null, "e": 3290, "s": 2943, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3330, "s": 3290, "text": "Click here to download the project code" } ]
Measure execution time of small Python code snippets (timeit)
The Timer class and other convenience functions in timeit module of Python's standard library are designed to provide a mechanism to measure time taken by small bits of Python code to execute. The module has a command line interface and the functions can be called from within program as well. Easiest way to measure time of execution is by using following convenience function This function returns object of Timer class. It mainly requires two parameters. stmt − a string containing valid Python statement whose execution time is to be measured. stmt − a string containing valid Python statement whose execution time is to be measured. setup − a string containing Python statement which will be executed once, primarily to initialize certain objects or variables. setup − a string containing Python statement which will be executed once, primarily to initialize certain objects or variables. Both strings may contains multiple statements separated by semi colon(;) or newlines, and both default to pass keyword. Another optional parameter number may be given which denotes number of executions of 'stmt' In following example time required to perform thousand times the cumulative addition of numbers in a range 0-100 is measured. import timeit setupcode = "s = 0" function = ''' for x in range(100): s = s + x ''' print (timeit.timeit(setup = setupcode, stmt = function, number = 1000)) Here a string contains a for loop within which numbers within range 0-100 are added. This string is the stmt parameter. For addition, the initialization of a variable is done by a setupcode string. The timeit() function calculates the time required in seconds. Output 0.03055878530880241 The same result can be obtained by first creating a Timer object and then execute timeit() method on it. The Timer class also has a repeat() method to call timeit() repeatedly. It returns a list of all calls. An object oriented version of the above code is as follows − import timeit setupcode = "s = 0" function = ''' for x in range(100): s = s + x ''' t = timeit.Timer(setup = setupcode, stmt = function) print (t.timeit(number = 1000)) print ('calling repeat() :',t.repeat(3,1000)) Output 0.019971274194651528 calling repeat() : [0.023369810546474253, 0.020518432391765262, 0.02075439436427058] As mentioned earlier, timeit module has a command line interface. The module itself is imported using –m option in the command line for execution of Python script. Following command line options define various parameter line setup and executable code, repeat frequency, etc. Following is the command line equivalent of example code used earlier − C:\Users\acer>python -m timeit -s "s = 0" "for x in range(100): s = s + x" 10000 loops, best of 3: 22.4 usec per loop
[ { "code": null, "e": 1356, "s": 1062, "text": "The Timer class and other convenience functions in timeit module of Python's standard library are designed to provide a mechanism to measure time taken by small bits of Python code to execute. The module has a command line interface and the functions can be called from within program as well." }, { "code": null, "e": 1440, "s": 1356, "text": "Easiest way to measure time of execution is by using following convenience function" }, { "code": null, "e": 1520, "s": 1440, "text": "This function returns object of Timer class. It mainly requires two parameters." }, { "code": null, "e": 1610, "s": 1520, "text": "stmt − a string containing valid Python statement whose execution time is to be measured." }, { "code": null, "e": 1700, "s": 1610, "text": "stmt − a string containing valid Python statement whose execution time is to be measured." }, { "code": null, "e": 1828, "s": 1700, "text": "setup − a string containing Python statement which will be executed once, primarily to initialize certain objects or variables." }, { "code": null, "e": 1956, "s": 1828, "text": "setup − a string containing Python statement which will be executed once, primarily to initialize certain objects or variables." }, { "code": null, "e": 2168, "s": 1956, "text": "Both strings may contains multiple statements separated by semi colon(;) or newlines, and both default to pass keyword. Another optional parameter number may be given which denotes number of executions of 'stmt'" }, { "code": null, "e": 2294, "s": 2168, "text": "In following example time required to perform thousand times the cumulative addition of numbers in a range 0-100 is measured." }, { "code": null, "e": 2451, "s": 2294, "text": "import timeit\nsetupcode = \"s = 0\"\nfunction = '''\nfor x in range(100):\ns = s + x\n'''\nprint (timeit.timeit(setup = setupcode, stmt = function, number = 1000))" }, { "code": null, "e": 2712, "s": 2451, "text": "Here a string contains a for loop within which numbers within range 0-100 are added. This string is the stmt parameter. For addition, the initialization of a variable is done by a setupcode string. The timeit() function calculates the time required in seconds." }, { "code": null, "e": 2719, "s": 2712, "text": "Output" }, { "code": null, "e": 2739, "s": 2719, "text": "0.03055878530880241" }, { "code": null, "e": 2844, "s": 2739, "text": "The same result can be obtained by first creating a Timer object and then execute timeit() method on it." }, { "code": null, "e": 2948, "s": 2844, "text": "The Timer class also has a repeat() method to call timeit() repeatedly. It returns a list of all calls." }, { "code": null, "e": 3009, "s": 2948, "text": "An object oriented version of the above code is as follows −" }, { "code": null, "e": 3224, "s": 3009, "text": "import timeit\nsetupcode = \"s = 0\"\nfunction = '''\nfor x in range(100):\ns = s + x\n'''\nt = timeit.Timer(setup = setupcode, stmt = function)\nprint (t.timeit(number = 1000))\nprint ('calling repeat() :',t.repeat(3,1000))" }, { "code": null, "e": 3231, "s": 3224, "text": "Output" }, { "code": null, "e": 3337, "s": 3231, "text": "0.019971274194651528\ncalling repeat() : [0.023369810546474253, 0.020518432391765262, 0.02075439436427058]" }, { "code": null, "e": 3612, "s": 3337, "text": "As mentioned earlier, timeit module has a command line interface. The module itself is imported using –m option in the command line for execution of Python script. Following command line options define various parameter line setup and executable code, repeat frequency, etc." }, { "code": null, "e": 3684, "s": 3612, "text": "Following is the command line equivalent of example code used earlier −" }, { "code": null, "e": 3802, "s": 3684, "text": "C:\\Users\\acer>python -m timeit -s \"s = 0\" \"for x in range(100): s = s + x\"\n10000 loops, best of 3: 22.4 usec per loop" } ]
A Practitioner’s Guide To Interrupted Time Series | by Leihua Ye, PhD | Towards Data Science
In the world of causal inference, Randomized Controlled Trials, RCTs, are considered the gold standard as it rules out any covariate differences before the intervention. However, running a RCT isn’t an option for multiple reasons (e.g., too expensive, invalid assumptions, too long, not ethical, etc.). Under these circumstances, Interrupted Time Series (ITS) design comes in handy (see Netflix). Aa a quasi-experimental method, ITS contains a strong inferential power and has wide applications in epidemiology, medication research, and program evaluations in general. Arguably, ITS is the strongest quasi-experimental method in causal inference (Penfold and Zhang, 2013). In this post, we will learn the basics of the method and how to apply it in real life. As a quasi-experimental design, ITS is an analysis of a single time-series data before and after the intervention (Bernal, et al. 2017). From the perspective of research design, ITS builds upon a rather straightforward design idea: the outcome variable would not be altered if there were no intervention. However, the tricky part is: how we can derive causal argumentation from a single time series data? how can we eliminate confounders? In other words, it is crucial to create “counterfactuals” that serve as the baseline point. We can attribute the “altered” trajectory to the presence of the intervention. Fortunately, there is a time component with ITS, as the name suggests, that allows us to assume the outcome variable would not change if the intervention were not present. Besides, we could examine whether the outcome variable returns to the baseline after taking away the treatment condition, if there are multiple data entries (see Netflix for examples). Furthermore, we must control for time-varying confounders, including seasonable trends and concurrent events that may interfere with the results. For example, researchers challenge and repudiate the prior findings that the Great Recession in 2008 leads to more suicides in the U.S., arguing the previous studies fail to consider seasonality and social groupings (Harper and Bruckner). Penfold and Zhang (2013) have provided a complete list of the strengths and limitations, and I’m going to summarize the key points in the following. To control for long-term time trends in the data. ITS presents a long-term analytical framework with more extended periods, which better explain any data trends.To account for individual-level bias and to evaluate the outcome variable at the population level. Individual-level data may introduce bias, but not with population data. Honestly, this is both a blessing and a curse. We will elaborate more on the latter aspect in the following part.To evaluate both intended and unintended consequences of interventions. We can easily enlarge analysis and incorporate more outcome variables with minimum or no adaptations.To conduct stratified analyses of subpopulations of individuals and to derive different causal effects. This is critical. We can divide the total population into different sub-groups according to various criteria and examine how each sub-group may behave differently. Social groups are different, and grouping them together may dilute or hide critical information, as positive and negative effects mix together and cancel out (see Harper and Bruckner for examples).To provide clear and interpretable visual results. Visual inspections are always welcome and should be treated seriously (See my other post for more explanations). To control for long-term time trends in the data. ITS presents a long-term analytical framework with more extended periods, which better explain any data trends. To account for individual-level bias and to evaluate the outcome variable at the population level. Individual-level data may introduce bias, but not with population data. Honestly, this is both a blessing and a curse. We will elaborate more on the latter aspect in the following part. To evaluate both intended and unintended consequences of interventions. We can easily enlarge analysis and incorporate more outcome variables with minimum or no adaptations. To conduct stratified analyses of subpopulations of individuals and to derive different causal effects. This is critical. We can divide the total population into different sub-groups according to various criteria and examine how each sub-group may behave differently. Social groups are different, and grouping them together may dilute or hide critical information, as positive and negative effects mix together and cancel out (see Harper and Bruckner for examples). To provide clear and interpretable visual results. Visual inspections are always welcome and should be treated seriously (See my other post for more explanations). Multiple rounds of data entries. A minimum of 8 periods before and 8 after an intervention to evaluate the changes. So, we need a total of 16 data entries, which may not be possible all the time. I think Penfold and Zhang (2013) are being cautious about the number of data entries. It’s still possible to apply ITS with few rounds of data entry. Just the causal power may not as robust as the one with multiple rounds.Time lag. It takes some unknown time for a program to achieve intended results, which makes it difficult to pinpoint the causal effects of several events that coincide. Let’s say the transportation department in the U.S. adopt three policies within a two-year timespan to curb highway speeding. Playing God, we somehow know it would take 1 yr for Policy A to have any effect, 1.5 ys for Policy B, and 3 yrs for Policy C. In the meantime, it becomes impossible to separate the intertwined effects using ITS.Inference Level. It’s population-level data, so we can’t make inferences about each individual. Multiple rounds of data entries. A minimum of 8 periods before and 8 after an intervention to evaluate the changes. So, we need a total of 16 data entries, which may not be possible all the time. I think Penfold and Zhang (2013) are being cautious about the number of data entries. It’s still possible to apply ITS with few rounds of data entry. Just the causal power may not as robust as the one with multiple rounds. Time lag. It takes some unknown time for a program to achieve intended results, which makes it difficult to pinpoint the causal effects of several events that coincide. Let’s say the transportation department in the U.S. adopt three policies within a two-year timespan to curb highway speeding. Playing God, we somehow know it would take 1 yr for Policy A to have any effect, 1.5 ys for Policy B, and 3 yrs for Policy C. In the meantime, it becomes impossible to separate the intertwined effects using ITS. Inference Level. It’s population-level data, so we can’t make inferences about each individual. ITS uses Segmented Regression to examine the effects of the intervention. ITS requires two segments: the one before the intervention and the one after the intervention. Each segment has its own slope and intercept, and we compare the two segmented regression models to derive the effects. We attribute any changes in the direction (e.g., from positive to negative) and/or the extent (from large effects to small effects) between these two segmented regression models to the intervention variable. Actually, this is how ITS overcomes the limitations of having only one case and still has a strong inferential power. Here is an example of ITS analyses using simulated data. # simulated data # data preparationset.seed(1)CaseID = rep(1:100,6)# interventionIntervention = c(rep(0,300), rep(1,300))Outcome_Variable = c(rnorm(300), abs(rnorm(300)*4))mydata = cbind(CaseID, Intervention, Outcome_Variable)mydata = as.data.frame(mydata)#construct a simple OLS modelmodel = lm(Outcome_Variable ~ Intervention, data = mydata)summary(model)Call:lm(formula = Outcome_Variable ~ Intervention, data = mydata)Residuals: Min 1Q Median 3Q Max -3.3050 -1.2315 -0.1734 0.8691 11.9185Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.03358 0.11021 0.305 0.761 Intervention 3.28903 0.15586 21.103 <2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 1.909 on 598 degrees of freedomMultiple R-squared: 0.4268, Adjusted R-squared: 0.4259 F-statistic: 445.3 on 1 and 598 DF, p-value: < 2.2e-16 As can be seen, the regression result of the intervention variable is statistically significant. This is a quick intro class to ITS using simulated data. Actually, ITS can do so much more in causal inference, and I’ll elaborate more in a follow-up post soon. Hopefully~~ Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees. leihua-ye.medium.com Please find me on LinkedIn and Youtube. Also, check my other posts on Artificial Intelligence and Machine Learning.
[ { "code": null, "e": 350, "s": 47, "text": "In the world of causal inference, Randomized Controlled Trials, RCTs, are considered the gold standard as it rules out any covariate differences before the intervention. However, running a RCT isn’t an option for multiple reasons (e.g., too expensive, invalid assumptions, too long, not ethical, etc.)." }, { "code": null, "e": 616, "s": 350, "text": "Under these circumstances, Interrupted Time Series (ITS) design comes in handy (see Netflix). Aa a quasi-experimental method, ITS contains a strong inferential power and has wide applications in epidemiology, medication research, and program evaluations in general." }, { "code": null, "e": 720, "s": 616, "text": "Arguably, ITS is the strongest quasi-experimental method in causal inference (Penfold and Zhang, 2013)." }, { "code": null, "e": 807, "s": 720, "text": "In this post, we will learn the basics of the method and how to apply it in real life." }, { "code": null, "e": 1112, "s": 807, "text": "As a quasi-experimental design, ITS is an analysis of a single time-series data before and after the intervention (Bernal, et al. 2017). From the perspective of research design, ITS builds upon a rather straightforward design idea: the outcome variable would not be altered if there were no intervention." }, { "code": null, "e": 1141, "s": 1112, "text": "However, the tricky part is:" }, { "code": null, "e": 1212, "s": 1141, "text": "how we can derive causal argumentation from a single time series data?" }, { "code": null, "e": 1246, "s": 1212, "text": "how can we eliminate confounders?" }, { "code": null, "e": 1417, "s": 1246, "text": "In other words, it is crucial to create “counterfactuals” that serve as the baseline point. We can attribute the “altered” trajectory to the presence of the intervention." }, { "code": null, "e": 1589, "s": 1417, "text": "Fortunately, there is a time component with ITS, as the name suggests, that allows us to assume the outcome variable would not change if the intervention were not present." }, { "code": null, "e": 1774, "s": 1589, "text": "Besides, we could examine whether the outcome variable returns to the baseline after taking away the treatment condition, if there are multiple data entries (see Netflix for examples)." }, { "code": null, "e": 1920, "s": 1774, "text": "Furthermore, we must control for time-varying confounders, including seasonable trends and concurrent events that may interfere with the results." }, { "code": null, "e": 2159, "s": 1920, "text": "For example, researchers challenge and repudiate the prior findings that the Great Recession in 2008 leads to more suicides in the U.S., arguing the previous studies fail to consider seasonality and social groupings (Harper and Bruckner)." }, { "code": null, "e": 2308, "s": 2159, "text": "Penfold and Zhang (2013) have provided a complete list of the strengths and limitations, and I’m going to summarize the key points in the following." }, { "code": null, "e": 3555, "s": 2308, "text": "To control for long-term time trends in the data. ITS presents a long-term analytical framework with more extended periods, which better explain any data trends.To account for individual-level bias and to evaluate the outcome variable at the population level. Individual-level data may introduce bias, but not with population data. Honestly, this is both a blessing and a curse. We will elaborate more on the latter aspect in the following part.To evaluate both intended and unintended consequences of interventions. We can easily enlarge analysis and incorporate more outcome variables with minimum or no adaptations.To conduct stratified analyses of subpopulations of individuals and to derive different causal effects. This is critical. We can divide the total population into different sub-groups according to various criteria and examine how each sub-group may behave differently. Social groups are different, and grouping them together may dilute or hide critical information, as positive and negative effects mix together and cancel out (see Harper and Bruckner for examples).To provide clear and interpretable visual results. Visual inspections are always welcome and should be treated seriously (See my other post for more explanations)." }, { "code": null, "e": 3717, "s": 3555, "text": "To control for long-term time trends in the data. ITS presents a long-term analytical framework with more extended periods, which better explain any data trends." }, { "code": null, "e": 4002, "s": 3717, "text": "To account for individual-level bias and to evaluate the outcome variable at the population level. Individual-level data may introduce bias, but not with population data. Honestly, this is both a blessing and a curse. We will elaborate more on the latter aspect in the following part." }, { "code": null, "e": 4176, "s": 4002, "text": "To evaluate both intended and unintended consequences of interventions. We can easily enlarge analysis and incorporate more outcome variables with minimum or no adaptations." }, { "code": null, "e": 4642, "s": 4176, "text": "To conduct stratified analyses of subpopulations of individuals and to derive different causal effects. This is critical. We can divide the total population into different sub-groups according to various criteria and examine how each sub-group may behave differently. Social groups are different, and grouping them together may dilute or hide critical information, as positive and negative effects mix together and cancel out (see Harper and Bruckner for examples)." }, { "code": null, "e": 4806, "s": 4642, "text": "To provide clear and interpretable visual results. Visual inspections are always welcome and should be treated seriously (See my other post for more explanations)." }, { "code": null, "e": 5826, "s": 4806, "text": "Multiple rounds of data entries. A minimum of 8 periods before and 8 after an intervention to evaluate the changes. So, we need a total of 16 data entries, which may not be possible all the time. I think Penfold and Zhang (2013) are being cautious about the number of data entries. It’s still possible to apply ITS with few rounds of data entry. Just the causal power may not as robust as the one with multiple rounds.Time lag. It takes some unknown time for a program to achieve intended results, which makes it difficult to pinpoint the causal effects of several events that coincide. Let’s say the transportation department in the U.S. adopt three policies within a two-year timespan to curb highway speeding. Playing God, we somehow know it would take 1 yr for Policy A to have any effect, 1.5 ys for Policy B, and 3 yrs for Policy C. In the meantime, it becomes impossible to separate the intertwined effects using ITS.Inference Level. It’s population-level data, so we can’t make inferences about each individual." }, { "code": null, "e": 6245, "s": 5826, "text": "Multiple rounds of data entries. A minimum of 8 periods before and 8 after an intervention to evaluate the changes. So, we need a total of 16 data entries, which may not be possible all the time. I think Penfold and Zhang (2013) are being cautious about the number of data entries. It’s still possible to apply ITS with few rounds of data entry. Just the causal power may not as robust as the one with multiple rounds." }, { "code": null, "e": 6752, "s": 6245, "text": "Time lag. It takes some unknown time for a program to achieve intended results, which makes it difficult to pinpoint the causal effects of several events that coincide. Let’s say the transportation department in the U.S. adopt three policies within a two-year timespan to curb highway speeding. Playing God, we somehow know it would take 1 yr for Policy A to have any effect, 1.5 ys for Policy B, and 3 yrs for Policy C. In the meantime, it becomes impossible to separate the intertwined effects using ITS." }, { "code": null, "e": 6848, "s": 6752, "text": "Inference Level. It’s population-level data, so we can’t make inferences about each individual." }, { "code": null, "e": 7137, "s": 6848, "text": "ITS uses Segmented Regression to examine the effects of the intervention. ITS requires two segments: the one before the intervention and the one after the intervention. Each segment has its own slope and intercept, and we compare the two segmented regression models to derive the effects." }, { "code": null, "e": 7345, "s": 7137, "text": "We attribute any changes in the direction (e.g., from positive to negative) and/or the extent (from large effects to small effects) between these two segmented regression models to the intervention variable." }, { "code": null, "e": 7463, "s": 7345, "text": "Actually, this is how ITS overcomes the limitations of having only one case and still has a strong inferential power." }, { "code": null, "e": 7520, "s": 7463, "text": "Here is an example of ITS analyses using simulated data." }, { "code": null, "e": 8437, "s": 7520, "text": "# simulated data # data preparationset.seed(1)CaseID = rep(1:100,6)# interventionIntervention = c(rep(0,300), rep(1,300))Outcome_Variable = c(rnorm(300), abs(rnorm(300)*4))mydata = cbind(CaseID, Intervention, Outcome_Variable)mydata = as.data.frame(mydata)#construct a simple OLS modelmodel = lm(Outcome_Variable ~ Intervention, data = mydata)summary(model)Call:lm(formula = Outcome_Variable ~ Intervention, data = mydata)Residuals: Min 1Q Median 3Q Max -3.3050 -1.2315 -0.1734 0.8691 11.9185Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.03358 0.11021 0.305 0.761 Intervention 3.28903 0.15586 21.103 <2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 1.909 on 598 degrees of freedomMultiple R-squared: 0.4268, Adjusted R-squared: 0.4259 F-statistic: 445.3 on 1 and 598 DF, p-value: < 2.2e-16" }, { "code": null, "e": 8534, "s": 8437, "text": "As can be seen, the regression result of the intervention variable is statistically significant." }, { "code": null, "e": 8708, "s": 8534, "text": "This is a quick intro class to ITS using simulated data. Actually, ITS can do so much more in causal inference, and I’ll elaborate more in a follow-up post soon. Hopefully~~" }, { "code": null, "e": 8920, "s": 8708, "text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees." }, { "code": null, "e": 8941, "s": 8920, "text": "leihua-ye.medium.com" }, { "code": null, "e": 8981, "s": 8941, "text": "Please find me on LinkedIn and Youtube." } ]
Python String isspace() Method - GeeksforGeeks
12 Aug, 2021 Python String isspace() is a built-in method used for string handling. The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as: ‘ ‘ – Space ‘\t’ – Horizontal tab ‘\n’ – Newline ‘\v’ – Vertical tab ‘\f’ – Feed ‘\r’ – Carriage return Syntax: string.isspace() Parameters: isspace() does not take any parameters Returns: True – If all characters in the string are whitespace characters.False – If the string contains 1 or more non-whitespace characters. True – If all characters in the string are whitespace characters. False – If the string contains 1 or more non-whitespace characters. Input : string = 'Geeksforgeeks' Output : False Input : string = '\n \n \n' Output : True Input : string = 'Geeks\nFor\nGeeks' Output : False Python3 # Python code for implementation of isspace() # checking for whitespace charactersstring = 'Geeksforgeeks' print(string.isspace()) # checking if \n is a whitespace characterstring = '\n \n \n' print(string.isspace()) string = 'Geeks\nfor\ngeeks'print( string.isspace()) Output: False True False Given a string in python, count the number of whitespace characters in the string. Input : string = 'My name is Ayush' Output : 3 Input : string = 'My name is \n\n\n\n\nAyush' Output : 8 Algorithm: Traverse the given string character by character up to its length, check if the character is a whitespace character. If it is a whitespace character, increment the counter by 1, else traverse to the next character. Print the value of the counter. Traverse the given string character by character up to its length, check if the character is a whitespace character. If it is a whitespace character, increment the counter by 1, else traverse to the next character. Print the value of the counter. Python3 # Python implementation to count whitespace characters in a string# Given string# Initialising the counter to 0string = 'My name is Ayush'count=0 # Iterating the string and checking for whitespace characters# Incrementing the counter if a whitespace character is found# Finally printing the countfor a in string: if (a.isspace()) == True: count+=1print(count) string = 'My name is \n\n\n\n\nAyush'count = 0for a in string: if (a.isspace()) == True: count+=1print(count) Output: 3 8 AmiyaRanjanRout python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 23432, "s": 23404, "text": "\n12 Aug, 2021" }, { "code": null, "e": 23720, "s": 23432, "text": "Python String isspace() is a built-in method used for string handling. The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as:" }, { "code": null, "e": 23732, "s": 23720, "text": "‘ ‘ – Space" }, { "code": null, "e": 23754, "s": 23732, "text": "‘\\t’ – Horizontal tab" }, { "code": null, "e": 23769, "s": 23754, "text": "‘\\n’ – Newline" }, { "code": null, "e": 23789, "s": 23769, "text": "‘\\v’ – Vertical tab" }, { "code": null, "e": 23801, "s": 23789, "text": "‘\\f’ – Feed" }, { "code": null, "e": 23824, "s": 23801, "text": "‘\\r’ – Carriage return" }, { "code": null, "e": 23832, "s": 23824, "text": "Syntax:" }, { "code": null, "e": 23849, "s": 23832, "text": "string.isspace()" }, { "code": null, "e": 23861, "s": 23849, "text": "Parameters:" }, { "code": null, "e": 23900, "s": 23861, "text": "isspace() does not take any parameters" }, { "code": null, "e": 23909, "s": 23900, "text": "Returns:" }, { "code": null, "e": 24042, "s": 23909, "text": "True – If all characters in the string are whitespace characters.False – If the string contains 1 or more non-whitespace characters." }, { "code": null, "e": 24108, "s": 24042, "text": "True – If all characters in the string are whitespace characters." }, { "code": null, "e": 24176, "s": 24108, "text": "False – If the string contains 1 or more non-whitespace characters." }, { "code": null, "e": 24320, "s": 24176, "text": "Input : string = 'Geeksforgeeks'\nOutput : False\n\nInput : string = '\\n \\n \\n'\nOutput : True\n\nInput : string = 'Geeks\\nFor\\nGeeks'\nOutput : False" }, { "code": null, "e": 24328, "s": 24320, "text": "Python3" }, { "code": "# Python code for implementation of isspace() # checking for whitespace charactersstring = 'Geeksforgeeks' print(string.isspace()) # checking if \\n is a whitespace characterstring = '\\n \\n \\n' print(string.isspace()) string = 'Geeks\\nfor\\ngeeks'print( string.isspace())", "e": 24605, "s": 24328, "text": null }, { "code": null, "e": 24614, "s": 24605, "text": "Output: " }, { "code": null, "e": 24631, "s": 24614, "text": "False\nTrue\nFalse" }, { "code": null, "e": 24715, "s": 24631, "text": "Given a string in python, count the number of whitespace characters in the string. " }, { "code": null, "e": 24820, "s": 24715, "text": "Input : string = 'My name is Ayush'\nOutput : 3\n\nInput : string = 'My name is \\n\\n\\n\\n\\nAyush'\nOutput : 8" }, { "code": null, "e": 24832, "s": 24820, "text": "Algorithm: " }, { "code": null, "e": 25079, "s": 24832, "text": "Traverse the given string character by character up to its length, check if the character is a whitespace character. If it is a whitespace character, increment the counter by 1, else traverse to the next character. Print the value of the counter." }, { "code": null, "e": 25197, "s": 25079, "text": "Traverse the given string character by character up to its length, check if the character is a whitespace character. " }, { "code": null, "e": 25296, "s": 25197, "text": "If it is a whitespace character, increment the counter by 1, else traverse to the next character. " }, { "code": null, "e": 25328, "s": 25296, "text": "Print the value of the counter." }, { "code": null, "e": 25336, "s": 25328, "text": "Python3" }, { "code": "# Python implementation to count whitespace characters in a string# Given string# Initialising the counter to 0string = 'My name is Ayush'count=0 # Iterating the string and checking for whitespace characters# Incrementing the counter if a whitespace character is found# Finally printing the countfor a in string: if (a.isspace()) == True: count+=1print(count) string = 'My name is \\n\\n\\n\\n\\nAyush'count = 0for a in string: if (a.isspace()) == True: count+=1print(count)", "e": 25829, "s": 25336, "text": null }, { "code": null, "e": 25838, "s": 25829, "text": "Output: " }, { "code": null, "e": 25842, "s": 25838, "text": "3\n8" }, { "code": null, "e": 25858, "s": 25842, "text": "AmiyaRanjanRout" }, { "code": null, "e": 25872, "s": 25858, "text": "python-string" }, { "code": null, "e": 25879, "s": 25872, "text": "Python" }, { "code": null, "e": 25977, "s": 25879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25986, "s": 25977, "text": "Comments" }, { "code": null, "e": 25999, "s": 25986, "text": "Old Comments" }, { "code": null, "e": 26027, "s": 25999, "text": "Read JSON file using Python" }, { "code": null, "e": 26077, "s": 26027, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26099, "s": 26077, "text": "Python map() function" }, { "code": null, "e": 26143, "s": 26099, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26161, "s": 26143, "text": "Python Dictionary" }, { "code": null, "e": 26184, "s": 26161, "text": "Taking input in Python" }, { "code": null, "e": 26219, "s": 26184, "text": "Read a file line by line in Python" }, { "code": null, "e": 26241, "s": 26219, "text": "Enumerate() in Python" }, { "code": null, "e": 26273, "s": 26241, "text": "How to Install PIP on Windows ?" } ]
XAML - Debugging
If you are familiar with debugging in any procedural language (such as C#, C/C++ etc.) and you know the usage of break and are expecting the same kind of debugging in XAML, then you will be surprised to know that it is not possible yet to debug an XAML code like the way you used to debug any other procedural language code. Debugging an XAML app means trying to find an error; In data binding, your data doesn't show up on screen and you don't know why In data binding, your data doesn't show up on screen and you don't know why Or an issue is related to complex layouts. Or an issue is related to complex layouts. Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box. Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box. Debugging in XAML is something you typically do to check if your bindings work, and if it is not working, then to check what's wrong. Unfortunately, setting breakpoints in XAML bindings isn't possible except in Silverlight, but we can use the Output window to check for data binding errors. Let's have a look at the following XAML code to find the error in data binding. <Window x:Class = "DataBindingOneWay.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Name = "Display"> <StackPanel Orientation = "Horizontal" Margin = "50, 50, 0, 0"> <TextBlock Text = "Name: " Margin = "10" Width = "100"/> <TextBlock Margin = "10" Width = "100" Text = "{Binding FirstName}"/> </StackPanel> <StackPanel Orientation = "Horizontal" Margin = "50,0,50,0"> <TextBlock Text = "Title: " Margin = "10" Width = "100"/> <TextBlock Margin = "10" Width="100" Text = "{Binding Title}" /> </StackPanel> </StackPanel> </Grid> </Window> Text properties of the two text blocks are set to “Name” and “Title” statically, while the other two text block’s Text properties are bound to “FirstName” and “Title”. But the class variables are intentionally taken as Name and Title in the Employee class which are incorrect variable names. Let us now try to understand where we can find this type of mistake when the desired output is not shown. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataBindingOneWay { public class Employee { public string Name { get; set; } public string Title { get; set; } public static Employee GetEmployee() { var emp = new Employee() { Name = "Ali Ahmed", Title = "Developer" }; return emp; } } } Here is the implementation of MainWindow class in C# code − using System; using System.Windows; using System.Windows.Controls; namespace DataBindingOneWay { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = Employee.GetEmployee(); } } } Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Title of that Employee object but the name is not bound. To check what happened with the name, let’s look at the output window where a lot of log is generated. The easiest way to find an error is to just search for error and you will find the below mentioned error which says “BindingExpression path error: 'FirstName' property not found on 'object' ''Employe” System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Employee' (HashCode = 11611730)'. BindingExpression:Path = FirstName; DataItem = 'Employee' (HashCode = 11611730); target element is 'TextBlock' (Name = ''); target property is 'Text' (type 'String') Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix this type of issues in your application. When you change the FirstName to Name again, you will see the desired output. UI debugging tools for XAML are introduced with Visual Studio 2015 to inspect the XAML code at runtime. With the help of these tools, XAML code is presented in the form of visual tree of your running WPF application and also the different UI element properties in the tree. To enable this tool, follow the steps given below. Step 1 − Go to the Tools menu and select Options from the Tools menu. Step 1 − Go to the Tools menu and select Options from the Tools menu. Step 2 − You will get to see the following dialog box. Step 2 − You will get to see the following dialog box. Step 3 − Go to the General Options under Debugging item on the left side. Step 3 − Go to the General Options under Debugging item on the left side. Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML” Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML” Step 5 − Press the OK button. Step 5 − Press the OK button. Now run any XAML application or use the following XAML code − <Window x:Class = "XAMLTestBinding.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <ComboBox Name = "comboBox" Margin = "50" Width = "100"> <ComboBoxItem Content = "Green"/> <ComboBoxItem Content = "Yellow" IsSelected = "True"/> <ComboBoxItem Content = "Orange" /> </ComboBox> <TextBox Name = "textBox" Margin = "50" Width = "100" Height = "23" VerticalAlignment = "Top" Text = "{ Binding ElementName = comboBox, Path = SelectedItem.Content, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" Background = "{Binding ElementName = comboBox, Path = SelectedItem.Content}"> </TextBox> </StackPanel> </Window> When the application executes, it will show the Live Visual Tree where all the elements are shown in a tree. This Live Visual Tree shows the complete layout structure to understand where the UI elements are placed. But this option is only available in Visual Studio 2015. If you are using an older version of Visual studio, then you can’t use this tool; however there is another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from http://xamlspy.com/download. We recommend you to download this tool if you are using an older version of Visual Studio. Print Add Notes Bookmark this page
[ { "code": null, "e": 2301, "s": 1923, "text": "If you are familiar with debugging in any procedural language (such as C#, C/C++ etc.) and you know the usage of break and are expecting the same kind of debugging in XAML, then you will be surprised to know that it is not possible yet to debug an XAML code like the way you used to debug any other procedural language code. Debugging an XAML app means trying to find an error;" }, { "code": null, "e": 2377, "s": 2301, "text": "In data binding, your data doesn't show up on screen and you don't know why" }, { "code": null, "e": 2453, "s": 2377, "text": "In data binding, your data doesn't show up on screen and you don't know why" }, { "code": null, "e": 2496, "s": 2453, "text": "Or an issue is related to complex layouts." }, { "code": null, "e": 2539, "s": 2496, "text": "Or an issue is related to complex layouts." }, { "code": null, "e": 2661, "s": 2539, "text": "Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box." }, { "code": null, "e": 2783, "s": 2661, "text": "Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box." }, { "code": null, "e": 3154, "s": 2783, "text": "Debugging in XAML is something you typically do to check if your bindings work, and if it is not working, then to check what's wrong. Unfortunately, setting breakpoints in XAML bindings isn't possible except in Silverlight, but we can use the Output window to check for data binding errors. Let's have a look at the following XAML code to find the error in data binding." }, { "code": null, "e": 3972, "s": 3154, "text": "<Window x:Class = \"DataBindingOneWay.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid>\n <StackPanel Name = \"Display\">\n <StackPanel Orientation = \"Horizontal\" Margin = \"50, 50, 0, 0\">\n <TextBlock Text = \"Name: \" Margin = \"10\" Width = \"100\"/>\n <TextBlock Margin = \"10\" Width = \"100\" Text = \"{Binding FirstName}\"/>\n </StackPanel>\n\t\t\t\n <StackPanel Orientation = \"Horizontal\" Margin = \"50,0,50,0\">\n <TextBlock Text = \"Title: \" Margin = \"10\" Width = \"100\"/>\n <TextBlock Margin = \"10\" Width=\"100\" Text = \"{Binding Title}\" />\n </StackPanel>\n </StackPanel>\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 4370, "s": 3972, "text": "Text properties of the two text blocks are set to “Name” and “Title” statically, while the other two text block’s Text properties are bound to “FirstName” and “Title”. But the class variables are intentionally taken as Name and Title in the Employee class which are incorrect variable names. Let us now try to understand where we can find this type of mistake when the desired output is not shown." }, { "code": null, "e": 4826, "s": 4370, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace DataBindingOneWay {\n public class Employee {\n public string Name { get; set; } \n public string Title { get; set; }\n\t\t\n public static Employee GetEmployee() {\n var emp = new Employee() {\n Name = \"Ali Ahmed\", \n Title = \"Developer\"\n };\n return emp; \n }\n }\n}" }, { "code": null, "e": 4886, "s": 4826, "text": "Here is the implementation of MainWindow class in C# code −" }, { "code": null, "e": 5244, "s": 4886, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace DataBindingOneWay {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() {\n InitializeComponent(); \n DataContext = Employee.GetEmployee(); \n }\n }\n}" }, { "code": null, "e": 5413, "s": 5244, "text": "Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Title of that Employee object but the name is not bound." }, { "code": null, "e": 5516, "s": 5413, "text": "To check what happened with the name, let’s look at the output window where a lot of log is generated." }, { "code": null, "e": 5717, "s": 5516, "text": "The easiest way to find an error is to just search for error and you will find the below mentioned error which says “BindingExpression path error: 'FirstName' property not found on 'object' ''Employe”" }, { "code": null, "e": 6029, "s": 5717, "text": "System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName'\n property not found on 'object' ''Employee' (HashCode = 11611730)'.\nBindingExpression:Path = FirstName; \nDataItem = 'Employee' (HashCode = 11611730); target element is 'TextBlock' (Name = ''); \ntarget property is 'Text' (type 'String')" }, { "code": null, "e": 6162, "s": 6029, "text": "Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix this type of issues in your application." }, { "code": null, "e": 6240, "s": 6162, "text": "When you change the FirstName to Name again, you will see the desired output." }, { "code": null, "e": 6565, "s": 6240, "text": "UI debugging tools for XAML are introduced with Visual Studio 2015 to inspect the XAML code at runtime. With the help of these tools, XAML code is presented in the form of visual tree of your running WPF application and also the different UI element properties in the tree. To enable this tool, follow the steps given below." }, { "code": null, "e": 6635, "s": 6565, "text": "Step 1 − Go to the Tools menu and select Options from the Tools menu." }, { "code": null, "e": 6705, "s": 6635, "text": "Step 1 − Go to the Tools menu and select Options from the Tools menu." }, { "code": null, "e": 6760, "s": 6705, "text": "Step 2 − You will get to see the following dialog box." }, { "code": null, "e": 6815, "s": 6760, "text": "Step 2 − You will get to see the following dialog box." }, { "code": null, "e": 6889, "s": 6815, "text": "Step 3 − Go to the General Options under Debugging item on the left side." }, { "code": null, "e": 6963, "s": 6889, "text": "Step 3 − Go to the General Options under Debugging item on the left side." }, { "code": null, "e": 7044, "s": 6963, "text": "Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML”" }, { "code": null, "e": 7125, "s": 7044, "text": "Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML”" }, { "code": null, "e": 7155, "s": 7125, "text": "Step 5 − Press the OK button." }, { "code": null, "e": 7185, "s": 7155, "text": "Step 5 − Press the OK button." }, { "code": null, "e": 7247, "s": 7185, "text": "Now run any XAML application or use the following XAML code −" }, { "code": null, "e": 8125, "s": 7247, "text": "<Window x:Class = \"XAMLTestBinding.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <StackPanel>\n <ComboBox Name = \"comboBox\" Margin = \"50\" Width = \"100\">\n <ComboBoxItem Content = \"Green\"/>\n <ComboBoxItem Content = \"Yellow\" IsSelected = \"True\"/>\n <ComboBoxItem Content = \"Orange\" />\n </ComboBox>\n\t\t\n <TextBox Name = \"textBox\" Margin = \"50\" Width = \"100\" \n Height = \"23\" VerticalAlignment = \"Top\" Text = \"{\n Binding ElementName = comboBox, Path = SelectedItem.Content, \n Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}\" \n Background = \"{Binding ElementName = comboBox, Path = SelectedItem.Content}\"> \n </TextBox>\n </StackPanel>\n\t\n</Window>" }, { "code": null, "e": 8234, "s": 8125, "text": "When the application executes, it will show the Live Visual Tree where all the elements are shown in a tree." }, { "code": null, "e": 8733, "s": 8234, "text": "This Live Visual Tree shows the complete layout structure to understand where the UI elements are placed. But this option is only available in Visual Studio 2015. If you are using an older version of Visual studio, then you can’t use this tool; however there is another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from http://xamlspy.com/download. We recommend you to download this tool if you are using an older version of Visual Studio." }, { "code": null, "e": 8740, "s": 8733, "text": " Print" }, { "code": null, "e": 8751, "s": 8740, "text": " Add Notes" } ]
Execute INSERT if table is empty in MySQL?
You can execute insert if table is empty with the help of subquery. For that, work on not exists condition with subquery. The below syntax will work only when your table is empty. If your table is not empty then it will not insert the record. The syntax is as follows: INSERT INTO yourTableName(yourColumnName) SELECT ‘anyValue’ WHERE NOT EXISTS (SELECT *FROM yourTableName); To understand the above syntax, let us create a table. The query to create a table is as follows: mysql> create table ExecuteInsertDemo -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.67 sec) Let us insert record in the table using insert command. The query to insert record is as follows: mysql> insert into ExecuteInsertDemo values('John'); Query OK, 1 row affected (0.19 sec) Let’s say our table is not empty. It has only a single record. If you execute insert command then MySQL will not enter that record in the table. The query to execute insert is as follows: mysql> insert into ExecuteInsertDemo(Name) -> select 'Larry' -> where not exists (select *from ExecuteInsertDemo); Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 Display the record using select statement. The query is as follows: mysql> select *from ExecuteInsertDemo; The following is the output: +------+ | Name | +------+ | John | +------+ 1 row in set (0.00 sec) Yo need to delete the record from the table to run the query we saw above. Use truncate command. The query is as follows: mysql> truncate table ExecuteInsertDemo; Query OK, 0 rows affected (1.10 sec) Run the above query to execute insert command. The query is as follows: mysql> insert into ExecuteInsertDemo(Name) -> select 'Larry' -> where not exists (select *from ExecuteInsertDemo); Query OK, 1 row affected (0.33 sec) Records: 1 Duplicates: 0 Warnings: 0 Display the record from the table using select. The query is as follows: mysql> select *from ExecuteInsertDemo; The following is the output: +-------+ | Name | +-------+ | Larry | +-------+ 1 row in set (0.00 sec) Look at the sample output, ’Larry’ has been inserted successfully when the table was empty.
[ { "code": null, "e": 1184, "s": 1062, "text": "You can execute insert if table is empty with the help of subquery. For that, work on not exists condition with subquery." }, { "code": null, "e": 1331, "s": 1184, "text": "The below syntax will work only when your table is empty. If your table is not empty then it will not insert the record. The syntax is as follows:" }, { "code": null, "e": 1438, "s": 1331, "text": "INSERT INTO yourTableName(yourColumnName)\nSELECT ‘anyValue’\nWHERE NOT EXISTS (SELECT *FROM yourTableName);" }, { "code": null, "e": 1536, "s": 1438, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1651, "s": 1536, "text": "mysql> create table ExecuteInsertDemo\n -> (\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.67 sec)" }, { "code": null, "e": 1749, "s": 1651, "text": "Let us insert record in the table using insert command. The query to insert record is as follows:" }, { "code": null, "e": 1838, "s": 1749, "text": "mysql> insert into ExecuteInsertDemo values('John');\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 1983, "s": 1838, "text": "Let’s say our table is not empty. It has only a single record. If you execute insert command then MySQL will not enter that record in the table." }, { "code": null, "e": 2026, "s": 1983, "text": "The query to execute insert is as follows:" }, { "code": null, "e": 2221, "s": 2026, "text": "mysql> insert into ExecuteInsertDemo(Name)\n -> select 'Larry'\n -> where not exists (select *from ExecuteInsertDemo);\nQuery OK, 0 rows affected (0.00 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2289, "s": 2221, "text": "Display the record using select statement. The query is as follows:" }, { "code": null, "e": 2328, "s": 2289, "text": "mysql> select *from ExecuteInsertDemo;" }, { "code": null, "e": 2357, "s": 2328, "text": "The following is the output:" }, { "code": null, "e": 2426, "s": 2357, "text": "+------+\n| Name |\n+------+\n| John |\n+------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2548, "s": 2426, "text": "Yo need to delete the record from the table to run the query we saw above. Use truncate command. The query is as follows:" }, { "code": null, "e": 2626, "s": 2548, "text": "mysql> truncate table ExecuteInsertDemo;\nQuery OK, 0 rows affected (1.10 sec)" }, { "code": null, "e": 2698, "s": 2626, "text": "Run the above query to execute insert command. The query is as follows:" }, { "code": null, "e": 2892, "s": 2698, "text": "mysql> insert into ExecuteInsertDemo(Name)\n -> select 'Larry'\n -> where not exists (select *from ExecuteInsertDemo);\nQuery OK, 1 row affected (0.33 sec)\nRecords: 1 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2965, "s": 2892, "text": "Display the record from the table using select. The query is as follows:" }, { "code": null, "e": 3004, "s": 2965, "text": "mysql> select *from ExecuteInsertDemo;" }, { "code": null, "e": 3033, "s": 3004, "text": "The following is the output:" }, { "code": null, "e": 3107, "s": 3033, "text": "+-------+\n| Name |\n+-------+\n| Larry |\n+-------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3199, "s": 3107, "text": "Look at the sample output, ’Larry’ has been inserted successfully when the table was empty." } ]
Amazon Interview Experience for SDE-1 FTE (On-Campus) - GeeksforGeeks
22 Feb, 2022 Amazon visited our campus for SDE-1 FTE hiring. There were a total of 4 rounds (1 Coding Test+3 Technical Interviews) Round 1 (Coding Test): This round had 4 sections, debugging, coding, Workstyle Assessment, and aptitude. Debugging and aptitude were easy and didn’t even require any preparation. You just need to be a little quick in all these rounds. In the coding round, 2 random questions were chosen for everybody from this pool of questions. https://leetcode.com/discuss/interview-question/344650/Amazon-Online-Assessment-Questions/ Try all the questions in the new and old sections. Round 2 (Technical Interview 1): Two nodes of a BST are swapped, correct the BST.Given a number N, count the number of arrays that can be constructed such that the sum of elements is N. One constraint is that each element should be greater than 3. Two nodes of a BST are swapped, correct the BST. Given a number N, count the number of arrays that can be constructed such that the sum of elements is N. One constraint is that each element should be greater than 3. Example: Input: 6 Output: 2 Possible arrays: [3,3], [6] I gave the recursive solution. They wanted the time complexity of that solution. which was something like (N-6)^(N/3). Then they asked for the optimized solution of the same using DP. Round 3(Technical Interview 2): Given 2 numbers N and M count the number of set bits in them. He first asked me to make a function that returns the number of set bits of a number, then asked to code the solution. He wanted the most optimized solution something like this. https://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n-set-2/ Which I was not able to give.Given dependencies like A->B, C, D and B -> D and D -> E. Print the ordering of the tasks. for ex E D B C D A. I came up with the topological sort solution https://www.geeksforgeeks.org/topological-sorting/. He wanted to look for all the edge cases and check if the code was perfect. I found the case when there are circular dependencies and changed the code accordingly.Then he asked for a few OS and networking questions like the Difference between semaphore and mutex, the Difference between TCP and UDP, and what is Banker’s algorithm. Then he jumped to my CV and asked about the Internship I did. Given 2 numbers N and M count the number of set bits in them. He first asked me to make a function that returns the number of set bits of a number, then asked to code the solution. He wanted the most optimized solution something like this. https://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n-set-2/ Which I was not able to give. Given dependencies like A->B, C, D and B -> D and D -> E. Print the ordering of the tasks. for ex E D B C D A. I came up with the topological sort solution https://www.geeksforgeeks.org/topological-sorting/. He wanted to look for all the edge cases and check if the code was perfect. I found the case when there are circular dependencies and changed the code accordingly. Then he asked for a few OS and networking questions like the Difference between semaphore and mutex, the Difference between TCP and UDP, and what is Banker’s algorithm. Then he jumped to my CV and asked about the Internship I did. Round 4(Technical And Managerial): For me, the round was only for 45 minutes. Given a binary tree find the level with maximum nodes and give the sum of nodes at that level. He wanted me to use just the queue and nothing else, and then he asked to optimize it as the tree is huge. Then he asked for the time complexity of the same. I missed one edge case in this.Tell me about a time when you were faced with a complex problem and what solution you came up with? Then he asked if I could have done anything different and better.Tell me a time when I had to process a lot of data in a small amount of time? Again asked if I could have gone for any different approach. Given a binary tree find the level with maximum nodes and give the sum of nodes at that level. He wanted me to use just the queue and nothing else, and then he asked to optimize it as the tree is huge. Then he asked for the time complexity of the same. I missed one edge case in this. Tell me about a time when you were faced with a complex problem and what solution you came up with? Then he asked if I could have done anything different and better. Tell me a time when I had to process a lot of data in a small amount of time? Again asked if I could have gone for any different approach. Check this for more details. https://www.amazon.jobs/en/landing_pages/in-person-interview In the end, there were 8 students who gave 4 rounds and 6/8 were selected including me Note: They were very serious about the time complexity of every algorithm. Prepare for the behavioural questions, and read about leadership principles and STAR format, mentioned in the above link. They wanted the runnable code for every question also covering all the edge cases. Amazon Marketing On-Campus Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience for SDE-1 Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Directi Interview | Set 7 (Programming Questions) Amazon Interview Experience (Off-Campus) 2022 Oracle Interview Experience | Set 69 (Application Engineer) Amazon Interview Experience for SDE-1
[ { "code": null, "e": 25351, "s": 25323, "text": "\n22 Feb, 2022" }, { "code": null, "e": 25469, "s": 25351, "text": "Amazon visited our campus for SDE-1 FTE hiring. There were a total of 4 rounds (1 Coding Test+3 Technical Interviews)" }, { "code": null, "e": 25705, "s": 25469, "text": "Round 1 (Coding Test): This round had 4 sections, debugging, coding, Workstyle Assessment, and aptitude. Debugging and aptitude were easy and didn’t even require any preparation. You just need to be a little quick in all these rounds. " }, { "code": null, "e": 25800, "s": 25705, "text": "In the coding round, 2 random questions were chosen for everybody from this pool of questions." }, { "code": null, "e": 25891, "s": 25800, "text": "https://leetcode.com/discuss/interview-question/344650/Amazon-Online-Assessment-Questions/" }, { "code": null, "e": 25943, "s": 25891, "text": "Try all the questions in the new and old sections. " }, { "code": null, "e": 25976, "s": 25943, "text": "Round 2 (Technical Interview 1):" }, { "code": null, "e": 26192, "s": 25976, "text": "Two nodes of a BST are swapped, correct the BST.Given a number N, count the number of arrays that can be constructed such that the sum of elements is N. One constraint is that each element should be greater than 3. " }, { "code": null, "e": 26241, "s": 26192, "text": "Two nodes of a BST are swapped, correct the BST." }, { "code": null, "e": 26409, "s": 26241, "text": "Given a number N, count the number of arrays that can be constructed such that the sum of elements is N. One constraint is that each element should be greater than 3. " }, { "code": null, "e": 26418, "s": 26409, "text": "Example:" }, { "code": null, "e": 26465, "s": 26418, "text": "Input: 6\nOutput: 2\nPossible arrays: [3,3], [6]" }, { "code": null, "e": 26649, "s": 26465, "text": "I gave the recursive solution. They wanted the time complexity of that solution. which was something like (N-6)^(N/3). Then they asked for the optimized solution of the same using DP." }, { "code": null, "e": 26681, "s": 26649, "text": "Round 3(Technical Interview 2):" }, { "code": null, "e": 27637, "s": 26681, "text": "Given 2 numbers N and M count the number of set bits in them. He first asked me to make a function that returns the number of set bits of a number, then asked to code the solution. He wanted the most optimized solution something like this. https://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n-set-2/ Which I was not able to give.Given dependencies like A->B, C, D and B -> D and D -> E. Print the ordering of the tasks. for ex E D B C D A. I came up with the topological sort solution https://www.geeksforgeeks.org/topological-sorting/. He wanted to look for all the edge cases and check if the code was perfect. I found the case when there are circular dependencies and changed the code accordingly.Then he asked for a few OS and networking questions like the Difference between semaphore and mutex, the Difference between TCP and UDP, and what is Banker’s algorithm. Then he jumped to my CV and asked about the Internship I did." }, { "code": null, "e": 27992, "s": 27637, "text": "Given 2 numbers N and M count the number of set bits in them. He first asked me to make a function that returns the number of set bits of a number, then asked to code the solution. He wanted the most optimized solution something like this. https://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n-set-2/ Which I was not able to give." }, { "code": null, "e": 28364, "s": 27992, "text": "Given dependencies like A->B, C, D and B -> D and D -> E. Print the ordering of the tasks. for ex E D B C D A. I came up with the topological sort solution https://www.geeksforgeeks.org/topological-sorting/. He wanted to look for all the edge cases and check if the code was perfect. I found the case when there are circular dependencies and changed the code accordingly." }, { "code": null, "e": 28595, "s": 28364, "text": "Then he asked for a few OS and networking questions like the Difference between semaphore and mutex, the Difference between TCP and UDP, and what is Banker’s algorithm. Then he jumped to my CV and asked about the Internship I did." }, { "code": null, "e": 28674, "s": 28595, "text": "Round 4(Technical And Managerial): For me, the round was only for 45 minutes. " }, { "code": null, "e": 29262, "s": 28674, "text": "Given a binary tree find the level with maximum nodes and give the sum of nodes at that level. He wanted me to use just the queue and nothing else, and then he asked to optimize it as the tree is huge. Then he asked for the time complexity of the same. I missed one edge case in this.Tell me about a time when you were faced with a complex problem and what solution you came up with? Then he asked if I could have done anything different and better.Tell me a time when I had to process a lot of data in a small amount of time? Again asked if I could have gone for any different approach." }, { "code": null, "e": 29547, "s": 29262, "text": "Given a binary tree find the level with maximum nodes and give the sum of nodes at that level. He wanted me to use just the queue and nothing else, and then he asked to optimize it as the tree is huge. Then he asked for the time complexity of the same. I missed one edge case in this." }, { "code": null, "e": 29713, "s": 29547, "text": "Tell me about a time when you were faced with a complex problem and what solution you came up with? Then he asked if I could have done anything different and better." }, { "code": null, "e": 29852, "s": 29713, "text": "Tell me a time when I had to process a lot of data in a small amount of time? Again asked if I could have gone for any different approach." }, { "code": null, "e": 29942, "s": 29852, "text": "Check this for more details. https://www.amazon.jobs/en/landing_pages/in-person-interview" }, { "code": null, "e": 30029, "s": 29942, "text": "In the end, there were 8 students who gave 4 rounds and 6/8 were selected including me" }, { "code": null, "e": 30226, "s": 30029, "text": "Note: They were very serious about the time complexity of every algorithm. Prepare for the behavioural questions, and read about leadership principles and STAR format, mentioned in the above link." }, { "code": null, "e": 30309, "s": 30226, "text": "They wanted the runnable code for every question also covering all the edge cases." }, { "code": null, "e": 30316, "s": 30309, "text": "Amazon" }, { "code": null, "e": 30326, "s": 30316, "text": "Marketing" }, { "code": null, "e": 30336, "s": 30326, "text": "On-Campus" }, { "code": null, "e": 30358, "s": 30336, "text": "Interview Experiences" }, { "code": null, "e": 30365, "s": 30358, "text": "Amazon" }, { "code": null, "e": 30463, "s": 30365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30472, "s": 30463, "text": "Comments" }, { "code": null, "e": 30485, "s": 30472, "text": "Old Comments" }, { "code": null, "e": 30544, "s": 30485, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 30594, "s": 30544, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 30632, "s": 30594, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 30704, "s": 30632, "text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022" }, { "code": null, "e": 30769, "s": 30704, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 30819, "s": 30769, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 30869, "s": 30819, "text": "Directi Interview | Set 7 (Programming Questions)" }, { "code": null, "e": 30915, "s": 30869, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 30975, "s": 30915, "text": "Oracle Interview Experience | Set 69 (Application Engineer)" } ]
Design finite automata from regular expressions - GeeksforGeeks
05 Jul, 2021 Prerequisite – Finite automata, Regular expressions, grammar, and language. In this article, we will see some popular regular expressions and how we can convert them to finite automata (NFA and DFA). Let’s discuss it one by one. Overview :Let a and b are input symbols and r is the regular expression. Now we have to design NFA as well as DFA for each regular expression. Design finite automata from the regular expression :Here, we will discuss the Design of finite automata from regular expression as follows. Case-1 : When r = Φ, then FA will be as follows. Case-2 : When r = ε, then FA will be as follows. Case-3 : When r = a, then FA will be as follows. Case-4 : When r = a+b , then FA will be as follows. Case-5 : When r = r = a* , then FA will be as follows. Case-6 : When r = a* + b*, then FA will be as follows. Case-7 : When r = (ab)*, then FA will be as follows. Case-8 : When r = (ab)*b, then FA will be as follows. Case-9 : When r = (ab)*a, then FA will be as follows. Case-10 : When r = a*b*, then FA will be as follows. Case-11 : When r = (a+b)*, then FA will be as follows. Unary Design :Let a is the input symbol and r is the regular expression. For each regular expression, we will design finite automata. Case-1 : r = a* Case-2 : r = (aa)* Case-3 : r = (aa)*a Case-4 : r = aaaa* Case-5 : r= (aa + aaa)* Case-6 : r=( aaa+aaaaa)* Case-7 : r=(aa + aaaaaa)*It is a multiple of 1 term i.e. aa, so it can be reduced to r=(aa)*. L= {an | n = 7x+12, x € Z, x >=0 } General Methods :Here, we will discuss some general methods as follows. Method-1 : L = { aK1n+K2 ; n>=0 } If K1>K2, No. of states = K1If K1<K2, No. of states = K2 +1If K1=K2, No. of states = K1 +1 = k2 +1 Method-2 : L = { aKn ; n>0 , K is a fixed integer } = { aKn ; n>=1. K is an integer} No. of states = K +1 Method-3 : L = { aKn ; n>=0 , K is a fixed integer } Here, residue i.e. K2=0, K1>K2. Therefore, No. of states = K regular-expression GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Regular Expressions, Regular Grammar and Regular Languages Difference between Clustered and Non-clustered index Preemptive and Non-Preemptive Scheduling Introduction of Process Synchronization Third Normal Form (3NF) Regular Expressions, Regular Grammar and Regular Languages Difference between DFA and NFA Introduction of Finite Automata Pumping Lemma in Theory of Computation Turing Machine in TOC
[ { "code": null, "e": 24272, "s": 24244, "text": "\n05 Jul, 2021" }, { "code": null, "e": 24349, "s": 24272, "text": "Prerequisite – Finite automata, Regular expressions, grammar, and language." }, { "code": null, "e": 24502, "s": 24349, "text": "In this article, we will see some popular regular expressions and how we can convert them to finite automata (NFA and DFA). Let’s discuss it one by one." }, { "code": null, "e": 24645, "s": 24502, "text": "Overview :Let a and b are input symbols and r is the regular expression. Now we have to design NFA as well as DFA for each regular expression." }, { "code": null, "e": 24785, "s": 24645, "text": "Design finite automata from the regular expression :Here, we will discuss the Design of finite automata from regular expression as follows." }, { "code": null, "e": 24834, "s": 24785, "text": "Case-1 : When r = Φ, then FA will be as follows." }, { "code": null, "e": 24883, "s": 24834, "text": "Case-2 : When r = ε, then FA will be as follows." }, { "code": null, "e": 24932, "s": 24883, "text": "Case-3 : When r = a, then FA will be as follows." }, { "code": null, "e": 24984, "s": 24932, "text": "Case-4 : When r = a+b , then FA will be as follows." }, { "code": null, "e": 25040, "s": 24984, "text": "Case-5 : When r = r = a* , then FA will be as follows. " }, { "code": null, "e": 25095, "s": 25040, "text": "Case-6 : When r = a* + b*, then FA will be as follows." }, { "code": null, "e": 25148, "s": 25095, "text": "Case-7 : When r = (ab)*, then FA will be as follows." }, { "code": null, "e": 25202, "s": 25148, "text": "Case-8 : When r = (ab)*b, then FA will be as follows." }, { "code": null, "e": 25256, "s": 25202, "text": "Case-9 : When r = (ab)*a, then FA will be as follows." }, { "code": null, "e": 25309, "s": 25256, "text": "Case-10 : When r = a*b*, then FA will be as follows." }, { "code": null, "e": 25364, "s": 25309, "text": "Case-11 : When r = (a+b)*, then FA will be as follows." }, { "code": null, "e": 25498, "s": 25364, "text": "Unary Design :Let a is the input symbol and r is the regular expression. For each regular expression, we will design finite automata." }, { "code": null, "e": 25515, "s": 25498, "text": "Case-1 : r = a* " }, { "code": null, "e": 25534, "s": 25515, "text": "Case-2 : r = (aa)*" }, { "code": null, "e": 25554, "s": 25534, "text": "Case-3 : r = (aa)*a" }, { "code": null, "e": 25573, "s": 25554, "text": "Case-4 : r = aaaa*" }, { "code": null, "e": 25597, "s": 25573, "text": "Case-5 : r= (aa + aaa)*" }, { "code": null, "e": 25622, "s": 25597, "text": "Case-6 : r=( aaa+aaaaa)*" }, { "code": null, "e": 25717, "s": 25622, "text": "Case-7 : r=(aa + aaaaaa)*It is a multiple of 1 term i.e. aa, so it can be reduced to r=(aa)*. " }, { "code": null, "e": 25753, "s": 25717, "text": "L= {an | n = 7x+12, x € Z, x >=0 }" }, { "code": null, "e": 25825, "s": 25753, "text": "General Methods :Here, we will discuss some general methods as follows." }, { "code": null, "e": 25836, "s": 25825, "text": "Method-1 :" }, { "code": null, "e": 25860, "s": 25836, "text": "L = { aK1n+K2 ; n>=0 }" }, { "code": null, "e": 25959, "s": 25860, "text": "If K1>K2, No. of states = K1If K1<K2, No. of states = K2 +1If K1=K2, No. of states = K1 +1 = k2 +1" }, { "code": null, "e": 25970, "s": 25959, "text": "Method-2 :" }, { "code": null, "e": 26012, "s": 25970, "text": "L = { aKn ; n>0 , K is a fixed integer }" }, { "code": null, "e": 26079, "s": 26012, "text": " = { aKn ; n>=1. K is an integer} No. of states = K +1 " }, { "code": null, "e": 26090, "s": 26079, "text": "Method-3 :" }, { "code": null, "e": 26133, "s": 26090, "text": "L = { aKn ; n>=0 , K is a fixed integer }" }, { "code": null, "e": 26196, "s": 26133, "text": "Here, residue i.e. K2=0, K1>K2. Therefore, No. of states = K " }, { "code": null, "e": 26215, "s": 26196, "text": "regular-expression" }, { "code": null, "e": 26223, "s": 26215, "text": "GATE CS" }, { "code": null, "e": 26256, "s": 26223, "text": "Theory of Computation & Automata" }, { "code": null, "e": 26354, "s": 26256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26363, "s": 26354, "text": "Comments" }, { "code": null, "e": 26376, "s": 26363, "text": "Old Comments" }, { "code": null, "e": 26435, "s": 26376, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 26488, "s": 26435, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26529, "s": 26488, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 26569, "s": 26529, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 26593, "s": 26569, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 26652, "s": 26593, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 26683, "s": 26652, "text": "Difference between DFA and NFA" }, { "code": null, "e": 26715, "s": 26683, "text": "Introduction of Finite Automata" }, { "code": null, "e": 26754, "s": 26715, "text": "Pumping Lemma in Theory of Computation" } ]
OpenCV - Reading an Image as Grayscale
The following program demonstrates how to read a colored image as grayscale and display it using JavaFX window. In here, we have read the image by passing the flag IMREAD_GRAYSCALE along with the String holding the path of a colored image. import java.awt.image.BufferedImage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; public class ReadingAsGrayscale extends Application { @Override public void start(Stage stage) throws Exception { WritableImage writableImage = loadAndConvert(); // Setting the image view ImageView imageView = new ImageView(writableImage); // Setting the position of the image imageView.setX(10); imageView.setY(10); // setting the fit height and width of the image view imageView.setFitHeight(400); imageView.setFitWidth(600); // Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // Creating a Group object Group root = new Group(imageView); // Creating a scene object Scene scene = new Scene(root, 600, 400); // Setting title to the Stage stage.setTitle("Reading image as grayscale"); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } public WritableImage loadAndConvert() throws Exception { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Instantiating the imagecodecs class Imgcodecs imageCodecs = new Imgcodecs(); String input = "C:/EXAMPLES/OpenCV/sample.jpg"; // Reading the image Mat src = imageCodecs.imread(input, Imgcodecs.IMREAD_GRAYSCALE); byte[] data1 = new byte[src.rows() * src.cols() * (int)(src.elemSize())]; src.get(0, 0, data1); // Creating the buffered image BufferedImage bufImage = new BufferedImage(src.cols(),src.rows(), BufferedImage.TYPE_BYTE_GRAY); // Setting the data elements to the image bufImage.getRaster().setDataElements(0, 0, src.cols(), src.rows(), data1); // Creating a WritableImage WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null); System.out.println("Image Read"); return writableImage; } public static void main(String args[]) throws Exception { launch(args); } } Assume that following is the input image sample.jpg specified in the above program. On executing the program, you will get the following output. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3244, "s": 3004, "text": "The following program demonstrates how to read a colored image as grayscale and display it using JavaFX window. In here, we have read the image by passing the flag IMREAD_GRAYSCALE along with the String holding the path of a colored image." }, { "code": null, "e": 5726, "s": 3244, "text": "import java.awt.image.BufferedImage;\n\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\n\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\n\npublic class ReadingAsGrayscale extends Application {\n @Override\n public void start(Stage stage) throws Exception {\n WritableImage writableImage = loadAndConvert();\n\n // Setting the image view\n ImageView imageView = new ImageView(writableImage);\n\n // Setting the position of the image\n imageView.setX(10);\n imageView.setY(10);\n\n // setting the fit height and width of the image view\n imageView.setFitHeight(400);\n imageView.setFitWidth(600);\n \n // Setting the preserve ratio of the image view\n imageView.setPreserveRatio(true);\n \n // Creating a Group object \n Group root = new Group(imageView);\n \n // Creating a scene object\n Scene scene = new Scene(root, 600, 400);\n \n // Setting title to the Stage\n stage.setTitle(\"Reading image as grayscale\");\n \n // Adding scene to the stage\n stage.setScene(scene);\n \n // Displaying the contents of the stage\n stage.show();\n } \n public WritableImage loadAndConvert() throws Exception {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Instantiating the imagecodecs class\n Imgcodecs imageCodecs = new Imgcodecs();\n\n String input = \"C:/EXAMPLES/OpenCV/sample.jpg\";\n\n // Reading the image\n Mat src = imageCodecs.imread(input, Imgcodecs.IMREAD_GRAYSCALE);\n \n byte[] data1 = new byte[src.rows() * src.cols() * (int)(src.elemSize())];\n src.get(0, 0, data1);\n \n // Creating the buffered image\n BufferedImage bufImage = new BufferedImage(src.cols(),src.rows(), \n BufferedImage.TYPE_BYTE_GRAY);\n \n // Setting the data elements to the image\n bufImage.getRaster().setDataElements(0, 0, src.cols(), src.rows(), data1);\n \n // Creating a WritableImage\n WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);\n System.out.println(\"Image Read\");\n return writableImage;\n } \n public static void main(String args[]) throws Exception { \n launch(args); \n } \n}" }, { "code": null, "e": 5810, "s": 5726, "text": "Assume that following is the input image sample.jpg specified in the above program." }, { "code": null, "e": 5871, "s": 5810, "text": "On executing the program, you will get the following output." }, { "code": null, "e": 5904, "s": 5871, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5921, "s": 5904, "text": " Abhilash Nelson" }, { "code": null, "e": 5954, "s": 5921, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 5971, "s": 5954, "text": " Abhilash Nelson" }, { "code": null, "e": 6004, "s": 5971, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6018, "s": 6004, "text": " Spotle Learn" }, { "code": null, "e": 6050, "s": 6018, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 6067, "s": 6050, "text": " Srikanth Guskra" }, { "code": null, "e": 6100, "s": 6067, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 6115, "s": 6100, "text": " Haithem Gasmi" }, { "code": null, "e": 6150, "s": 6115, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6168, "s": 6150, "text": " Gianluca Mottola" }, { "code": null, "e": 6175, "s": 6168, "text": " Print" }, { "code": null, "e": 6186, "s": 6175, "text": " Add Notes" } ]
Print all possible words from phone digits in C++
In this problem, we are given a number and we have to print all words that can be formed by pressing those words in an old fashioned mobile keyboard. We are quite familiar with the QWERTY keyboard style that we use today. But before the invention of QWERTY keypad phones were fitted with keypads with 12 buttons and each button contains words and numbers both. Like they word 6 on the keypad will contain words “MNO” which will be typed by clicking one, twice or thrice the keys. The keypad looked like this − In these keywords also all words are present and the user can type then. So, in this problem, we will be print all possible words that can be generated using the number sequence is given. Let’s take an example to understand the problem better − Input: 687 Output: MTP, MTQ, MTR, MTR, MUP, MUQ, MUR, MUS, MVP, MVQ, MVR, MVR, NTP, NTQ, NTR, NTR, NUP, NUQ, NUR, NUS, NVP, NVQ, NVR, NVR, OTP, OTQ, OTR, OTR, OUP, OUQ, OUR, OUS, OVP, OVQ, OVR, OVR. To solve this problem, let’s see the pattern that is made in the above example. Each button has its own associated characters and we will have to use those while typing. So, for each number, there are at max 4 options(in case of 7 and 9). For this, we can fix on digit and then use then digit and for generated words. This can be done using recursion. Lets we the program to implement the concept using recursion. Live Demo #include <iostream> #include <string.h> using namespace std; const char keypad[10][5] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; void printWords(int number[], int curr_digit, char output[], int n){ int i; if (curr_digit == n){ cout<<output<<" "; return ; } for (i=0; i<strlen(keypad[number[curr_digit]]); i++){ output[curr_digit] = keypad[number[curr_digit]][i]; printWords(number, curr_digit+1, output, n); if (number[curr_digit] == 0 || number[curr_digit] == 1) return; } } int main(void){ int number[] = {6,8,7}; cout<<"The output character formed is : \n"; int n = sizeof(number)/sizeof(number[0]); char result[n+1]; result[n] ='\0'; printWords(number, 0, result, n); return 0; } The output character formed is − mtp mtq mtr mts mup muq mur mus mvp mvq mvr mvs ntp ntq ntr nts nup nuq nur nus nvp nvq nvr nvs otp otq otr ots oup ouq our ous ovp ovq ovr ovs
[ { "code": null, "e": 1212, "s": 1062, "text": "In this problem, we are given a number and we have to print all words that can be formed by pressing those words in an old fashioned mobile keyboard." }, { "code": null, "e": 1542, "s": 1212, "text": "We are quite familiar with the QWERTY keyboard style that we use today. But before the invention of QWERTY keypad phones were fitted with keypads with 12 buttons and each button contains words and numbers both. Like they word 6 on the keypad will contain words “MNO” which will be typed by clicking one, twice or thrice the keys." }, { "code": null, "e": 1572, "s": 1542, "text": "The keypad looked like this −" }, { "code": null, "e": 1760, "s": 1572, "text": "In these keywords also all words are present and the user can type then. So, in\nthis problem, we will be print all possible words that can be generated using\nthe number sequence is given." }, { "code": null, "e": 1817, "s": 1760, "text": "Let’s take an example to understand the problem better −" }, { "code": null, "e": 2016, "s": 1817, "text": "Input: 687\nOutput: MTP, MTQ, MTR, MTR, MUP, MUQ, MUR, MUS, MVP, MVQ,\nMVR, MVR, NTP, NTQ, NTR, NTR, NUP, NUQ, NUR, NUS, NVP, NVQ,\nNVR, NVR, OTP, OTQ, OTR, OTR, OUP, OUQ, OUR, OUS, OVP, OVQ,\nOVR, OVR." }, { "code": null, "e": 2368, "s": 2016, "text": "To solve this problem, let’s see the pattern that is made in the above example. Each button has its own associated characters and we will have to\nuse those while typing. So, for each number, there are at max 4 options(in\ncase of 7 and 9). For this, we can fix on digit and then use then digit and for\ngenerated words. This can be done using recursion." }, { "code": null, "e": 2430, "s": 2368, "text": "Lets we the program to implement the concept using recursion." }, { "code": null, "e": 2441, "s": 2430, "text": " Live Demo" }, { "code": null, "e": 3227, "s": 2441, "text": "#include <iostream>\n#include <string.h>\nusing namespace std;\nconst char keypad[10][5] = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\",\n\"pqrs\", \"tuv\", \"wxyz\"};\nvoid printWords(int number[], int curr_digit, char output[], int n){\n int i;\n if (curr_digit == n){\n cout<<output<<\" \";\n return ;\n }\n for (i=0; i<strlen(keypad[number[curr_digit]]); i++){\n output[curr_digit] = keypad[number[curr_digit]][i];\n printWords(number, curr_digit+1, output, n);\n if (number[curr_digit] == 0 || number[curr_digit] == 1)\n return;\n }\n}\nint main(void){\n int number[] = {6,8,7};\n cout<<\"The output character formed is : \\n\";\n int n = sizeof(number)/sizeof(number[0]);\n char result[n+1];\n result[n] ='\\0';\n printWords(number, 0, result, n);\n return 0;\n}" }, { "code": null, "e": 3260, "s": 3227, "text": "The output character formed is −" }, { "code": null, "e": 3404, "s": 3260, "text": "mtp mtq mtr mts mup muq mur mus mvp mvq mvr mvs ntp ntq ntr nts\nnup nuq nur nus nvp nvq nvr nvs otp otq otr ots oup ouq our ous ovp\novq ovr ovs" } ]
Recreating Gapminder Animation in 2 lines of Python with Plotly Express | by AbdulMajedRaja RS | Towards Data Science
Disclaimer: A new moduleplotly_express is used, Gapminder Animation not coded from scratch using 2 lines It’s one of the iconic moments of Data Visualization when Hans Rosling presented the famous Gapminder Animation in his TED talk which is one of the most viewed TED talks ever. Since then, It’s been like a benchmark for anyone who does visualization to replicate it to show their Data Visualization prowess — much like replicating Edward Tufte’s or Nate Silver’s visualization pieces. Very recently Plotly (who’s known for their Interactive Visualization DSL for R and Python) came up with a new tool/module/library called Plotly Express. As the name suggests, the primary objective of plotly express is to be a high-level API that’s insanely simple, fast and easy to use to build Interactive Visualizations. Much more like this, Plotly Express:Plotly.py :: Seaborn:Matplotlib Inspired by ggplot2 of R and seaborn of Python, having simplicity at its core plotly express attempts to do things in one-liners . In this piece, We’ll see how to recreate (If not entirely, at least similar to) the iconic Gapminder animation using just plotly express . pip3 install plotly_express import plotly_express as px px.scatter(px.data.gapminder(), x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country", size="pop", color="country", hover_name="country", log_x = True, size_max=45, range_x=[100,100000], range_y=[25,90]) That’s a pretty simplistic function (I’ve ever seen to do this Gapminder Animation). The function px.scatter() gets the data from px.data.gapminder() and then typically, defining x and y axis along with the animation_frame that gets incremented for every year. With a few more arguments for cosmetic improvements, the Animated Bubble Chart is ready! Plotly Express Tutorial Video to build Gapminder Animation: FIN The objective of this post is to spread out the word about plotly_express which is nothing short of amazing to create beautiful interactive visualization (also similar to highcharter in R). If you want a course of Plotly in general, Check out Datacamp. Complete Code used in this Post A very comprehensive intro to Plotly Express
[ { "code": null, "e": 277, "s": 172, "text": "Disclaimer: A new moduleplotly_express is used, Gapminder Animation not coded from scratch using 2 lines" }, { "code": null, "e": 661, "s": 277, "text": "It’s one of the iconic moments of Data Visualization when Hans Rosling presented the famous Gapminder Animation in his TED talk which is one of the most viewed TED talks ever. Since then, It’s been like a benchmark for anyone who does visualization to replicate it to show their Data Visualization prowess — much like replicating Edward Tufte’s or Nate Silver’s visualization pieces." }, { "code": null, "e": 985, "s": 661, "text": "Very recently Plotly (who’s known for their Interactive Visualization DSL for R and Python) came up with a new tool/module/library called Plotly Express. As the name suggests, the primary objective of plotly express is to be a high-level API that’s insanely simple, fast and easy to use to build Interactive Visualizations." }, { "code": null, "e": 1006, "s": 985, "text": "Much more like this," }, { "code": null, "e": 1053, "s": 1006, "text": "Plotly Express:Plotly.py :: Seaborn:Matplotlib" }, { "code": null, "e": 1323, "s": 1053, "text": "Inspired by ggplot2 of R and seaborn of Python, having simplicity at its core plotly express attempts to do things in one-liners . In this piece, We’ll see how to recreate (If not entirely, at least similar to) the iconic Gapminder animation using just plotly express ." }, { "code": null, "e": 1351, "s": 1323, "text": "pip3 install plotly_express" }, { "code": null, "e": 1379, "s": 1351, "text": "import plotly_express as px" }, { "code": null, "e": 1639, "s": 1379, "text": "px.scatter(px.data.gapminder(), x=\"gdpPercap\", y=\"lifeExp\", animation_frame=\"year\", animation_group=\"country\", size=\"pop\", color=\"country\", hover_name=\"country\", log_x = True, size_max=45, range_x=[100,100000], range_y=[25,90])" }, { "code": null, "e": 1989, "s": 1639, "text": "That’s a pretty simplistic function (I’ve ever seen to do this Gapminder Animation). The function px.scatter() gets the data from px.data.gapminder() and then typically, defining x and y axis along with the animation_frame that gets incremented for every year. With a few more arguments for cosmetic improvements, the Animated Bubble Chart is ready!" }, { "code": null, "e": 2049, "s": 1989, "text": "Plotly Express Tutorial Video to build Gapminder Animation:" }, { "code": null, "e": 2053, "s": 2049, "text": "FIN" }, { "code": null, "e": 2306, "s": 2053, "text": "The objective of this post is to spread out the word about plotly_express which is nothing short of amazing to create beautiful interactive visualization (also similar to highcharter in R). If you want a course of Plotly in general, Check out Datacamp." }, { "code": null, "e": 2338, "s": 2306, "text": "Complete Code used in this Post" } ]
MySQL - ROLLBACK TO SAVEPOINT Statement
The SAVEPOINT statement is used to set a save point for the transaction with the specified name. If a save point with the given name already exists the old one will be deleted. The ROLLBACK TO SAVEPOINT statement is similar to ROLLBACK except it undoes all the changes done by the current transaction to the last named save point. This statement doesnot terminates the transaction but it just reverts the modifications. This statement also deletes all the savepoints created after the specified savepoint (to which the changes are being reverted). When you invoke this statement if there is no savepoint with the given name an error will be generated. Following is the syntax of the MySQL RELEASE SAVEPOINT Statement − ROLLBACK [WORK] TO [SAVEPOINT] identifier Assume we have created a table using the CREATE statement as shown below − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME VARCHAR(20), LAST_NAME VARCHAR(20), AGE INT, INCOME INT); If we have a .csv file, and an .xml file with the following contents − data.xml − <rowgt; <FIRST_NAMEgt;Javed</FIRST_NAMEgt; <LAST_NAMEgt;Syed</LAST_NAMEgt; <AGEgt;25</AGEgt; <INCOMEgt;9855</INCOMEgt; </rowgt; <rowgt; <FIRST_NAMEgt;Abhinav</FIRST_NAMEgt; <LAST_NAMEgt;Gomatam</LAST_NAMEgt; <AGEgt;30</AGEgt; <INCOMEgt;7000</INCOMEgt; </rowgt; data.csv − 'Krishna','Sharma',19,2000 'Raj','Kandukuri',20,7000 Following MySQL transaction tries to insert contents of these files in to the table − START TRANSACTION; LOAD DATA INFILE "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/data.csv" into table employee FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'; SAVEPOINT mysavepoint; load xml infile "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/data.xml" into table employee ROWS IDENTIFIED BY '<row>'; If you verify the contents of the above table, you can observe all the inserted records as − mysql> SELECT * FROM EMPLOYEE; +------------+-------------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | INCOME | +------------+-------------+------+--------+ | 'Krishna' | 'Sharma' | 19 | 2000 | | 'Raj' | 'Kandukuri' | 20 | 7000 | | Javed | Syed | 25 | 9855 | | Abhinav | Gomatam | 30 | 7000 | +------------+-------------+------+--------+ 4 rows in set (0.00 sec) Following statement reverts the changes made to the last savepoint − mysql> ROLLBACK TO SAVEPOINT mysavepoint; After this if you verify the contents, you can observe only two records − mysql> select * FROM EMPLOYEE; +------------+-------------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | INCOME | +------------+-------------+------+--------+ | 'Krishna' | 'Sharma' | 19 | 2000 | | 'Raj' | 'Kandukuri' | 20 | 7000 | +------------+-------------+------+--------+ 2 rows in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2510, "s": 2333, "text": "The SAVEPOINT statement is used to set a save point for the transaction with the specified name. If a save point with the given name already exists the old one will be deleted." }, { "code": null, "e": 2753, "s": 2510, "text": "The ROLLBACK TO SAVEPOINT statement is similar to ROLLBACK except it undoes all the changes done by the current transaction to the last named save point. This statement doesnot terminates the transaction but it just reverts the modifications." }, { "code": null, "e": 2881, "s": 2753, "text": "This statement also deletes all the savepoints created after the specified savepoint (to which the changes are being reverted)." }, { "code": null, "e": 2985, "s": 2881, "text": "When you invoke this statement if there is no savepoint with the given name an error will be generated." }, { "code": null, "e": 3052, "s": 2985, "text": "Following is the syntax of the MySQL RELEASE SAVEPOINT Statement −" }, { "code": null, "e": 3095, "s": 3052, "text": "ROLLBACK [WORK] TO [SAVEPOINT] identifier\n" }, { "code": null, "e": 3170, "s": 3095, "text": "Assume we have created a table using the CREATE statement as shown below −" }, { "code": null, "e": 3281, "s": 3170, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME VARCHAR(20),\n LAST_NAME VARCHAR(20),\n AGE INT,\n INCOME INT);" }, { "code": null, "e": 3352, "s": 3281, "text": "If we have a .csv file, and an .xml file with the following contents −" }, { "code": null, "e": 3363, "s": 3352, "text": "data.xml −" }, { "code": null, "e": 3649, "s": 3363, "text": "<rowgt;\n <FIRST_NAMEgt;Javed</FIRST_NAMEgt;\n <LAST_NAMEgt;Syed</LAST_NAMEgt;\n <AGEgt;25</AGEgt;\n <INCOMEgt;9855</INCOMEgt;\n</rowgt;\n<rowgt;\n <FIRST_NAMEgt;Abhinav</FIRST_NAMEgt;\n <LAST_NAMEgt;Gomatam</LAST_NAMEgt; \n <AGEgt;30</AGEgt;\n <INCOMEgt;7000</INCOMEgt;\n</rowgt;" }, { "code": null, "e": 3660, "s": 3649, "text": "data.csv −" }, { "code": null, "e": 3714, "s": 3660, "text": "'Krishna','Sharma',19,2000\n'Raj','Kandukuri',20,7000\n" }, { "code": null, "e": 3800, "s": 3714, "text": "Following MySQL transaction tries to insert contents of these files in to the table −" }, { "code": null, "e": 4117, "s": 3800, "text": "START TRANSACTION;\n\nLOAD DATA INFILE \"C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/data.csv\" into table employee\n FIELDS TERMINATED BY ','\n LINES TERMINATED BY '\\n';\n\nSAVEPOINT mysavepoint;\n\nload xml infile \"C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/data.xml\" into table employee ROWS IDENTIFIED BY '<row>';" }, { "code": null, "e": 4210, "s": 4117, "text": "If you verify the contents of the above table, you can observe all the inserted records as −" }, { "code": null, "e": 4626, "s": 4210, "text": "mysql> SELECT * FROM EMPLOYEE;\n+------------+-------------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | INCOME |\n+------------+-------------+------+--------+\n| 'Krishna' | 'Sharma' | 19 | 2000 |\n| 'Raj' | 'Kandukuri' | 20 | 7000 |\n| Javed | Syed | 25 | 9855 |\n| Abhinav | Gomatam | 30 | 7000 |\n+------------+-------------+------+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 4695, "s": 4626, "text": "Following statement reverts the changes made to the last savepoint −" }, { "code": null, "e": 4737, "s": 4695, "text": "mysql> ROLLBACK TO SAVEPOINT mysavepoint;" }, { "code": null, "e": 4811, "s": 4737, "text": "After this if you verify the contents, you can observe only two records −" }, { "code": null, "e": 5137, "s": 4811, "text": "mysql> select * FROM EMPLOYEE;\n+------------+-------------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | INCOME |\n+------------+-------------+------+--------+\n| 'Krishna' | 'Sharma' | 19 | 2000 |\n| 'Raj' | 'Kandukuri' | 20 | 7000 |\n+------------+-------------+------+--------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 5170, "s": 5137, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5198, "s": 5170, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5233, "s": 5198, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5250, "s": 5233, "text": " Frahaan Hussain" }, { "code": null, "e": 5284, "s": 5250, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5319, "s": 5284, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5353, "s": 5319, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 5381, "s": 5353, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5414, "s": 5381, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 5434, "s": 5414, "text": " Harshit Srivastava" }, { "code": null, "e": 5467, "s": 5434, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 5485, "s": 5467, "text": " Trevoir Williams" }, { "code": null, "e": 5492, "s": 5485, "text": " Print" }, { "code": null, "e": 5503, "s": 5492, "text": " Add Notes" } ]
How to Recover Deleted Files Using Foremost in Linux? - GeeksforGeeks
17 Nov, 2020 Foremost is a digital forensic application that is used to recover lost or deleted files. Foremost can recover the files for hard disk, memory card, pen drive, and another mode of memory devices easily. It can also work on the image files that are being generated by any other Application. It is a free command-line tool that is pre-installed in Kali Linux. This tool comes pre-installed in Kali Linux. Foremost is a very useful software that is used to recover the deleted files, if some files are deleted accidentally or in any case files are deleted. You can recover the deleted files from foremost only if the data in the device is not overridden, which means after deleting the files no more data is added to the storage device because in that case data may be overridden and the chances of recovery also get reduced and data must get corrupted. Installing the Foremost Tool: Use the following command to install this tool in any Debian based Linux Operating System or in any other Operating System using the APT package manager. sudo apt install foremost Use the following command to install this tool using dnf package manager sudo dnf install foremost Use the following command to install this tool using Pacman package manager or in Arch Linux. sudo pacman -S foremost Syntax: foremost [options] Here you can check the options available and their functions. Let us now see how to recover deleted files using foremost: Recovering from USB/Hard Disk: Connect the External memory storage with the system. First, you need to know the path of your external memory device, for that use the command fdisk -l Now from here, you can copy the path of the disk. After copying the device path, now we have to recover the files from that device. Use the options available by the “foremost -h” command. For example : foremost -t jpg,pdf,mp4,exe -v -q -i /dev/sdb2 -o /root/desktop/recover Here I use this command to recover the data from the device. -t: It is the type of files we want to recover. Here I want to recover jpg, pdf,mp4, and exe files. -q: It is a quick scan for the device -i: It means the input as in this case external memory. -o: It is the output folder, where to save the recovered files. Hereafter running this command, all the files will be saved in the folder name as mentioned. Here you can see the folder recover on desktop and all the files will be stored here. Technical Scripter 2020 Linux-Unix Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Named Pipe or FIFO with example C program Thread functions in C/C++ SED command in Linux | Set 2 Array Basics in Shell Scripting | Set 1 Introduction to Linux Shell and Shell Scripting How to Find the Wi-Fi Password Using CMD in Windows? Setting up the environment in Java How to setup cron jobs in Ubuntu How to Run a Python Script using Docker? Running Python script on GPU.
[ { "code": null, "e": 24350, "s": 24322, "text": "\n17 Nov, 2020" }, { "code": null, "e": 25201, "s": 24350, "text": "Foremost is a digital forensic application that is used to recover lost or deleted files. Foremost can recover the files for hard disk, memory card, pen drive, and another mode of memory devices easily. It can also work on the image files that are being generated by any other Application. It is a free command-line tool that is pre-installed in Kali Linux. This tool comes pre-installed in Kali Linux. Foremost is a very useful software that is used to recover the deleted files, if some files are deleted accidentally or in any case files are deleted. You can recover the deleted files from foremost only if the data in the device is not overridden, which means after deleting the files no more data is added to the storage device because in that case data may be overridden and the chances of recovery also get reduced and data must get corrupted." }, { "code": null, "e": 25231, "s": 25201, "text": "Installing the Foremost Tool:" }, { "code": null, "e": 25385, "s": 25231, "text": "Use the following command to install this tool in any Debian based Linux Operating System or in any other Operating System using the APT package manager." }, { "code": null, "e": 25412, "s": 25385, "text": "sudo apt install foremost\n" }, { "code": null, "e": 25485, "s": 25412, "text": "Use the following command to install this tool using dnf package manager" }, { "code": null, "e": 25512, "s": 25485, "text": "sudo dnf install foremost\n" }, { "code": null, "e": 25606, "s": 25512, "text": "Use the following command to install this tool using Pacman package manager or in Arch Linux." }, { "code": null, "e": 25631, "s": 25606, "text": "sudo pacman -S foremost\n" }, { "code": null, "e": 25639, "s": 25631, "text": "Syntax:" }, { "code": null, "e": 25659, "s": 25639, "text": "foremost [options]\n" }, { "code": null, "e": 25782, "s": 25659, "text": "Here you can check the options available and their functions. Let us now see how to recover deleted files using foremost: " }, { "code": null, "e": 25813, "s": 25782, "text": "Recovering from USB/Hard Disk:" }, { "code": null, "e": 25866, "s": 25813, "text": "Connect the External memory storage with the system." }, { "code": null, "e": 25956, "s": 25866, "text": "First, you need to know the path of your external memory device, for that use the command" }, { "code": null, "e": 25966, "s": 25956, "text": "fdisk -l\n" }, { "code": null, "e": 26016, "s": 25966, "text": "Now from here, you can copy the path of the disk." }, { "code": null, "e": 26098, "s": 26016, "text": "After copying the device path, now we have to recover the files from that device." }, { "code": null, "e": 26154, "s": 26098, "text": "Use the options available by the “foremost -h” command." }, { "code": null, "e": 26169, "s": 26154, "text": "For example : " }, { "code": null, "e": 26242, "s": 26169, "text": "foremost -t jpg,pdf,mp4,exe -v -q -i /dev/sdb2 -o /root/desktop/recover\n" }, { "code": null, "e": 26303, "s": 26242, "text": "Here I use this command to recover the data from the device." }, { "code": null, "e": 26403, "s": 26303, "text": "-t: It is the type of files we want to recover. Here I want to recover jpg, pdf,mp4, and exe files." }, { "code": null, "e": 26441, "s": 26403, "text": "-q: It is a quick scan for the device" }, { "code": null, "e": 26497, "s": 26441, "text": "-i: It means the input as in this case external memory." }, { "code": null, "e": 26561, "s": 26497, "text": "-o: It is the output folder, where to save the recovered files." }, { "code": null, "e": 26740, "s": 26561, "text": "Hereafter running this command, all the files will be saved in the folder name as mentioned. Here you can see the folder recover on desktop and all the files will be stored here." }, { "code": null, "e": 26764, "s": 26740, "text": "Technical Scripter 2020" }, { "code": null, "e": 26775, "s": 26764, "text": "Linux-Unix" }, { "code": null, "e": 26794, "s": 26775, "text": "Technical Scripter" }, { "code": null, "e": 26803, "s": 26794, "text": "TechTips" }, { "code": null, "e": 26901, "s": 26803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26910, "s": 26901, "text": "Comments" }, { "code": null, "e": 26923, "s": 26910, "text": "Old Comments" }, { "code": null, "e": 26965, "s": 26923, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 26991, "s": 26965, "text": "Thread functions in C/C++" }, { "code": null, "e": 27020, "s": 26991, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27060, "s": 27020, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 27108, "s": 27060, "text": "Introduction to Linux Shell and Shell Scripting" }, { "code": null, "e": 27161, "s": 27108, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 27196, "s": 27161, "text": "Setting up the environment in Java" }, { "code": null, "e": 27229, "s": 27196, "text": "How to setup cron jobs in Ubuntu" }, { "code": null, "e": 27270, "s": 27229, "text": "How to Run a Python Script using Docker?" } ]
RatingBar in Kotlin - GeeksforGeeks
02 Feb, 2022 Android RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allow users to give the rating by clicking on the stars. In RatingBar, we can set the step size using android:stepSize and it will always return a rating value as floating point number such as 1.0, 2.0, 2.5 etc. By using, android:numStars attribute we can specify the number of stars in RatingBar. RatingBar is used to get ratings form users or customers about the product, movie or hotel experience etc. RatingBar can be created manually or programmatically but we are going to discuss manually. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this file, we add RatingBar and button in the LinearLayout. Also set attributes for both of the widgets like id, stepSize, background etc. xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical" android:gravity ="center"> <RatingBar android:id="@+id/rBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:stepSize="0.5" android:theme="@style/Widget.AppCompat.RatingBar" android:background="@color/colorPrimary" android:numStars="4"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submit Rating" /> </LinearLayout> Name of the application can be put in strings.xml file xml <resources> <string name="app_name">RatingkBarInKotlin</string></resources> First, we will declare the variable rBar to access the Rating using the id like val rBar = findViewById<RatingBar>(R.id.rBar) then, declare another variable button and access the button using its id. val button = findViewById<Button>(R.id.button) In the end, to display toast msg while submitting the ratings we code like this button?.setOnClickListener { val msg = rBar.rating.toString() Toast.makeText(this@MainActivity, "Rating is: "+msg, Toast.LENGTH_SHORT).show() Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.RatingBarimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val rBar = findViewById<RatingBar>(R.id.rBar) if (rBar != null) { val button = findViewById<Button>(R.id.button) button?.setOnClickListener { val msg = rBar.rating.toString() Toast.makeText(this@MainActivity, "Rating is: "+msg, Toast.LENGTH_SHORT).show() } } }} xml <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest> ayushpandey3july Android-Bars Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Content Providers in Android with Example Services in Android with Example Android UI Layouts Android RecyclerView in Kotlin
[ { "code": null, "e": 23947, "s": 23919, "text": "\n02 Feb, 2022" }, { "code": null, "e": 24187, "s": 23947, "text": "Android RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allow users to give the rating by clicking on the stars." }, { "code": null, "e": 24535, "s": 24187, "text": "In RatingBar, we can set the step size using android:stepSize and it will always return a rating value as floating point number such as 1.0, 2.0, 2.5 etc. By using, android:numStars attribute we can specify the number of stars in RatingBar. RatingBar is used to get ratings form users or customers about the product, movie or hotel experience etc." }, { "code": null, "e": 24627, "s": 24535, "text": "RatingBar can be created manually or programmatically but we are going to discuss manually." }, { "code": null, "e": 24687, "s": 24627, "text": "First we create a new project by following the below steps:" }, { "code": null, "e": 24896, "s": 24687, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 24936, "s": 24896, "text": "Click on File, then New => New Project." }, { "code": null, "e": 24993, "s": 24936, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 25058, "s": 24993, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 25108, "s": 25058, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 25250, "s": 25108, "text": "In this file, we add RatingBar and button in the LinearLayout. Also set attributes for both of the widgets like id, stepSize, background etc." }, { "code": null, "e": 25254, "s": 25250, "text": "xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/container\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:orientation=\"vertical\" android:gravity =\"center\"> <RatingBar android:id=\"@+id/rBar\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:stepSize=\"0.5\" android:theme=\"@style/Widget.AppCompat.RatingBar\" android:background=\"@color/colorPrimary\" android:numStars=\"4\"/> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Submit Rating\" /> </LinearLayout>", "e": 26111, "s": 25254, "text": null }, { "code": null, "e": 26166, "s": 26111, "text": "Name of the application can be put in strings.xml file" }, { "code": null, "e": 26170, "s": 26166, "text": "xml" }, { "code": "<resources> <string name=\"app_name\">RatingkBarInKotlin</string></resources>", "e": 26249, "s": 26170, "text": null }, { "code": null, "e": 26329, "s": 26249, "text": "First, we will declare the variable rBar to access the Rating using the id like" }, { "code": null, "e": 26375, "s": 26329, "text": "val rBar = findViewById<RatingBar>(R.id.rBar)" }, { "code": null, "e": 26449, "s": 26375, "text": "then, declare another variable button and access the button using its id." }, { "code": null, "e": 26496, "s": 26449, "text": "val button = findViewById<Button>(R.id.button)" }, { "code": null, "e": 26576, "s": 26496, "text": "In the end, to display toast msg while submitting the ratings we code like this" }, { "code": null, "e": 26738, "s": 26576, "text": "button?.setOnClickListener {\n val msg = rBar.rating.toString()\n Toast.makeText(this@MainActivity,\n \"Rating is: \"+msg, Toast.LENGTH_SHORT).show()\n" }, { "code": null, "e": 26745, "s": 26738, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.RatingBarimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val rBar = findViewById<RatingBar>(R.id.rBar) if (rBar != null) { val button = findViewById<Button>(R.id.button) button?.setOnClickListener { val msg = rBar.rating.toString() Toast.makeText(this@MainActivity, \"Rating is: \"+msg, Toast.LENGTH_SHORT).show() } } }}", "e": 27507, "s": 26745, "text": null }, { "code": null, "e": 27511, "s": 27507, "text": "xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>", "e": 28166, "s": 27511, "text": null }, { "code": null, "e": 28185, "s": 28168, "text": "ayushpandey3july" }, { "code": null, "e": 28198, "s": 28185, "text": "Android-Bars" }, { "code": null, "e": 28213, "s": 28198, "text": "Kotlin Android" }, { "code": null, "e": 28221, "s": 28213, "text": "Android" }, { "code": null, "e": 28228, "s": 28221, "text": "Kotlin" }, { "code": null, "e": 28236, "s": 28228, "text": "Android" }, { "code": null, "e": 28334, "s": 28236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28343, "s": 28334, "text": "Comments" }, { "code": null, "e": 28356, "s": 28343, "text": "Old Comments" }, { "code": null, "e": 28399, "s": 28356, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28457, "s": 28399, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 28490, "s": 28457, "text": "Services in Android with Example" }, { "code": null, "e": 28532, "s": 28490, "text": "Content Providers in Android with Example" }, { "code": null, "e": 28563, "s": 28532, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 28606, "s": 28563, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28648, "s": 28606, "text": "Content Providers in Android with Example" }, { "code": null, "e": 28681, "s": 28648, "text": "Services in Android with Example" }, { "code": null, "e": 28700, "s": 28681, "text": "Android UI Layouts" } ]
How to compare string and number in Python?
Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers). When you order a numeric and a non-numeric type, the numeric type comes first. If you have a number in a str object, you can simply convert it to a float or an int using their respective constructors. For example, i = 100 j = "12" int_j = int(j) print(int_j < i) This will give the output: True
[ { "code": null, "e": 1387, "s": 1062, "text": "Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers)." }, { "code": null, "e": 1466, "s": 1387, "text": "When you order a numeric and a non-numeric type, the numeric type comes first." }, { "code": null, "e": 1601, "s": 1466, "text": "If you have a number in a str object, you can simply convert it to a float or an int using their respective constructors. For example," }, { "code": null, "e": 1650, "s": 1601, "text": "i = 100\nj = \"12\"\nint_j = int(j)\nprint(int_j < i)" }, { "code": null, "e": 1677, "s": 1650, "text": "This will give the output:" }, { "code": null, "e": 1682, "s": 1677, "text": "True" } ]
D3.js - Working Example
Let us perform an animated bar chart in this chapter. For this example, we take the data.csv file used in the previous chapter of the population records as dataset and generate an animated bar chart. To do this, we need to perform the following steps − Step 1 − Apply styles − Apply CSS styles using the coding given below. <style> .bar { fill: green; } .highlight { fill: red; } .title { fill: blue; font-weight: bold; } </style> Step 2 − Define variables − Let us define the SVG attributes using the script below. <script> var svg = d3.select("svg"), margin = 200, width = svg.attr("width") - margin, height = svg.attr("height") - margin; </script> Step 3 − Append text − Now, append text and apply the transformation using the coding below. svg.append("text") .attr("transform", "translate(100,0)") .attr("x", 50) .attr("y", 50) .attr("font-size", "20px") .attr("class", "title") .text("Population bar chart") Step 4 − Create scale range − In this step, we can create a scale range and append the group elements. It is defined below. var x = d3.scaleBand().range([0, width]).padding(0.4), y = d3.scaleLinear() .range([height, 0]); var g = svg.append("g") .attr("transform", "translate(" + 100 + "," + 100 + ")"); Step 5 − Read data − We have already created the data.csv file in our previous examples. The same file, we have used here. year,population 2006,40 2008,45 2010,48 2012,51 2014,53 2016,57 2017,62 Now, read the above file using the code below. d3.csv("data.csv", function(error, data) { if (error) { throw error; } Step 6 − Set domain − Now, set the domain using the coding below. x.domain(data.map(function(d) { return d.year; })); y.domain([0, d3.max(data, function(d) { return d.population; })]); Step 7 − Add X-axis − Now, you can add the X-axis to the transformation. It is shown below. g.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)).append("text") .attr("y", height - 250).attr("x", width - 100) .attr("text-anchor", "end").attr("font-size", "18px") .attr("stroke", "blue").text("year"); Step 8 − Add Y-axis − Add the Y-axis to the transformation using the code given below. g.append("g") .append("text").attr("transform", "rotate(-90)") .attr("y", 6).attr("dy", "-5.1em") .attr("text-anchor", "end").attr("font-size", "18px") .attr("stroke", "blue").text("population"); Step 9 − Append group elements − Now, append the group elements and apply transformation to Y-axis as defined below. g.append("g") .attr("transform", "translate(0, 0)") .call(d3.axisLeft(y)) Step 10 − Select the bar class − Now, select all the elements in the bar class as defined below. g.selectAll(".bar") .data(data).enter() .append("rect") .attr("class", "bar") .on("mouseover", onMouseOver) .on("mouseout", onMouseOut) .attr("x", function(d) { return x(d.year); }) .attr("y", function(d) { return y(d.population); }) .attr("width", x.bandwidth()) .transition() .ease(d3.easeLinear) .duration(200) .delay(function (d, i) { return i * 25; }) .attr("height", function(d) { return height - y(d.population); }); }); Here, we added the listener event for the mouseout and mouseover to perform animation. It applies the animation, when the mouse hovers over a particular bar and goes out of it. These functions are explained in the following step. The .ease(d3.easeLinear) function is used to perform apparent motion in animation. It processes the slow-in and the slow-out motion with a duration of 200. The delay can be calculated using − .delay(function (d, i) { return i * 25; }) Step 11 − Mouseover event handler function − Let us create a mouseover event handler to handle a mouse event as shown below. function onMouseOver(d, i) { d3.select(this) .attr('class', 'highlight'); d3.select(this) .transition() .duration(200) .attr('width', x.bandwidth() + 5) .attr("y", function(d) { return y(d.population) - 10; }) .attr("height", function(d) { return height - y(d.population) + 10; }); g.append("text") .attr('class', 'val') .attr('x', function() { return x(d.year); }) .attr('y', function() { return y(d.value) - 10; }) } Here, in the mouseover event, we want to increase the bar width and height, and the bar color of the selected bar to red. For the color, we have added a class ‘highlight’, which changes the color of the selected bar to red. A transition function to the bar for the duration of 200 milliseconds. When we increase the width of the bar by 5px, and the height by 10px, the transition from the previous width and height of the bar to the new width and height will be for the duration of 200 milliseconds. Next, we calculated a new ‘y’ value to the bar, so that the bar does not distort due to the new height value. Step 12 − Mouseout event handler function − Let us create a mouseout event handler to handle a mouse event. It is defined below. function onMouseOut(d, i) { d3.select(this).attr('class', 'bar'); d3.select(this) .transition() .duration(400).attr('width', x.bandwidth()) .attr("y", function(d) { return y(d.population); }) .attr("height", function(d) { return height - y(d.population); }); d3.selectAll('.val') .remove() } Here, in the mouseout event, we want to remove the selection features that we had applied in the mouseover event. Therefore, we revert the bar class to the original ‘bar’ class and restore the original width and height of the selected bar and restore the y value to the original value. The d3.selectAll(‘.val’).remove() function is used to remove the text value we had added during the bar selection. Step 13 − Working Example − The complete program is given in the following code block. Create a webpage animated_bar.html and add the following changes to it. <!DOCTYPE html> <html> <head> <style> .bar { fill: green; } .highlight { fill: red; } .title { fill: blue; font-weight: bold; } </style> <script src = "https://d3js.org/d3.v4.min.js"></script> <title> Animated bar chart </title> </head> <body> <svg width = "500" height = "500"></svg> <script> var svg = d3.select("svg"), margin = 200, width = svg.attr("width") - margin, height = svg.attr("height") - margin; svg.append("text") .attr("transform", "translate(100,0)") .attr("x", 50).attr("y", 50) .attr("font-size", "20px") .attr("class", "title") .text("Population bar chart") var x = d3.scaleBand().range([0, width]).padding(0.4), y = d3.scaleLinear().range([height, 0]); var g = svg.append("g") .attr("transform", "translate(" + 100 + "," + 100 + ")"); d3.csv("data.csv", function(error, data) { if (error) { throw error; } x.domain(data.map(function(d) { return d.year; })); y.domain([0, d3.max(data, function(d) { return d.population; })]); g.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) .append("text") .attr("y", height - 250) .attr("x", width - 100) .attr("text-anchor", "end") .attr("font-size", "18px") .attr("stroke", "blue").text("year"); g.append("g") .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "-5.1em") .attr("text-anchor", "end") .attr("font-size", "18px") .attr("stroke", "blue") .text("population"); g.append("g") .attr("transform", "translate(0, 0)") .call(d3.axisLeft(y)) g.selectAll(".bar") .data(data) .enter() .append("rect") .attr("class", "bar") .on("mouseover", onMouseOver) .on("mouseout", onMouseOut) .attr("x", function(d) { return x(d.year); }) .attr("y", function(d) { return y(d.population); }) .attr("width", x.bandwidth()).transition() .ease(d3.easeLinear).duration(200) .delay(function (d, i) { return i * 25; }) .attr("height", function(d) { return height - y(d.population); }); }); function onMouseOver(d, i) { d3.select(this) .attr('class', 'highlight'); d3.select(this) .transition() .duration(200) .attr('width', x.bandwidth() + 5) .attr("y", function(d) { return y(d.population) - 10; }) .attr("height", function(d) { return height - y(d.population) + 10; }); g.append("text") .attr('class', 'val') .attr('x', function() { return x(d.year); }) .attr('y', function() { return y(d.value) - 10; }) } function onMouseOut(d, i) { d3.select(this) .attr('class', 'bar'); d3.select(this) .transition() .duration(200) .attr('width', x.bandwidth()) .attr("y", function(d) { return y(d.population); }) .attr("height", function(d) { return height - y(d.population); }); d3.selectAll('.val') .remove() } </script> </body> </html> Now, request the browser and we will see the following response. If we select any bar, it will be highlighted in red color. D3 is a general-purpose visualization library that deals with the transformation of data into information, documents, elements, etc., and ultimately helps in creating data visualization. Print Add Notes Bookmark this page
[ { "code": null, "e": 2330, "s": 2130, "text": "Let us perform an animated bar chart in this chapter. For this example, we take the data.csv file used in the previous chapter of the population records as dataset and generate an animated bar chart." }, { "code": null, "e": 2383, "s": 2330, "text": "To do this, we need to perform the following steps −" }, { "code": null, "e": 2454, "s": 2383, "text": "Step 1 − Apply styles − Apply CSS styles using the coding given below." }, { "code": null, "e": 2611, "s": 2454, "text": "<style>\n .bar {\n fill: green;\n }\n \n .highlight {\n fill: red;\n }\n \n .title {\n fill: blue;\n font-weight: bold;\n }\n</style>" }, { "code": null, "e": 2696, "s": 2611, "text": "Step 2 − Define variables − Let us define the SVG attributes using the script below." }, { "code": null, "e": 2840, "s": 2696, "text": "<script>\n var svg = d3.select(\"svg\"), margin = 200,\n width = svg.attr(\"width\") - margin,\n height = svg.attr(\"height\") - margin;\n</script>" }, { "code": null, "e": 2933, "s": 2840, "text": "Step 3 − Append text − Now, append text and apply the transformation using the coding below." }, { "code": null, "e": 3120, "s": 2933, "text": "svg.append(\"text\")\n .attr(\"transform\", \"translate(100,0)\")\n .attr(\"x\", 50)\n .attr(\"y\", 50)\n .attr(\"font-size\", \"20px\")\n .attr(\"class\", \"title\")\n .text(\"Population bar chart\")" }, { "code": null, "e": 3244, "s": 3120, "text": "Step 4 − Create scale range − In this step, we can create a scale range and append the group elements. It is defined below." }, { "code": null, "e": 3441, "s": 3244, "text": "var x = d3.scaleBand().range([0, width]).padding(0.4),\n y = d3.scaleLinear()\n .range([height, 0]);\n var g = svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + 100 + \",\" + 100 + \")\");" }, { "code": null, "e": 3564, "s": 3441, "text": "Step 5 − Read data − We have already created the data.csv file in our previous examples. The same file, we have used here." }, { "code": null, "e": 3636, "s": 3564, "text": "year,population\n2006,40\n2008,45\n2010,48\n2012,51\n2014,53\n2016,57\n2017,62" }, { "code": null, "e": 3683, "s": 3636, "text": "Now, read the above file using the code below." }, { "code": null, "e": 3766, "s": 3683, "text": "d3.csv(\"data.csv\", function(error, data) {\n if (error) {\n throw error;\n }" }, { "code": null, "e": 3832, "s": 3766, "text": "Step 6 − Set domain − Now, set the domain using the coding below." }, { "code": null, "e": 3951, "s": 3832, "text": "x.domain(data.map(function(d) { return d.year; }));\ny.domain([0, d3.max(data, function(d) { return d.population; })]);" }, { "code": null, "e": 4043, "s": 3951, "text": "Step 7 − Add X-axis − Now, you can add the X-axis to the transformation. It is shown below." }, { "code": null, "e": 4301, "s": 4043, "text": "g.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(d3.axisBottom(x)).append(\"text\")\n .attr(\"y\", height - 250).attr(\"x\", width - 100)\n .attr(\"text-anchor\", \"end\").attr(\"font-size\", \"18px\")\n .attr(\"stroke\", \"blue\").text(\"year\");" }, { "code": null, "e": 4388, "s": 4301, "text": "Step 8 − Add Y-axis − Add the Y-axis to the transformation using the code given below." }, { "code": null, "e": 4596, "s": 4388, "text": "g.append(\"g\")\n .append(\"text\").attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 6).attr(\"dy\", \"-5.1em\")\n .attr(\"text-anchor\", \"end\").attr(\"font-size\", \"18px\")\n .attr(\"stroke\", \"blue\").text(\"population\");" }, { "code": null, "e": 4713, "s": 4596, "text": "Step 9 − Append group elements − Now, append the group elements and apply transformation to Y-axis as defined below." }, { "code": null, "e": 4793, "s": 4713, "text": "g.append(\"g\")\n .attr(\"transform\", \"translate(0, 0)\")\n .call(d3.axisLeft(y))" }, { "code": null, "e": 4890, "s": 4793, "text": "Step 10 − Select the bar class − Now, select all the elements in the bar class as defined below." }, { "code": null, "e": 5367, "s": 4890, "text": "g.selectAll(\".bar\")\n .data(data).enter()\n .append(\"rect\")\n .attr(\"class\", \"bar\")\n .on(\"mouseover\", onMouseOver) \n .on(\"mouseout\", onMouseOut)\n .attr(\"x\", function(d) { return x(d.year); })\n .attr(\"y\", function(d) { return y(d.population); })\n .attr(\"width\", x.bandwidth())\n .transition()\n .ease(d3.easeLinear)\n .duration(200)\n .delay(function (d, i) {\n return i * 25;\n })\n .attr(\"height\", function(d) { return height - y(d.population); });\n});" }, { "code": null, "e": 5597, "s": 5367, "text": "Here, we added the listener event for the mouseout and mouseover to perform animation. It applies the animation, when the mouse hovers over a particular bar and goes out of it. These functions are explained in the following step." }, { "code": null, "e": 5789, "s": 5597, "text": "The .ease(d3.easeLinear) function is used to perform apparent motion in animation. It processes the slow-in and the slow-out motion with a duration of 200. The delay can be calculated using −" }, { "code": null, "e": 5835, "s": 5789, "text": ".delay(function (d, i) {\n return i * 25;\n})" }, { "code": null, "e": 5960, "s": 5835, "text": "Step 11 − Mouseover event handler function − Let us create a mouseover event handler to handle a mouse event as shown below." }, { "code": null, "e": 6463, "s": 5960, "text": "function onMouseOver(d, i) {\n d3.select(this)\n .attr('class', 'highlight');\n d3.select(this)\n .transition()\n .duration(200)\n .attr('width', x.bandwidth() + 5)\n .attr(\"y\", function(d) { return y(d.population) - 10; })\n .attr(\"height\", function(d) { return height - y(d.population) + 10; });\n g.append(\"text\")\n .attr('class', 'val') \n \n .attr('x', function() {\n return x(d.year);\n })\n \n .attr('y', function() {\n return y(d.value) - 10;\n })\n}" }, { "code": null, "e": 6687, "s": 6463, "text": "Here, in the mouseover event, we want to increase the bar width and height, and the bar color of the selected bar to red. For the color, we have added a class ‘highlight’, which changes the color of the selected bar to red." }, { "code": null, "e": 6963, "s": 6687, "text": "A transition function to the bar for the duration of 200 milliseconds. When we increase the width of the bar by 5px, and the height by 10px, the transition from the previous width and height of the bar to the new width and height will be for the duration of 200 milliseconds." }, { "code": null, "e": 7073, "s": 6963, "text": "Next, we calculated a new ‘y’ value to the bar, so that the bar does not distort due to the new height value." }, { "code": null, "e": 7202, "s": 7073, "text": "Step 12 − Mouseout event handler function − Let us create a mouseout event handler to handle a mouse event. It is defined below." }, { "code": null, "e": 7546, "s": 7202, "text": "function onMouseOut(d, i) {\n d3.select(this).attr('class', 'bar');\n \n d3.select(this)\n .transition() \n .duration(400).attr('width', x.bandwidth())\n .attr(\"y\", function(d) { return y(d.population); })\n .attr(\"height\", function(d) { return height - y(d.population); });\n \n d3.selectAll('.val')\n .remove()\n}" }, { "code": null, "e": 7832, "s": 7546, "text": "Here, in the mouseout event, we want to remove the selection features that we had applied in the mouseover event. Therefore, we revert the bar class to the original ‘bar’ class and restore the original width and height of the selected bar and restore the y value to the original value." }, { "code": null, "e": 7947, "s": 7832, "text": "The d3.selectAll(‘.val’).remove() function is used to remove the text value we had added during the bar selection." }, { "code": null, "e": 8106, "s": 7947, "text": "Step 13 − Working Example − The complete program is given in the following code block. Create a webpage animated_bar.html and add the following changes to it." }, { "code": null, "e": 12331, "s": 8106, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .bar {\n fill: green;\n }\n \n .highlight {\n fill: red;\n }\n \n .title {\n fill: blue;\n font-weight: bold;\n }\n </style>\n <script src = \"https://d3js.org/d3.v4.min.js\"></script>\n <title> Animated bar chart </title>\n </head>\n\n <body>\n <svg width = \"500\" height = \"500\"></svg>\n <script>\n var svg = d3.select(\"svg\"),\n margin = 200, width = svg.attr(\"width\") - margin,\n height = svg.attr(\"height\") - margin;\n \n svg.append(\"text\")\n .attr(\"transform\", \"translate(100,0)\")\n .attr(\"x\", 50).attr(\"y\", 50)\n .attr(\"font-size\", \"20px\")\n .attr(\"class\", \"title\")\n .text(\"Population bar chart\")\n \n var x = d3.scaleBand().range([0, width]).padding(0.4),\n y = d3.scaleLinear().range([height, 0]);\n \n var g = svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + 100 + \",\" + 100 + \")\");\n\n d3.csv(\"data.csv\", function(error, data) {\n if (error) {\n throw error;\n }\n \n x.domain(data.map(function(d) { return d.year; }));\n y.domain([0, d3.max(data, function(d) { return d.population; })]);\n \n g.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(d3.axisBottom(x))\n .append(\"text\")\n .attr(\"y\", height - 250)\n .attr(\"x\", width - 100)\n .attr(\"text-anchor\", \"end\")\n .attr(\"font-size\", \"18px\")\n .attr(\"stroke\", \"blue\").text(\"year\");\n \n g.append(\"g\")\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 6)\n .attr(\"dy\", \"-5.1em\")\n .attr(\"text-anchor\", \"end\")\n .attr(\"font-size\", \"18px\")\n .attr(\"stroke\", \"blue\")\n .text(\"population\");\n \n g.append(\"g\")\n .attr(\"transform\", \"translate(0, 0)\")\n .call(d3.axisLeft(y))\n\n g.selectAll(\".bar\")\n .data(data)\n .enter()\n .append(\"rect\")\n .attr(\"class\", \"bar\")\n .on(\"mouseover\", onMouseOver) \n .on(\"mouseout\", onMouseOut) \n .attr(\"x\", function(d) { return x(d.year); })\n .attr(\"y\", function(d) { return y(d.population); })\n .attr(\"width\", x.bandwidth()).transition()\n .ease(d3.easeLinear).duration(200)\n .delay(function (d, i) {\n return i * 25;\n })\n \n .attr(\"height\", function(d) { return height - y(d.population); });\n });\n \n \n function onMouseOver(d, i) {\n d3.select(this)\n .attr('class', 'highlight');\n \n d3.select(this)\n .transition() \n .duration(200)\n .attr('width', x.bandwidth() + 5)\n .attr(\"y\", function(d) { return y(d.population) - 10; })\n .attr(\"height\", function(d) { return height - y(d.population) + 10; });\n \n g.append(\"text\")\n .attr('class', 'val')\n .attr('x', function() {\n return x(d.year);\n })\n \n .attr('y', function() {\n return y(d.value) - 10;\n })\n }\n \n function onMouseOut(d, i) {\n \n d3.select(this)\n .attr('class', 'bar');\n \n d3.select(this)\n .transition() \n .duration(200)\n .attr('width', x.bandwidth())\n .attr(\"y\", function(d) { return y(d.population); })\n .attr(\"height\", function(d) { return height - y(d.population); });\n \n d3.selectAll('.val')\n .remove()\n }\n </script>\n </body>\n</html>" }, { "code": null, "e": 12396, "s": 12331, "text": "Now, request the browser and we will see the following response." }, { "code": null, "e": 12642, "s": 12396, "text": "If we select any bar, it will be highlighted in red color. D3 is a general-purpose visualization library that deals with the transformation of data into information, documents, elements, etc., and ultimately helps in creating data visualization." }, { "code": null, "e": 12649, "s": 12642, "text": " Print" }, { "code": null, "e": 12660, "s": 12649, "text": " Add Notes" } ]
3 Tools to Track and Visualize the Execution of your Python Code | by Khuyen Tran | Towards Data Science
Have you ever seen an error output like below: 2 divided by 1 is equal to 2.0.Traceback (most recent call last): File "loguru_example.py", line 17, in <module> divide_numbers(num_list) File "loguru_example.py", line 11, in divide_numbers res = division(num1, num2) File "loguru_example.py", line 5, in division return num1/num2ZeroDivisionError: division by zero and wish the output can be a little bit easier to understand as shown here? You might also want to visualize which lines of code are being executed and how many times they are executed in real-time: If so, this article will give you the tools to do exactly the above. Those 3 tools are: Loguru — print better exceptions snoop — print the lines of code being executed in a function heartrate — visualize the execution of a Python program in real-time And all it takes to use these tools is one line of code! Loguru is a library that aims to make logging in Python enjoyable. Loguru provides many interesting functionalities, but one functionality that I found to be the most helpful is the ability to catch unexpected errors and display which value of a variable causes your code to fail. To install Loguru, type pip install loguru To understand how Loguru can be useful, imagine that you have 2 functions division and divide_numbersand the function divide_numbers is executed. Note that combinations([2,1,0], 2) returns [(2, 1), (2, 0), (1, 0)] . After running the code above, we get this error: 2 divided by 1 is equal to 2.0.Traceback (most recent call last): File "loguru_example.py", line 17, in <module> divide_numbers(num_list) File "loguru_example.py", line 11, in divide_numbers res = division(num1, num2) File "loguru_example.py", line 5, in division return num1/num2ZeroDivisionError: division by zero From the output, we know that the line return num1/num2 is where the error occurs, but we don’t know which values of num1 and num2 cause the error. Luckily, this can be easily tracked by adding Loguru’s logger.catch decorator: Output: By adding logger.catch, the exceptions are much easier to understand! It turns out that the error occurs when dividing 2 by 0. What if there is no error in the code, but we want to figure out what is going on in the code? That is when snoop comes in handy. snoop is a Python package that prints the lines of code being executed along with the values of each variable by adding only one decorator. To install snoop, type: pip install snoop Let’s imagine we have a function calledfactorial that finds the factorial of an integer. Output: The factorial of 5 is 120 To understand why the output of factorial(5) is 20 , we can add snoop decorator to the function factorial . Output: In the output above, we can view the values of the variables and which lines of code are executed. Now we can understand how recursion works much better! If you want to visualize which lines are executed and how many times they are executed, try heartrate. heartrate is also created by the creator of snoop. To install heartrate, type: pip install heartrate Now let’s add heartrate.trace(browser=True) to our previous code. This will open a browser window displaying the visualization of the file where trace() was called. A new browser should pop up when you run the code above. If not, go to http://localhost:9999. You should see the output like below: Cool! The bars show the lines that have been hit. The longer bars mean more hits, lighter colors mean more recent. From the output above, we can see that the program executes: if x==1 5 times return 1 once return (x * factorial(x-1)) 4 times The output makes sense since the initial value of x is 5 and the function is called repetitively until x equals to 1 . Now let’s see what it is like to visualize the execution of a Python program in real-time using heartrate. Let’s add sleep(0.5) so that the program runs a little bit slower and increase num to 20 . Awesome! We can see which lines of code are being executed and how many times each of them has been executed in real-time. Congratulations! You have just learned 3 tools to track and visualize the execution of your Python code. I hope debugging will be less painful for you when using these 3 tools. Since these tools only require one line of code, why not give them a try to see how helpful they are? Feel free to play and fork the source code of this article here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 219, "s": 172, "text": "Have you ever seen an error output like below:" }, { "code": null, "e": 547, "s": 219, "text": "2 divided by 1 is equal to 2.0.Traceback (most recent call last): File \"loguru_example.py\", line 17, in <module> divide_numbers(num_list) File \"loguru_example.py\", line 11, in divide_numbers res = division(num1, num2) File \"loguru_example.py\", line 5, in division return num1/num2ZeroDivisionError: division by zero" }, { "code": null, "e": 623, "s": 547, "text": "and wish the output can be a little bit easier to understand as shown here?" }, { "code": null, "e": 746, "s": 623, "text": "You might also want to visualize which lines of code are being executed and how many times they are executed in real-time:" }, { "code": null, "e": 834, "s": 746, "text": "If so, this article will give you the tools to do exactly the above. Those 3 tools are:" }, { "code": null, "e": 867, "s": 834, "text": "Loguru — print better exceptions" }, { "code": null, "e": 928, "s": 867, "text": "snoop — print the lines of code being executed in a function" }, { "code": null, "e": 997, "s": 928, "text": "heartrate — visualize the execution of a Python program in real-time" }, { "code": null, "e": 1054, "s": 997, "text": "And all it takes to use these tools is one line of code!" }, { "code": null, "e": 1335, "s": 1054, "text": "Loguru is a library that aims to make logging in Python enjoyable. Loguru provides many interesting functionalities, but one functionality that I found to be the most helpful is the ability to catch unexpected errors and display which value of a variable causes your code to fail." }, { "code": null, "e": 1359, "s": 1335, "text": "To install Loguru, type" }, { "code": null, "e": 1378, "s": 1359, "text": "pip install loguru" }, { "code": null, "e": 1524, "s": 1378, "text": "To understand how Loguru can be useful, imagine that you have 2 functions division and divide_numbersand the function divide_numbers is executed." }, { "code": null, "e": 1643, "s": 1524, "text": "Note that combinations([2,1,0], 2) returns [(2, 1), (2, 0), (1, 0)] . After running the code above, we get this error:" }, { "code": null, "e": 1971, "s": 1643, "text": "2 divided by 1 is equal to 2.0.Traceback (most recent call last): File \"loguru_example.py\", line 17, in <module> divide_numbers(num_list) File \"loguru_example.py\", line 11, in divide_numbers res = division(num1, num2) File \"loguru_example.py\", line 5, in division return num1/num2ZeroDivisionError: division by zero" }, { "code": null, "e": 2198, "s": 1971, "text": "From the output, we know that the line return num1/num2 is where the error occurs, but we don’t know which values of num1 and num2 cause the error. Luckily, this can be easily tracked by adding Loguru’s logger.catch decorator:" }, { "code": null, "e": 2206, "s": 2198, "text": "Output:" }, { "code": null, "e": 2333, "s": 2206, "text": "By adding logger.catch, the exceptions are much easier to understand! It turns out that the error occurs when dividing 2 by 0." }, { "code": null, "e": 2463, "s": 2333, "text": "What if there is no error in the code, but we want to figure out what is going on in the code? That is when snoop comes in handy." }, { "code": null, "e": 2603, "s": 2463, "text": "snoop is a Python package that prints the lines of code being executed along with the values of each variable by adding only one decorator." }, { "code": null, "e": 2627, "s": 2603, "text": "To install snoop, type:" }, { "code": null, "e": 2645, "s": 2627, "text": "pip install snoop" }, { "code": null, "e": 2734, "s": 2645, "text": "Let’s imagine we have a function calledfactorial that finds the factorial of an integer." }, { "code": null, "e": 2742, "s": 2734, "text": "Output:" }, { "code": null, "e": 2768, "s": 2742, "text": "The factorial of 5 is 120" }, { "code": null, "e": 2876, "s": 2768, "text": "To understand why the output of factorial(5) is 20 , we can add snoop decorator to the function factorial ." }, { "code": null, "e": 2884, "s": 2876, "text": "Output:" }, { "code": null, "e": 3038, "s": 2884, "text": "In the output above, we can view the values of the variables and which lines of code are executed. Now we can understand how recursion works much better!" }, { "code": null, "e": 3141, "s": 3038, "text": "If you want to visualize which lines are executed and how many times they are executed, try heartrate." }, { "code": null, "e": 3220, "s": 3141, "text": "heartrate is also created by the creator of snoop. To install heartrate, type:" }, { "code": null, "e": 3242, "s": 3220, "text": "pip install heartrate" }, { "code": null, "e": 3407, "s": 3242, "text": "Now let’s add heartrate.trace(browser=True) to our previous code. This will open a browser window displaying the visualization of the file where trace() was called." }, { "code": null, "e": 3539, "s": 3407, "text": "A new browser should pop up when you run the code above. If not, go to http://localhost:9999. You should see the output like below:" }, { "code": null, "e": 3654, "s": 3539, "text": "Cool! The bars show the lines that have been hit. The longer bars mean more hits, lighter colors mean more recent." }, { "code": null, "e": 3715, "s": 3654, "text": "From the output above, we can see that the program executes:" }, { "code": null, "e": 3731, "s": 3715, "text": "if x==1 5 times" }, { "code": null, "e": 3745, "s": 3731, "text": "return 1 once" }, { "code": null, "e": 3781, "s": 3745, "text": "return (x * factorial(x-1)) 4 times" }, { "code": null, "e": 3900, "s": 3781, "text": "The output makes sense since the initial value of x is 5 and the function is called repetitively until x equals to 1 ." }, { "code": null, "e": 4098, "s": 3900, "text": "Now let’s see what it is like to visualize the execution of a Python program in real-time using heartrate. Let’s add sleep(0.5) so that the program runs a little bit slower and increase num to 20 ." }, { "code": null, "e": 4221, "s": 4098, "text": "Awesome! We can see which lines of code are being executed and how many times each of them has been executed in real-time." }, { "code": null, "e": 4500, "s": 4221, "text": "Congratulations! You have just learned 3 tools to track and visualize the execution of your Python code. I hope debugging will be less painful for you when using these 3 tools. Since these tools only require one line of code, why not give them a try to see how helpful they are?" }, { "code": null, "e": 4565, "s": 4500, "text": "Feel free to play and fork the source code of this article here:" }, { "code": null, "e": 4576, "s": 4565, "text": "github.com" }, { "code": null, "e": 4736, "s": 4576, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Basic Linear Programming in Python with PuLP | by Rahul Banerjee | Towards Data Science
A basic Linear Programming problem is where we are given multiple equations. The value of one of the equations has to be maximized or minimized while the other equations are constraints. In high school, we used to plot the equations on a graph, shade the feasible region and find the value of the equation to be maximized or minimized by substituting the variables with the verticle values of the shaded region. I briefly go over this technique in the first part of the tutorial I will be dividing the tutorial into two parts A brief overview of Linear Programming Using PuLP to solve an optimization problem Linear Programming is used to solve Optimization problems given a few constraints. An example problem is below: We have two models of a car, Car A and Car B. Car A gives us a profit of 20k and Car B gives us a profit of 45k The Designer takes 4 days to build Car A and 5 days to build Car B The Engineer takes 3 days to build Car A and 6 days to build Car B The Machine takes 2 days to build Car A and 7 days to build Car B The Designer, Engineer and Machine can all work for 30 days Getting High School Flashbacks? We need to maximize our Profits 💵 💵 The first point gives us our decision variables. The following point gives us our Objective Function which we need to maximize and the rest of the points give us our constraints. One way to solve it is to plot the equations on a graph, find the feasible area and then plug in the value of the vertices. Below is the feasible region shaded in green. The vertices are not necessarily integers and since we can not make cars in fractions, we can only accept integer solutions. Finding the integer solutions is not so trivial, we can not round up the vertice values and consider it a solution since we may violate some constraints in doing so. Using PuLP, we will be able to easily find the integral solutions PuLP is an open-source Python library used for Linear Programming. Documentation for the library can be found here. pip install pulp from pulp import * problem = LpProblem('Car Factory', LpMaximize) The first parameter is the name of our problem and the second parameter is the type of the Problem. We need to maximize our profits, therefore we use LpMaximize A = LpVariable('Car A', lowBound=0 , cat=LpInteger)B = LpVariable('Car B', lowBound=0 , cat=LpInteger) The first parameter is the name of the variable, the second parameter specifies the lower bound and third parameter specifies the type of the variable. The type can also be LpContinuous or LpBinary. We add the objective function and constraints to the instance of the LpProblem we created earlier. #Objective Functionproblem += 20000*A + 45000*B , 'Objective Function'#Constraintsproblem += 4*A + 5*B <= 30 , 'Designer Constraint'problem += 3*A + 6*B <=30, 'Engineer Constraint'problem += 2*A + 7*B <=30, 'Machine Constraint Upon printing the problem variable to the terminal we get the following output Car_Profit: MAXIMIZE 20000*Car_A + 45000*Car_B + 0 SUBJECT TO Designer_Constraint: 4 Car_A + 5 Car_B <= 30 Engineer_Constraint: 3 Car_A + 6 Car_B <= 30 Machine_Constraint: 2 Car_A + 7 Car_B <= 30 VARIABLES 0 <= Car_A Integer 0 <= Car_B Integer We can also use the status attribute to check the current Status of our problem. It is an integer value and we will need to use LpStatus to map it to a meaningful message print("Current Status: ", LpStatus[problem.status]) Current Status: Not Solved We will use the solve method to solve the problem. problem.solve()print("Number of Car A Made: ", A.varValue)print("Number of Car B Made: ", B.varValue)print("Total Profit: ", value(problem.objective)) The output is the following Number of Car A Made: 1.0Number of Car B Made: 4.0Total Profit: 200000.0 If you print the status now, you should get the following output Current Status: Optimal In just a few lines of code, we were able to maximize the profits by making more or Car B as compared to Car A. PuLP has many other interesting applications as well. A couple of them are listed below Sudoku Solver: Use Linear Programming to solve the famous Sudoku Puzzles towardsdatascience.com Diet Plan: Create a diet plan such that various constraints on calorie and nutrition intake are met while minimizing the cost I recently created a blog using WordPress, I would love it if you could check it out 😃 realpythonproject.com Connect with me on LinkedIn www.linkedin.com Originally published at https://realpythonproject.com on November 27, 2020.
[ { "code": null, "e": 651, "s": 172, "text": "A basic Linear Programming problem is where we are given multiple equations. The value of one of the equations has to be maximized or minimized while the other equations are constraints. In high school, we used to plot the equations on a graph, shade the feasible region and find the value of the equation to be maximized or minimized by substituting the variables with the verticle values of the shaded region. I briefly go over this technique in the first part of the tutorial" }, { "code": null, "e": 698, "s": 651, "text": "I will be dividing the tutorial into two parts" }, { "code": null, "e": 737, "s": 698, "text": "A brief overview of Linear Programming" }, { "code": null, "e": 781, "s": 737, "text": "Using PuLP to solve an optimization problem" }, { "code": null, "e": 893, "s": 781, "text": "Linear Programming is used to solve Optimization problems given a few constraints. An example problem is below:" }, { "code": null, "e": 939, "s": 893, "text": "We have two models of a car, Car A and Car B." }, { "code": null, "e": 1005, "s": 939, "text": "Car A gives us a profit of 20k and Car B gives us a profit of 45k" }, { "code": null, "e": 1072, "s": 1005, "text": "The Designer takes 4 days to build Car A and 5 days to build Car B" }, { "code": null, "e": 1139, "s": 1072, "text": "The Engineer takes 3 days to build Car A and 6 days to build Car B" }, { "code": null, "e": 1205, "s": 1139, "text": "The Machine takes 2 days to build Car A and 7 days to build Car B" }, { "code": null, "e": 1265, "s": 1205, "text": "The Designer, Engineer and Machine can all work for 30 days" }, { "code": null, "e": 1297, "s": 1265, "text": "Getting High School Flashbacks?" }, { "code": null, "e": 1333, "s": 1297, "text": "We need to maximize our Profits 💵 💵" }, { "code": null, "e": 1512, "s": 1333, "text": "The first point gives us our decision variables. The following point gives us our Objective Function which we need to maximize and the rest of the points give us our constraints." }, { "code": null, "e": 1636, "s": 1512, "text": "One way to solve it is to plot the equations on a graph, find the feasible area and then plug in the value of the vertices." }, { "code": null, "e": 1807, "s": 1636, "text": "Below is the feasible region shaded in green. The vertices are not necessarily integers and since we can not make cars in fractions, we can only accept integer solutions." }, { "code": null, "e": 2039, "s": 1807, "text": "Finding the integer solutions is not so trivial, we can not round up the vertice values and consider it a solution since we may violate some constraints in doing so. Using PuLP, we will be able to easily find the integral solutions" }, { "code": null, "e": 2155, "s": 2039, "text": "PuLP is an open-source Python library used for Linear Programming. Documentation for the library can be found here." }, { "code": null, "e": 2191, "s": 2155, "text": "pip install pulp from pulp import *" }, { "code": null, "e": 2238, "s": 2191, "text": "problem = LpProblem('Car Factory', LpMaximize)" }, { "code": null, "e": 2399, "s": 2238, "text": "The first parameter is the name of our problem and the second parameter is the type of the Problem. We need to maximize our profits, therefore we use LpMaximize" }, { "code": null, "e": 2502, "s": 2399, "text": "A = LpVariable('Car A', lowBound=0 , cat=LpInteger)B = LpVariable('Car B', lowBound=0 , cat=LpInteger)" }, { "code": null, "e": 2701, "s": 2502, "text": "The first parameter is the name of the variable, the second parameter specifies the lower bound and third parameter specifies the type of the variable. The type can also be LpContinuous or LpBinary." }, { "code": null, "e": 2800, "s": 2701, "text": "We add the objective function and constraints to the instance of the LpProblem we created earlier." }, { "code": null, "e": 3027, "s": 2800, "text": "#Objective Functionproblem += 20000*A + 45000*B , 'Objective Function'#Constraintsproblem += 4*A + 5*B <= 30 , 'Designer Constraint'problem += 3*A + 6*B <=30, 'Engineer Constraint'problem += 2*A + 7*B <=30, 'Machine Constraint" }, { "code": null, "e": 3106, "s": 3027, "text": "Upon printing the problem variable to the terminal we get the following output" }, { "code": null, "e": 3350, "s": 3106, "text": "Car_Profit: MAXIMIZE 20000*Car_A + 45000*Car_B + 0 SUBJECT TO Designer_Constraint: 4 Car_A + 5 Car_B <= 30 Engineer_Constraint: 3 Car_A + 6 Car_B <= 30 Machine_Constraint: 2 Car_A + 7 Car_B <= 30 VARIABLES 0 <= Car_A Integer 0 <= Car_B Integer" }, { "code": null, "e": 3521, "s": 3350, "text": "We can also use the status attribute to check the current Status of our problem. It is an integer value and we will need to use LpStatus to map it to a meaningful message" }, { "code": null, "e": 3600, "s": 3521, "text": "print(\"Current Status: \", LpStatus[problem.status]) Current Status: Not Solved" }, { "code": null, "e": 3651, "s": 3600, "text": "We will use the solve method to solve the problem." }, { "code": null, "e": 3802, "s": 3651, "text": "problem.solve()print(\"Number of Car A Made: \", A.varValue)print(\"Number of Car B Made: \", B.varValue)print(\"Total Profit: \", value(problem.objective))" }, { "code": null, "e": 3830, "s": 3802, "text": "The output is the following" }, { "code": null, "e": 3903, "s": 3830, "text": "Number of Car A Made: 1.0Number of Car B Made: 4.0Total Profit: 200000.0" }, { "code": null, "e": 3968, "s": 3903, "text": "If you print the status now, you should get the following output" }, { "code": null, "e": 3992, "s": 3968, "text": "Current Status: Optimal" }, { "code": null, "e": 4192, "s": 3992, "text": "In just a few lines of code, we were able to maximize the profits by making more or Car B as compared to Car A. PuLP has many other interesting applications as well. A couple of them are listed below" }, { "code": null, "e": 4265, "s": 4192, "text": "Sudoku Solver: Use Linear Programming to solve the famous Sudoku Puzzles" }, { "code": null, "e": 4288, "s": 4265, "text": "towardsdatascience.com" }, { "code": null, "e": 4414, "s": 4288, "text": "Diet Plan: Create a diet plan such that various constraints on calorie and nutrition intake are met while minimizing the cost" }, { "code": null, "e": 4501, "s": 4414, "text": "I recently created a blog using WordPress, I would love it if you could check it out 😃" }, { "code": null, "e": 4523, "s": 4501, "text": "realpythonproject.com" }, { "code": null, "e": 4551, "s": 4523, "text": "Connect with me on LinkedIn" }, { "code": null, "e": 4568, "s": 4551, "text": "www.linkedin.com" } ]
Explain the sorting techniques in C language
What are the different sorting techniques in C Language? Explain any one sorting technique with an example. C language provides five sorting techniques, which are as follows − Bubble sort (or) Exchange Sort. Selection sort. Insertion sort (or) Linear sort. Quick sort (or) Partition exchange sort. Merge Sort (or) External sort. It is the simplest sorting technique which is also called as an exchange sort. Compare the first element with the remaining elements in the list and exchange(swap) them if they are not in order. Compare the first element with the remaining elements in the list and exchange(swap) them if they are not in order. Repeat the same for other elements in the list until all the elements gets sorted. Repeat the same for other elements in the list until all the elements gets sorted. 30 50 40 10 20 Consider the elements given below − Compare first element with the remaining elements. a[0] > a[1] ◻ ◻30 >50 (F) ◻ ◻no exchange a[0] > a[2] ◻ ◻ 30 >40 (F) ◻ ◻ no exchange a[0] > a[3] ◻ ◻ 30 >10 (T) ◻ ◻ exchange a[0] > a[4] ◻ ◻ 10>20 (F) ◻ ◻ no exchange 10 50 40 30 20 Compare second element with the remaining elements. a[1] > a[2] ◻ ◻ 50 >40 (T) ◻ ◻ exchange a[1] > a[3] ◻ ◻ 40 >30 (T) ◻ ◻ exchange a[1] > a[4] ◻ ◻ 30 >20 (T) ◻ ◻ exchange 10 20 50 40 30 Compare third element with the remaining elements. a[2] > a[3] ◻ ◻ 50 >40 (T) ◻ ◻ exchange a[2] > a[4] ◻ ◻ 40 >30 (T) ◻ ◻ exchange 10 20 30 50 40 Compare fourth element with the remaining elements. a[3] > a[4] ◻ ◻ 50 >40 (T) ◻ ◻ exchange 10 20 30 40 50 Refer the procedure for bubble sort as given below − for (i=0; i<n-1; i++){ for (j=i+1; j<n; j++){ if (a[i] > a[j]){ t=a[i]; a[i] = a[j]; a[j] = t; } } } Following is the C program for bubble sorting technique − Live Demo #include<stdio.h> int main(){ int a[50], i,j,n,t; printf("enter the No: of elements in the list:\n"); scanf("%d", &n); printf("enter the elements:\n"); for(i=0; i<n; i++){ scanf ("%d", &a[i]); } printf("Before bubble sorting the elements are:\n"); for(i=0; i<n; i++) printf("%d \t\n", a[i]); for (i=0; i<n-1; i++){ for (j=i+1; j<n; j++){ if (a[i] > a[j]){ t = a[i]; a[i] = a[j]; a[j] = t; } } } printf ("after bubble sorting the elements are:\n"); for (i=0; i<n; i++) printf("%d\t", a[i]); return 0; } When the above program is executed, it produces the following result − enter the No: of elements in the list: 5 enter the elements: 12 11 45 26 67 Before bubble sorting the elements are: 12 11 45 26 67 after bubble sorting the elements are: 11 12 26 45 67
[ { "code": null, "e": 1170, "s": 1062, "text": "What are the different sorting techniques in C Language? Explain any one sorting technique with an example." }, { "code": null, "e": 1238, "s": 1170, "text": "C language provides five sorting techniques, which are as follows −" }, { "code": null, "e": 1270, "s": 1238, "text": "Bubble sort (or) Exchange Sort." }, { "code": null, "e": 1286, "s": 1270, "text": "Selection sort." }, { "code": null, "e": 1319, "s": 1286, "text": "Insertion sort (or) Linear sort." }, { "code": null, "e": 1360, "s": 1319, "text": "Quick sort (or) Partition exchange sort." }, { "code": null, "e": 1391, "s": 1360, "text": "Merge Sort (or) External sort." }, { "code": null, "e": 1470, "s": 1391, "text": "It is the simplest sorting technique which is also called as an exchange sort." }, { "code": null, "e": 1586, "s": 1470, "text": "Compare the first element with the remaining elements in the list and exchange(swap) them if they are not in order." }, { "code": null, "e": 1702, "s": 1586, "text": "Compare the first element with the remaining elements in the list and exchange(swap) them if they are not in order." }, { "code": null, "e": 1785, "s": 1702, "text": "Repeat the same for other elements in the list until all the elements gets sorted." }, { "code": null, "e": 1868, "s": 1785, "text": "Repeat the same for other elements in the list until all the elements gets sorted." }, { "code": null, "e": 1883, "s": 1868, "text": "30 50 40 10 20" }, { "code": null, "e": 1919, "s": 1883, "text": "Consider the elements given below −" }, { "code": null, "e": 1970, "s": 1919, "text": "Compare first element with the remaining elements." }, { "code": null, "e": 2011, "s": 1970, "text": "a[0] > a[1] ◻ ◻30 >50 (F) ◻ ◻no exchange" }, { "code": null, "e": 2054, "s": 2011, "text": "a[0] > a[2] ◻ ◻ 30 >40 (F) ◻ ◻ no exchange" }, { "code": null, "e": 2094, "s": 2054, "text": "a[0] > a[3] ◻ ◻ 30 >10 (T) ◻ ◻ exchange" }, { "code": null, "e": 2136, "s": 2094, "text": "a[0] > a[4] ◻ ◻ 10>20 (F) ◻ ◻ no exchange" }, { "code": null, "e": 2151, "s": 2136, "text": "10 50 40 30 20" }, { "code": null, "e": 2203, "s": 2151, "text": "Compare second element with the remaining elements." }, { "code": null, "e": 2243, "s": 2203, "text": "a[1] > a[2] ◻ ◻ 50 >40 (T) ◻ ◻ exchange" }, { "code": null, "e": 2283, "s": 2243, "text": "a[1] > a[3] ◻ ◻ 40 >30 (T) ◻ ◻ exchange" }, { "code": null, "e": 2323, "s": 2283, "text": "a[1] > a[4] ◻ ◻ 30 >20 (T) ◻ ◻ exchange" }, { "code": null, "e": 2338, "s": 2323, "text": "10 20 50 40 30" }, { "code": null, "e": 2389, "s": 2338, "text": "Compare third element with the remaining elements." }, { "code": null, "e": 2429, "s": 2389, "text": "a[2] > a[3] ◻ ◻ 50 >40 (T) ◻ ◻ exchange" }, { "code": null, "e": 2469, "s": 2429, "text": "a[2] > a[4] ◻ ◻ 40 >30 (T) ◻ ◻ exchange" }, { "code": null, "e": 2484, "s": 2469, "text": "10 20 30 50 40" }, { "code": null, "e": 2536, "s": 2484, "text": "Compare fourth element with the remaining elements." }, { "code": null, "e": 2576, "s": 2536, "text": "a[3] > a[4] ◻ ◻ 50 >40 (T) ◻ ◻ exchange" }, { "code": null, "e": 2591, "s": 2576, "text": "10 20 30 40 50" }, { "code": null, "e": 2644, "s": 2591, "text": "Refer the procedure for bubble sort as given below −" }, { "code": null, "e": 2790, "s": 2644, "text": "for (i=0; i<n-1; i++){\n for (j=i+1; j<n; j++){\n if (a[i] > a[j]){\n t=a[i];\n a[i] = a[j];\n a[j] = t;\n }\n }\n}" }, { "code": null, "e": 2848, "s": 2790, "text": "Following is the C program for bubble sorting technique −" }, { "code": null, "e": 2859, "s": 2848, "text": " Live Demo" }, { "code": null, "e": 3484, "s": 2859, "text": "#include<stdio.h>\nint main(){\n int a[50], i,j,n,t;\n printf(\"enter the No: of elements in the list:\\n\");\n scanf(\"%d\", &n);\n printf(\"enter the elements:\\n\");\n for(i=0; i<n; i++){\n scanf (\"%d\", &a[i]);\n }\n printf(\"Before bubble sorting the elements are:\\n\");\n for(i=0; i<n; i++)\n printf(\"%d \\t\\n\", a[i]);\n for (i=0; i<n-1; i++){\n for (j=i+1; j<n; j++){\n if (a[i] > a[j]){\n t = a[i];\n a[i] = a[j];\n a[j] = t;\n }\n }\n }\n printf (\"after bubble sorting the elements are:\\n\");\n for (i=0; i<n; i++)\n printf(\"%d\\t\", a[i]);\n return 0;\n}" }, { "code": null, "e": 3555, "s": 3484, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3740, "s": 3555, "text": "enter the No: of elements in the list:\n5\nenter the elements:\n12 11 45 26 67\nBefore bubble sorting the elements are:\n12\n11\n45\n26\n67\nafter bubble sorting the elements are:\n11 12 26 45 67" } ]
Apache Presto - Quick Guide
Data analytics is the process of analyzing raw data to gather relevant information for better decision making. It is primarily used in many organizations to make business decisions. Well, big data analytics involves a large amount of data and this process is quite complex, hence companies use different strategies. For example, Facebook is one of the leading data driven and largest data warehouse company in the world. Facebook warehouse data is stored in Hadoop for large scale computation. Later, when warehouse data grew to petabytes, they decided to develop a new system with low latency. In the year of 2012, Facebook team members designed “Presto” for interactive query analytics that would operate quickly even with petabytes of data. Apache Presto is a distributed parallel query execution engine, optimized for low latency and interactive query analysis. Presto runs queries easily and scales without down time even from gigabytes to petabytes. A single Presto query can process data from multiple sources like HDFS, MySQL, Cassandra, Hive and many more data sources. Presto is built in Java and easy to integrate with other data infrastructure components. Presto is powerful, and leading companies like Airbnb, DropBox, Groupon, Netflix are adopting it. Presto contains the following features − Simple and extensible architecture. Pluggable connectors - Presto supports pluggable connector to provide metadata and data for queries. Pipelined executions - Avoids unnecessary I/O latency overhead. User-defined functions - Analysts can create custom user-defined functions to migrate easily. Vectorized columnar processing. Here is a list of benefits that Apache Presto offers − Specialized SQL operations Easy to install and debug Simple storage abstraction Quickly scales petabytes data with low latency Presto supports most of today’s best industrial applications. Let’s take a look at some of the notable applications. Facebook − Facebook built Presto for data analytics needs. Presto easily scales large velocity of data. Facebook − Facebook built Presto for data analytics needs. Presto easily scales large velocity of data. Teradata − Teradata provides end-to-end solutions in Big Data analytics and data warehousing. Teradata contribution to Presto makes it easier for more companies to enable all analytical needs. Teradata − Teradata provides end-to-end solutions in Big Data analytics and data warehousing. Teradata contribution to Presto makes it easier for more companies to enable all analytical needs. Airbnb − Presto is an integral part of the Airbnb data infrastructure. Well, hundreds of employees are running queries each day with the technology. Airbnb − Presto is an integral part of the Airbnb data infrastructure. Well, hundreds of employees are running queries each day with the technology. Presto supports standard ANSI SQL which has made it very easy for data analysts and developers. Though it is built in Java, it avoids typical issues of Java code related to memory allocation and garbage collection. Presto has a connector architecture that is Hadoop friendly. It allows to easily plug in file systems. Presto runs on multiple Hadoop distributions. In addition, Presto can reach out from a Hadoop platform to query Cassandra, relational databases, or other data stores. This cross-platform analytic capability allows Presto users to extract maximum business value from gigabytes to petabytes of data. The architecture of Presto is almost similar to classic MPP (massively parallel processing) DBMS architecture. The following diagram illustrates the architecture of Presto. The above diagram consists of different components. Following table describes each of the component in detail. Client Client (Presto CLI) submits SQL statements to a coordinator to get the result. Coordinator Coordinator is a master daemon. The coordinator initially parses the SQL queries then analyzes and plans for the query execution. Scheduler performs pipeline execution, assigns work to the closest node and monitors progress. Connector Storage plugins are called as connectors. Hive, HBase, MySQL, Cassandra and many more act as a connector; otherwise you can also implement a custom one. The connector provides metadata and data for queries. The coordinator uses the connector to get metadata for building a query plan. Worker The coordinator assigns task to worker nodes. The workers get actual data from the connector. Finally, the worker node delivers result to the client. Presto is a distributed system that runs on a cluster of nodes. Presto’s distributed query engine is optimized for interactive analysis and supports standard ANSI SQL, including complex queries, aggregations, joins, and window functions. Presto architecture is simple and extensible. Presto client (CLI) submits SQL statements to a master daemon coordinator. The scheduler connects through execution pipeline. The scheduler assigns work to nodes which is closest to the data and monitors progress. The coordinator assigns task to multiple worker nodes and finally the worker node delivers the result back to the client. The client pulls data from the output process. Extensibility is the key design. Pluggable connectors like Hive, HBase, MySQL, etc., provides metadata and data for queries. Presto was designed with a “simple storage abstraction” that makes it easy to provide SQL query capability against these different kind of data sources. Presto supports custom query and execution engine with operators designed to support SQL semantics. In addition to improved scheduling, all processing is in memory and pipelined across the network between different stages. This avoids unnecessary I/O latency overhead. This chapter will explain how to install Presto on your machine. Let’s go through the basic requirements of Presto, Linux or Mac OS Java version 8 Now, let’s continue the following steps to install Presto on your machine. Hopefully, you have already installed Java version 8 on your machine right now, so you just verify it using the following command. $ java -version If Java is successfully installed on your machine, you could see the version of installed Java. If Java is not installed, follow the subsequent steps to install Java 8 on your machine. Download JDK. Download the latest version of JDK by visiting the following link. http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html The latest version is JDK 8u 92 and the file is “jdk-8u92-linux-x64.tar.gz”. Please download the file on your machine. After that, extract the files and move to the specific directory. Then set Java alternatives. Finally Java will be installed on your machine. Download the latest version of Presto by visiting the following link, https://repo1.maven.org/maven2/com/facebook/presto/presto-server/0.149/ Now the latest version of “presto-server-0.149.tar.gz” will be downloaded on your machine. Extract the tar file using the following command − $ tar -zxf presto-server-0.149.tar.gz $ cd presto-server-0.149 Create a data directory outside the installation directory, which will be used for storing logs, metadata, etc., so that it is to be easily preserved when upgrading Presto. It is defined using the following code − $ cd $ mkdir data To view the path where it is located, use the command “pwd”. This location will be assigned in the next node.properties file. Create an etc directory inside Presto installation directory using the following code − $ cd presto-server-0.149 $ mkdir etc This directory will hold configuration files. Let’s create each file one by one. Presto node properties file contains environmental configuration specific to each node. It is created inside etc directory (etc/node.properties) using the following code − $ cd etc $ vi node.properties node.environment = production node.id = ffffffff-ffff-ffff-ffff-ffffffffffff node.data-dir = /Users/../workspace/Presto After making all the changes, save the file, and quit the terminal. Here node.data is the location path of the above created data directory. node.id represents the unique identifier for each node. Create a file “jvm.config” inside etc directory (etc/jvm.config). This file contains a list of command line options used for launching the Java Virtual Machine. $ cd etc $ vi jvm.config -server -Xmx16G -XX:+UseG1GC -XX:G1HeapRegionSize = 32M -XX:+UseGCOverheadLimit -XX:+ExplicitGCInvokesConcurrent -XX:+HeapDumpOnOutOfMemoryError -XX:OnOutOfMemoryError = kill -9 %p After making all the changes, save the file, and quit the terminal. Create a file “config.properties” inside etc directory(etc/config.properties). This file contains the configuration of Presto server. If you are setting up a single machine for testing, Presto server can function only as the coordination process as defined using the following code − $ cd etc $ vi config.properties coordinator = true node-scheduler.include-coordinator = true http-server.http.port = 8080 query.max-memory = 5GB query.max-memory-per-node = 1GB discovery-server.enabled = true discovery.uri = http://localhost:8080 Here, coordinator − master node. coordinator − master node. node-scheduler.include-coordinator − Allows scheduling work on the coordinator. node-scheduler.include-coordinator − Allows scheduling work on the coordinator. http-server.http.port − Specifies the port for the HTTP server. http-server.http.port − Specifies the port for the HTTP server. query.max-memory=5GB − The maximum amount of distributed memory. query.max-memory=5GB − The maximum amount of distributed memory. query.max-memory-per-node=1GB − The maximum amount of memory per node. query.max-memory-per-node=1GB − The maximum amount of memory per node. discovery-server.enabled − Presto uses the Discovery service to find all the nodes in the cluster. discovery-server.enabled − Presto uses the Discovery service to find all the nodes in the cluster. discovery.uri − he URI to the Discovery server. discovery.uri − he URI to the Discovery server. If you are setting up multiple machine Presto server, Presto will function as both coordination and worker process. Use this configuration setting to test Presto server on multiple machines. $ cd etc $ vi config.properties coordinator = true node-scheduler.include-coordinator = false http-server.http.port = 8080 query.max-memory = 50GB query.max-memory-per-node = 1GB discovery-server.enabled = true discovery.uri = http://localhost:8080 $ cd etc $ vi config.properties coordinator = false http-server.http.port = 8080 query.max-memory = 50GB query.max-memory-per-node = 1GB discovery.uri = http://localhost:8080 Create a file “log.properties” inside etc directory(etc/log.properties). This file contains minimum log level for named logger hierarchies. It is defined using the following code − $ cd etc $ vi log.properties com.facebook.presto = INFO Save the file and quit the terminal. Here, four log levels are used such as DEBUG, INFO, WARN and ERROR. Default log level is INFO. Create a directory “catalog” inside etc directory(etc/catalog). This will be used for mounting data. For example, create etc/catalog/jmx.properties with the following contents to mount the jmx connector as the jmx catalog − $ cd etc $ mkdir catalog $ cd catalog $ vi jmx.properties connector.name = jmx Presto can be started using the following command, $ bin/launcher start Then you will see the response similar to this, Started as 840 To launch Presto server, use the following command − $ bin/launcher run After successfully launching Presto server, you can find log files in “var/log” directory. launcher.log − This log is created by the launcher and is connected to the stdout and stderr streams of the server. launcher.log − This log is created by the launcher and is connected to the stdout and stderr streams of the server. server.log − This is the main log file used by Presto. server.log − This is the main log file used by Presto. http-request.log − HTTP request received by the server. http-request.log − HTTP request received by the server. As of now, you have successfully installed Presto configuration settings on your machine. Let’s continue the steps to install Presto CLI. The Presto CLI provides a terminal-based interactive shell for running queries. Download the Presto CLI by visiting the following link, https://repo1.maven.org/maven2/com/facebook/presto/presto-cli/0.149/ Now “presto-cli-0.149-executable.jar” will be installed on your machine. After downloading the presto-cli, copy it to the location which you want to run it from. This location may be any node that has network access to the coordinator. First change the name of the Jar file to Presto. Then make it executable with chmod + x command using the following code − $ mv presto-cli-0.149-executable.jar presto $ chmod +x presto Now execute CLI using the following command, ./presto --server localhost:8080 --catalog jmx --schema default Here jmx(Java Management Extension) refers to catalog and default referes to schema. You will see the following response, presto:default> Now type “jps” command on your terminal and you will see the running daemons. After having performed all the executions, you can stop the presto server using the following command − $ bin/launcher stop This chapter will discuss the configuration settings for Presto. The Presto Verifier can be used to test Presto against another database (such as MySQL), or to test two Presto clusters against each other. Open MySQL server and create a database using the following command. create database test Now you have created “test” database in the server. Create the table and load it with the following query. CREATE TABLE verifier_queries( id INT NOT NULL AUTO_INCREMENT, suite VARCHAR(256) NOT NULL, name VARCHAR(256), test_catalog VARCHAR(256) NOT NULL, test_schema VARCHAR(256) NOT NULL, test_prequeries TEXT, test_query TEXT NOT NULL, test_postqueries TEXT, test_username VARCHAR(256) NOT NULL default 'verifier-test', test_password VARCHAR(256), control_catalog VARCHAR(256) NOT NULL, control_schema VARCHAR(256) NOT NULL, control_prequeries TEXT, control_query TEXT NOT NULL, control_postqueries TEXT, control_username VARCHAR(256) NOT NULL default 'verifier-test', control_password VARCHAR(256), session_properties_json TEXT, PRIMARY KEY (id) ); Create a properties file to configure the verifier − $ vi config.properties suite = mysuite query-database = jdbc:mysql://localhost:3306/tutorials?user=root&password=pwd control.gateway = jdbc:presto://localhost:8080 test.gateway = jdbc:presto://localhost:8080 thread-count = 1 Here, in the query-database field, enter the following details − mysql database name, user name, and password. Download Presto-verifier jar file by visiting the following link, https://repo1.maven.org/maven2/com/facebook/presto/presto-verifier/0.149/ Now the version “presto-verifier-0.149-executable.jar” is downloaded on your machine. Execute the JAR file using the following command, $ mv presto-verifier-0.149-executable.jar verifier $ chmod+x verifier Run the verifier using the following command, $ ./verifier config.properties Let’s create a simple table in “test” database using the following query. create table product(id int not null, name varchar(50)) After creating a table, insert two records using the following query, insert into product values(1,’Phone') insert into product values(2,’Television’) Execute the following sample query in the verifier terminal (./verifier config.propeties) to check the verifier result. insert into verifier_queries (suite, test_catalog, test_schema, test_query, control_catalog, control_schema, control_query) values ('mysuite', 'mysql', 'default', 'select * from mysql.test.product', 'mysql', 'default', 'select * from mysql.test.product'); Here, select * from mysql.test.product query refers to mysql catalog, test is database name and product is table name. In this way, you can access mysql connector using Presto server. Here, two same select queries are tested against each other to see the performance. Similarly, you can run other queries to test the performance results. You can also connect two Presto clusters to check the performance results. In this chapter, we will discuss the administration tools used in Presto. Let’s start with the Web Interface of Presto. Presto provides a web interface for monitoring and managing queries. It can be accessed from the port number specified in the coordinator Config Properties. Start Presto server and Presto CLI. Then you can access the web interface from the following url − http://localhost:8080/ The output will be similar to the above screen. Here, the main page has a list of queries along with information like unique query ID, query text, query state, percentage completed, username and source from which this query is originated. Latest queries are running first, then completed or not completed queries are displayed at the bottom. If Presto cluster is having any performance-related issues, change your default configuration settings to the following settings. task. info -refresh-max-wait − Reduces coordinator work load. task. info -refresh-max-wait − Reduces coordinator work load. task.max-worker-threads − Splits the process and assigns to each worker nodes. task.max-worker-threads − Splits the process and assigns to each worker nodes. distributed-joins-enabled − Hash-based distributed joins. distributed-joins-enabled − Hash-based distributed joins. node-scheduler.network-topology − Sets network topology to scheduler. node-scheduler.network-topology − Sets network topology to scheduler. Change your default JVM settings to the following settings. This will be helpful for diagnosing garbage collection issues. -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCCause -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+PrintGCDetails -XX:+PrintReferenceGC -XX:+PrintClassHistogramAfterFullGC -XX:+PrintClassHistogramBeforeFullGC -XX:PrintFLSStatistics = 2 -XX:+PrintAdaptiveSizePolicy -XX:+PrintSafepointStatistics -XX:PrintSafepointStatisticsCount = 1 In this chapter, we will discuss how to create and execute queries on Presto. Let us go through Presto supported basic data types. The following table describes the basic data types of Presto. VARCHAR Variable length character data BIGINT A 64-bit signed integer DOUBLE A 64-bit floating point double precision value DECIMAL A fixed precision decimal number. For example DECIMAL(10,3) - 10 is precision, i.e. total number of digits and 3 is scale value represented as fractional point. Scale is optional and default value is 0 BOOLEAN Boolean values true and false VARBINARY Variable length binary data JSON JSON data DATE Date data type represented as year-month-day TIME, TIMESTAMP, TIMESTAMP with TIME ZONE TIME - Time of the day (hour-min-sec-millisecond) TIMESTAMP - Date and time of the day TIMESTAMP with TIME ZONE - Date and time of the day with time zone from the value INTERVAL Stretch or extend date and time data types ARRAY Array of the given component type. For example, ARRAY[5,7] MAP Map between the given component types. For example, MAP(ARRAY[‘one’,’two’],ARRAY[5,7]) ROW Row structure made up of named fields Presto operators are listed in the following table. Presto supports arithmetic operators such as +, -, *, /, % <,>,<=,>=,=,<> AND, OR, NOT Range operator is used to test the value in a specific range. Presto supports BETWEEN, IS NULL, IS NOT NULL, GREATEST and LEAST Binary arithmetic decimal operator performs binary arithmetic operation for decimal type Unary decimal operator − The - operator performs negation The ‘||’ operator performs string concatenation Performs arithmetic addition and subtraction operations on date and time data types Subscript operator[] - access an element of an array Concatenation operator || - concatenate an array with an array or an element of the same type Map subscript operator [] - retrieve the value corresponding to a given key from a map As of now we were discussing running some simple basic queries on Presto. This chapter will discuss the important SQL functions. Math functions operate on mathematical formulas. Following table describes the list of functions in detail. Returns the absolute value of x Returns the cube root of x Returns the x value rounded up to the nearest integer ceil(x) Alias for ceiling(x) Returns the degree value for x Returns the double value for Euler’s number exp(x) Returns the exponent value for Euler’s number Returns x rounded down to the nearest integer from_base(string,radix) Returns the value of string interpreted as a base-radix number ln(x) Returns the natural logarithm of x Returns the base 2 logarithm of x log10(x) Returns the base 10 logarithm of x log(x,y) Returns the base y logarithm of x Returns the modulus (remainder) of n divided by m pi() Returns pi value. The result will be returned as a double value Returns power of value ‘p’ to the x value pow(x,p) Alias for power(x,p) converts the angle x in degree radians rand() Alias for radians() Returns the pseudo-random value rand(n) Alias for random() Returns the rounded value for x round(x,d) x value rounded for the ‘d’ decimal places sign(x) Returns the signum function of x, i.e., 0 if the argument is 0 1 if the argument is greater than 0 -1 if the argument is less than 0 For double arguments, the function additionally returns − NaN if the argument is NaN 1 if the argument is +Infinity -1 if the argument is -Infinity Returns the square root of x Return type is archer. The result is returned as the base radix for x Truncates the value for x Returns the bin number of x specified bound1 and bound2 bounds and n number of buckets Returns the bin number of x according to the bins specified by the array bins Trigonometric functions arguments are represented as radians(). Following table lists out the functions. Returns the inverse cosine value(x) asin(x) Returns the inverse sine value(x) atan(x) Returns the inverse tangent value(x) Returns the inverse tangent value(y/x) cos(x) Returns the cosine value(x) Returns the hyperbolic cosine value(x) Returns the sine value(x) tan(x) Returns the tangent value(x) tanh(x) Returns the hyperbolic tangent value(x) The following table lists out the Bitwise functions. Count the number of bits Perform bitwise AND operation for two bits, x and y Bitwise OR operation between two bits x, y Bitwise Not operation for bit x XOR operation for bits x, y Following table lists out the String functions. Concatenate the given strings Returns the length of the given string Returns the lowercase format for the string Returns the uppercase format for the given string Left padding for the given string Removes the leading whitespace from the string Replaces the string value Reverses the operation performed for the string Right padding for the given string Removes the trailing whitespace from the string Splits the string on delimiter and returns an array of size at the most limit Splits the string on delimiter and returns the field index Returns the starting position of the substring in the string Returns the substring for the given string Returns the substring for the given string with the specific length Removes the leading and trailing whitespace from the string Following table lists out the Date and Time functions. Returns the current date Returns the current time Returns the current timestamp Returns the current timezone Returns the current date,timestamp with the timezone Returns the local time Returns the local timestamp The following table lists out the Regular Expression functions. Returns the string matched by the regular expression for the pattern Returns the string matched by the regular expression for the pattern and the group Returns the first substring matched by the regular expression for the pattern Returns the first substring matched by the regular expression for the pattern and the group Returns the string matches for the pattern. If the string is returned, the value will be true otherwise false Replaces the instance of the string matched for the expression with the pattern Replace the instance of the string matched for the expression with the pattern and replacement Splits the regular expression for the given pattern The following table lists out JSON functions. Check the value exists in a json array. If the value exists it will return true, otherwise false Get the element for index in json array Returns the length in json array Returns the json structure format Parses the string as a json Returns the size of the value The following table lists out the URL functions. Returns the URL’s host Returns the URL’s path Returns the URL’s port Returns the URL’s protocol Returns the URL’s query string The following table lists out the Aggregate functions. avg(x) Returns average for the given value Returns the minimum value from two values Returns the maximum value from two values Returns the sum of value Returns the number of input rows Returns the count of input values Returns the checksum for x Returns the arbitrary value for x Following table lists out the Color functions. Renders a single bar using rgb low_color and high_color Renders a single bar for the specified width Returns the color value for the entered string Renders value x using the specific color using ANSI color codes Accepts boolean value b and renders a green true or a red false using ANSI color codes rgb(red, green, blue) Returns a color value capturing the RGB value of three component color values supplied as int parameters ranging from 0 to 255 The following table lists out the Array functions. Finds the max element in an array Finds the min element in an array Sorts the elements in an array Removes the specific element from an array Concatenates two arrays Finds the given elements in an array. True will be returned if it is present, otherwise false Find the position of the given element in an array Performs an intersection between two arrays Returns the array element position Slices the array elements with the specific length The following table lists out Teradata functions. Returns the index of the string with the given substring Returns the substring of the given string. You can specify the start index here Returns the substring of the given string for the specific start index and length of the string The MySQL connector is used to query an external MySQL database. MySQL server installation. Hopefully you have installed mysql server on your machine. To enable mysql properties on Presto server, you must create a file “mysql.properties” in “etc/catalog” directory. Issue the following command to create a mysql.properties file. $ cd etc $ cd catalog $ vi mysql.properties connector.name = mysql connection-url = jdbc:mysql://localhost:3306 connection-user = root connection-password = pwd Save the file and quit the terminal. In the above file, you must enter your mysql password in connection-password field. Open MySQL server and create a database using the following command. create database tutorials Now you have created “tutorials” database in the server. To enable database type, use the command “use tutorials” in the query window. Let’s create a simple table on “tutorials” database. create table author(auth_id int not null, auth_name varchar(50),topic varchar(100)) After creating a table, insert three records using the following query. insert into author values(1,'Doug Cutting','Hadoop') insert into author values(2,’James Gosling','java') insert into author values(3,'Dennis Ritchie’,'C') To retrieve all the records, type the following query. select * from author auth_id auth_name topic 1 Doug Cutting Hadoop 2 James Gosling java 3 Dennis Ritchie C As of now, you have queried data using MySQL server. Let’s connect Mysql storage plugin to Presto server. Type the following command to connect MySql plugin on Presto CLI. ./presto --server localhost:8080 --catalog mysql --schema tutorials You will receive the following response. presto:tutorials> Here “tutorials” refers to schema in mysql server. To list out all the schemas in mysql, type the following query in Presto server. presto:tutorials> show schemas from mysql; Schema -------------------- information_schema performance_schema sys tutorials From this result, we can conclude the first three schemas as predefined and the last one as created by yourself. Following query lists out all the tables in tutorials schema. presto:tutorials> show tables from mysql.tutorials; Table -------- author We have created only one table in this schema. If you have created multiple tables, it will list out all the tables. To describe the table fields, type the following query. presto:tutorials> describe mysql.tutorials.author; Column | Type | Comment -----------+--------------+--------- auth_id | integer | auth_name | varchar(50) | topic | varchar(100) | presto:tutorials> show columns from mysql.tutorials.author; Column | Type | Comment -----------+--------------+--------- auth_id | integer | auth_name | varchar(50) | topic | varchar(100) | To fetch all the records from mysql table, issue the following query. presto:tutorials> select * from mysql.tutorials.author; auth_id | auth_name | topic ---------+----------------+-------- 1 | Doug Cutting | Hadoop 2 | James Gosling | java 3 | Dennis Ritchie | C From this result, you can retrieve mysql server records in Presto. Mysql connector doesn’t support create table query but you can create a table using as command. presto:tutorials> create table mysql.tutorials.sample as select * from mysql.tutorials.author; CREATE TABLE: 3 rows You can’t insert rows directly because this connector has some limitations. It cannot support the following queries − create insert update delete drop To view the records in the newly created table, type the following query. presto:tutorials> select * from mysql.tutorials.sample; auth_id | auth_name | topic ---------+----------------+-------- 1 | Doug Cutting | Hadoop 2 | James Gosling | java 3 | Dennis Ritchie | C Java Management Extensions (JMX) gives information about the Java Virtual Machine and software running inside JVM. The JMX connector is used to query JMX information in Presto server. As we have already enabled “jmx.properties” file under “etc/catalog” directory. Now connect Prest CLI to enable JMX plugin. $ ./presto --server localhost:8080 --catalog jmx --schema jmx You will receive the following response. presto:jmx> To list out all the schemas in “jmx”, type the following query. presto:jmx> show schemas from jmx; Schema -------------------- information_schema current To view the tables in the “current” schema, use the following command. presto:jmx> show tables from jmx.current; Table ------------------------------------------------------------------------------ com.facebook.presto.execution.scheduler:name = nodescheduler com.facebook.presto.execution:name = queryexecution com.facebook.presto.execution:name = querymanager com.facebook.presto.execution:name = remotetaskfactory com.facebook.presto.execution:name = taskexecutor com.facebook.presto.execution:name = taskmanager com.facebook.presto.execution:type = queryqueue,name = global,expansion = global .................. ................... presto:jmx> select * from jmx.current.”java.lang:type = compilation"; node | compilationtimemonitoringsupported | name | objectname | totalcompilationti --------------------------------------+------------------------------------+--------------------------------+----------------------------+------------------- ffffffff-ffff-ffff-ffff-ffffffffffff | true | HotSpot 64-Bit Tiered Compilers | java.lang:type=Compilation | 1276 presto:jmx> select * from jmx.current."com.facebook.presto.server:name = taskresource"; node | readfromoutputbuffertime.alltime.count | readfromoutputbuffertime.alltime.max | readfromoutputbuffertime.alltime.maxer --------------------------------------+---------------------------------------+--------------------------------------+--------------------------------------- ffffffff-ffff-ffff-ffff-ffffffffffff | 92.0 | 1.009106149 | The Hive connector allows querying data stored in a Hive data warehouse. Hadoop Hive Hopefully you have installed Hadoop and Hive on your machine. Start all the services one by one in the new terminal. Then, start hive metastore using the following command, hive --service metastore Presto uses Hive metastore service to get the hive table’s details. Create a file “hive.properties” under “etc/catalog” directory. Use the following command. $ cd etc $ cd catalog $ vi hive.properties connector.name = hive-cdh4 hive.metastore.uri = thrift://localhost:9083 After making all the changes, save the file and quit the terminal. Create a database in Hive using the following query − hive> CREATE SCHEMA tutorials; After the database is created, you can verify it using the “show databases” command. Create Table is a statement used to create a table in Hive. For example, use the following query. hive> create table author(auth_id int, auth_name varchar(50), topic varchar(100) STORED AS SEQUENCEFILE; Following query is used to insert records in hive’s table. hive> insert into table author values (1,’ Doug Cutting’,Hadoop), (2,’ James Gosling’,java),(3,’ Dennis Ritchie’,C); You can start Presto CLI to connect Hive storage plugin using the following command. $ ./presto --server localhost:8080 --catalog hive —schema tutorials; You will receive the following response. presto:tutorials > To list out all the schemas in Hive connector, type the following command. presto:tutorials > show schemas from hive; default tutorials To list out all the tables in “tutorials” schema, use the following query. presto:tutorials > show tables from hive.tutorials; author Following query is used to fetch all the records from hive’s table. presto:tutorials > select * from hive.tutorials.author; auth_id | auth_name | topic ---------+----------------+-------- 1 | Doug Cutting | Hadoop 2 | James Gosling | java 3 | Dennis Ritchie | C The Kafka Connector for Presto allows to access data from Apache Kafka using Presto. Download and install the latest version of the following Apache projects. Apache ZooKeeper Apache Kafka Start ZooKeeper server using the following command. $ bin/zookeeper-server-start.sh config/zookeeper.properties Now, ZooKeeper starts port on 2181. Start Kafka in another terminal using the following command. $ bin/kafka-server-start.sh config/server.properties After kafka starts, it uses the port number 9092. $ curl -o kafka-tpch https://repo1.maven.org/maven2/de/softwareforge/kafka_tpch_0811/1.0/kafka_tpch_ 0811-1.0.sh Now you have downloaded the loader from Maven central using the above command. You will get a similar response as the following. % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0 5 21.6M 5 1279k 0 0 83898 0 0:04:30 0:00:15 0:04:15 129k 6 21.6M 6 1407k 0 0 86656 0 0:04:21 0:00:16 0:04:05 131k 24 21.6M 24 5439k 0 0 124k 0 0:02:57 0:00:43 0:02:14 175k 24 21.6M 24 5439k 0 0 124k 0 0:02:58 0:00:43 0:02:15 160k 25 21.6M 25 5736k 0 0 128k 0 0:02:52 0:00:44 0:02:08 181k ............................. Then, make it executable using the following command, $ chmod 755 kafka-tpch Run the kafka-tpch program to preload a number of topics with tpch data using the following command. $ ./kafka-tpch load --brokers localhost:9092 --prefix tpch. --tpch-type tiny 2016-07-13T16:15:52.083+0530 INFO main io.airlift.log.Logging Logging to stderr 2016-07-13T16:15:52.124+0530 INFO main de.softwareforge.kafka.LoadCommand Processing tables: [customer, orders, lineitem, part, partsupp, supplier, nation, region] 2016-07-13T16:15:52.834+0530 INFO pool-1-thread-1 de.softwareforge.kafka.LoadCommand Loading table 'customer' into topic 'tpch.customer'... 2016-07-13T16:15:52.834+0530 INFO pool-1-thread-2 de.softwareforge.kafka.LoadCommand Loading table 'orders' into topic 'tpch.orders'... 2016-07-13T16:15:52.834+0530 INFO pool-1-thread-3 de.softwareforge.kafka.LoadCommand Loading table 'lineitem' into topic 'tpch.lineitem'... 2016-07-13T16:15:52.834+0530 INFO pool-1-thread-4 de.softwareforge.kafka.LoadCommand Loading table 'part' into topic 'tpch.part'... ........................... ............................ Now, Kafka tables customers,orders,supplier, etc., are loaded using tpch. Let’s add the following Kafka connector configuration settings on Presto server. connector.name = kafka kafka.nodes = localhost:9092 kafka.table-names = tpch.customer,tpch.orders,tpch.lineitem,tpch.part,tpch.partsupp, tpch.supplier,tpch.nation,tpch.region kafka.hide-internal-columns = false In the above configuration, Kafka tables are loaded using Kafka-tpch program. Start Presto CLI using the following command, $ ./presto --server localhost:8080 --catalog kafka —schema tpch; Here “tpch" is a schema for Kafka connector and you will receive a response as the following. presto:tpch> Following query lists out all the tables in “tpch” schema. presto:tpch> show tables; Table ---------- customer lineitem nation orders part partsupp region supplier Following query describes “customer” table. presto:tpch> describe customer; Column | Type | Comment -------------------+---------+--------------------------------------------- _partition_id | bigint | Partition Id _partition_offset | bigint | Offset for the message within the partition _segment_start | bigint | Segment start offset _segment_end | bigint | Segment end offset _segment_count | bigint | Running message count per segment _key | varchar | Key text _key_corrupt | boolean | Key data is corrupt _key_length | bigint | Total number of key bytes _message | varchar | Message text _message_corrupt | boolean | Message data is corrupt _message_length | bigint | Total number of message bytes Presto’s JDBC interface is used to access Java application. Install presto-jdbc-0.150.jar You can download the JDBC jar file by visiting the following link, https://repo1.maven.org/maven2/com/facebook/presto/presto-jdbc/0.150/ After the jar file has been downloaded, add it to the class path of your Java application. Let’s create a simple java application using JDBC interface. Coding − PrestoJdbcSample.java import java.sql.*; import com.facebook.presto.jdbc.PrestoDriver; //import presto jdbc driver packages here. public class PrestoJdbcSample { public static void main(String[] args) { Connection connection = null; Statement statement = null; try { Class.forName("com.facebook.presto.jdbc.PrestoDriver"); connection = DriverManager.getConnection( "jdbc:presto://localhost:8080/mysql/tutorials", "tutorials", “"); //connect mysql server tutorials database here statement = connection.createStatement(); String sql; sql = "select auth_id, auth_name from mysql.tutorials.author”; //select mysql table author table two columns ResultSet resultSet = statement.executeQuery(sql); while(resultSet.next()){ int id = resultSet.getInt("auth_id"); String name = resultSet.getString(“auth_name"); System.out.print("ID: " + id + ";\nName: " + name + "\n"); } resultSet.close(); statement.close(); connection.close(); }catch(SQLException sqlException){ sqlException.printStackTrace(); }catch(Exception exception){ exception.printStackTrace(); } } } Save the file and quit the application. Now, start Presto server in one terminal and open a new terminal to compile and execute the result. Following are the steps − ~/Workspace/presto/presto-jdbc $ javac -cp presto-jdbc-0.149.jar PrestoJdbcSample.java ~/Workspace/presto/presto-jdbc $ java -cp .:presto-jdbc-0.149.jar PrestoJdbcSample INFO: Logging initialized @146ms ID: 1; Name: Doug Cutting ID: 2; Name: James Gosling ID: 3; Name: Dennis Ritchie Create a Maven project to develop Presto custom function. Create SimpleFunctionsFactory class to implement FunctionFactory interface. package com.tutorialspoint.simple.functions; import com.facebook.presto.metadata.FunctionFactory; import com.facebook.presto.metadata.FunctionListBuilder; import com.facebook.presto.metadata.SqlFunction; import com.facebook.presto.spi.type.TypeManager; import java.util.List; public class SimpleFunctionFactory implements FunctionFactory { private final TypeManager typeManager; public SimpleFunctionFactory(TypeManager typeManager) { this.typeManager = typeManager; } @Override public List<SqlFunction> listFunctions() { return new FunctionListBuilder(typeManager) .scalar(SimpleFunctions.class) .getFunctions(); } } Create a SimpleFunctionsPlugin class to implement Plugin interface. package com.tutorialspoint.simple.functions; import com.facebook.presto.metadata.FunctionFactory; import com.facebook.presto.spi.Plugin; import com.facebook.presto.spi.type.TypeManager; import com.google.common.collect.ImmutableList; import javax.inject.Inject; import java.util.List; import static java.util.Objects.requireNonNull; public class SimpleFunctionsPlugin implements Plugin { private TypeManager typeManager; @Inject public void setTypeManager(TypeManager typeManager) { this.typeManager = requireNonNull(typeManager, "typeManager is null”); //Inject TypeManager class here } @Override public <T> List<T> getServices(Class<T> type){ if (type == FunctionFactory.class) { return ImmutableList.of(type.cast(new SimpleFunctionFactory(typeManager))); } return ImmutableList.of(); } } Create a resource file which is specified in the implementation package. (com.tutorialspoint.simple.functions.SimpleFunctionsPlugin) Now move to the resource file location @ /path/to/resource/ Then add the changes, com.facebook.presto.spi.Plugin Add the following dependencies to pom.xml file. <?xml version = "1.0"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint.simple.functions</groupId> <artifactId>presto-simple-functions</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>presto-simple-functions</name> <description>Simple test functions for Presto</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-spi</artifactId> <version>0.149</version> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-main</artifactId> <version>0.149</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> </dependencies> <build> <finalName>presto-simple-functions</finalName> <plugins> <!-- Make this jar executable --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.2</version> </plugin> </plugins> </build> </project> Create SimpleFunctions class using Presto attributes. package com.tutorialspoint.simple.functions; import com.facebook.presto.operator.Description; import com.facebook.presto.operator.scalar.ScalarFunction; import com.facebook.presto.operator.scalar.StringFunctions; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.type.LiteralParameters; import com.facebook.presto.type.SqlType; public final class SimpleFunctions { private SimpleFunctions() { } @Description("Returns summation of two numbers") @ScalarFunction(“mysum") //function name @SqlType(StandardTypes.BIGINT) public static long sum(@SqlType(StandardTypes.BIGINT) long num1, @SqlType(StandardTypes.BIGINT) long num2) { return num1 + num2; } } After the application is created compile and execute the application. It will produce the JAR file. Copy the file and move the JAR file into the target Presto server plugin directory. mvn compile mvn package Now restart Presto server and connect Presto client. Then execute the custom function application as explained below, $ ./presto --catalog mysql --schema default presto:default> select mysum(10,10); _col0 ------- 20 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2322, "s": 2006, "text": "Data analytics is the process of analyzing raw data to gather relevant information for better decision making. It is primarily used in many organizations to make business decisions. Well, big data analytics involves a large amount of data and this process is quite complex, hence companies use different strategies." }, { "code": null, "e": 2750, "s": 2322, "text": "For example, Facebook is one of the leading data driven and largest data warehouse company in the world. Facebook warehouse data is stored in Hadoop for large scale computation. Later, when warehouse data grew to petabytes, they decided to develop a new system with low latency. In the year of 2012, Facebook team members designed “Presto” for interactive query analytics that would operate quickly even with petabytes of data." }, { "code": null, "e": 2962, "s": 2750, "text": "Apache Presto is a distributed parallel query execution engine, optimized for low latency and interactive query analysis. Presto runs queries easily and scales without down time even from gigabytes to petabytes." }, { "code": null, "e": 3272, "s": 2962, "text": "A single Presto query can process data from multiple sources like HDFS, MySQL, Cassandra, Hive and many more data sources. Presto is built in Java and easy to integrate with other data infrastructure components. Presto is powerful, and leading companies like Airbnb, DropBox, Groupon, Netflix are adopting it." }, { "code": null, "e": 3313, "s": 3272, "text": "Presto contains the following features −" }, { "code": null, "e": 3349, "s": 3313, "text": "Simple and extensible architecture." }, { "code": null, "e": 3450, "s": 3349, "text": "Pluggable connectors - Presto supports pluggable connector to provide metadata and data for queries." }, { "code": null, "e": 3514, "s": 3450, "text": "Pipelined executions - Avoids unnecessary I/O latency overhead." }, { "code": null, "e": 3608, "s": 3514, "text": "User-defined functions - Analysts can create custom user-defined functions to migrate easily." }, { "code": null, "e": 3640, "s": 3608, "text": "Vectorized columnar processing." }, { "code": null, "e": 3695, "s": 3640, "text": "Here is a list of benefits that Apache Presto offers −" }, { "code": null, "e": 3722, "s": 3695, "text": "Specialized SQL operations" }, { "code": null, "e": 3748, "s": 3722, "text": "Easy to install and debug" }, { "code": null, "e": 3775, "s": 3748, "text": "Simple storage abstraction" }, { "code": null, "e": 3822, "s": 3775, "text": "Quickly scales petabytes data with low latency" }, { "code": null, "e": 3939, "s": 3822, "text": "Presto supports most of today’s best industrial applications. Let’s take a look at some of the notable applications." }, { "code": null, "e": 4043, "s": 3939, "text": "Facebook − Facebook built Presto for data analytics needs. Presto easily scales large velocity of data." }, { "code": null, "e": 4147, "s": 4043, "text": "Facebook − Facebook built Presto for data analytics needs. Presto easily scales large velocity of data." }, { "code": null, "e": 4340, "s": 4147, "text": "Teradata − Teradata provides end-to-end solutions in Big Data analytics and data warehousing. Teradata contribution to Presto makes it easier for more companies to enable all analytical needs." }, { "code": null, "e": 4533, "s": 4340, "text": "Teradata − Teradata provides end-to-end solutions in Big Data analytics and data warehousing. Teradata contribution to Presto makes it easier for more companies to enable all analytical needs." }, { "code": null, "e": 4682, "s": 4533, "text": "Airbnb − Presto is an integral part of the Airbnb data infrastructure. Well, hundreds of employees are running queries each day with the technology." }, { "code": null, "e": 4831, "s": 4682, "text": "Airbnb − Presto is an integral part of the Airbnb data infrastructure. Well, hundreds of employees are running queries each day with the technology." }, { "code": null, "e": 5149, "s": 4831, "text": "Presto supports standard ANSI SQL which has made it very easy for data analysts and developers. Though it is built in Java, it avoids typical issues of Java code related to memory allocation and garbage collection. Presto has a connector architecture that is Hadoop friendly. It allows to easily plug in file systems." }, { "code": null, "e": 5447, "s": 5149, "text": "Presto runs on multiple Hadoop distributions. In addition, Presto can reach out from a Hadoop platform to query Cassandra, relational databases, or other data stores. This cross-platform analytic capability allows Presto users to extract maximum business value from gigabytes to petabytes of data." }, { "code": null, "e": 5620, "s": 5447, "text": "The architecture of Presto is almost similar to classic MPP (massively parallel processing) DBMS architecture. The following diagram illustrates the architecture of Presto." }, { "code": null, "e": 5731, "s": 5620, "text": "The above diagram consists of different components. Following table describes each of the component in detail." }, { "code": null, "e": 5738, "s": 5731, "text": "Client" }, { "code": null, "e": 5817, "s": 5738, "text": "Client (Presto CLI) submits SQL statements to a coordinator to get the result." }, { "code": null, "e": 5829, "s": 5817, "text": "Coordinator" }, { "code": null, "e": 6054, "s": 5829, "text": "Coordinator is a master daemon. The coordinator initially parses the SQL queries then analyzes and plans for the query execution. Scheduler performs pipeline execution, assigns work to the closest node and monitors progress." }, { "code": null, "e": 6064, "s": 6054, "text": "Connector" }, { "code": null, "e": 6349, "s": 6064, "text": "Storage plugins are called as connectors. Hive, HBase, MySQL, Cassandra and many more act as a connector; otherwise you can also implement a custom one. The connector provides metadata and data for queries. The coordinator uses the connector to get metadata for building a query plan." }, { "code": null, "e": 6356, "s": 6349, "text": "Worker" }, { "code": null, "e": 6506, "s": 6356, "text": "The coordinator assigns task to worker nodes. The workers get actual data from the connector. Finally, the worker node delivers result to the client." }, { "code": null, "e": 6865, "s": 6506, "text": "Presto is a distributed system that runs on a cluster of nodes. Presto’s distributed query engine is optimized for interactive analysis and supports standard ANSI SQL, including complex queries, aggregations, joins, and window functions. Presto architecture is simple and extensible. Presto client (CLI) submits SQL statements to a master daemon coordinator." }, { "code": null, "e": 7451, "s": 6865, "text": "The scheduler connects through execution pipeline. The scheduler assigns work to nodes which is closest to the data and monitors progress. The coordinator assigns task to multiple worker nodes and finally the worker node delivers the result back to the client. The client pulls data from the output process. Extensibility is the key design. Pluggable connectors like Hive, HBase, MySQL, etc., provides metadata and data for queries. Presto was designed with a “simple storage abstraction” that makes it easy to provide SQL query capability against these different kind of data sources." }, { "code": null, "e": 7720, "s": 7451, "text": "Presto supports custom query and execution engine with operators designed to support SQL semantics. In addition to improved scheduling, all processing is in memory and pipelined across the network between different stages. This avoids unnecessary I/O latency overhead." }, { "code": null, "e": 7836, "s": 7720, "text": "This chapter will explain how to install Presto on your machine. Let’s go through the basic requirements of Presto," }, { "code": null, "e": 7852, "s": 7836, "text": "Linux or Mac OS" }, { "code": null, "e": 7867, "s": 7852, "text": "Java version 8" }, { "code": null, "e": 7942, "s": 7867, "text": "Now, let’s continue the following steps to install Presto on your machine." }, { "code": null, "e": 8073, "s": 7942, "text": "Hopefully, you have already installed Java version 8 on your machine right now, so you just verify it using the following command." }, { "code": null, "e": 8091, "s": 8073, "text": "$ java -version \n" }, { "code": null, "e": 8276, "s": 8091, "text": "If Java is successfully installed on your machine, you could see the version of installed Java. If Java is not installed, follow the subsequent steps to install Java 8 on your machine." }, { "code": null, "e": 8357, "s": 8276, "text": "Download JDK. Download the latest version of JDK by visiting the following link." }, { "code": null, "e": 8441, "s": 8357, "text": "http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html" }, { "code": null, "e": 8560, "s": 8441, "text": "The latest version is JDK 8u 92 and the file is “jdk-8u92-linux-x64.tar.gz”. Please download the file on your machine." }, { "code": null, "e": 8626, "s": 8560, "text": "After that, extract the files and move to the specific directory." }, { "code": null, "e": 8702, "s": 8626, "text": "Then set Java alternatives. Finally Java will be installed on your machine." }, { "code": null, "e": 8772, "s": 8702, "text": "Download the latest version of Presto by visiting the following link," }, { "code": null, "e": 8844, "s": 8772, "text": "https://repo1.maven.org/maven2/com/facebook/presto/presto-server/0.149/" }, { "code": null, "e": 8935, "s": 8844, "text": "Now the latest version of “presto-server-0.149.tar.gz” will be downloaded on your machine." }, { "code": null, "e": 8986, "s": 8935, "text": "Extract the tar file using the following command −" }, { "code": null, "e": 9054, "s": 8986, "text": "$ tar -zxf presto-server-0.149.tar.gz \n$ cd presto-server-0.149 \n" }, { "code": null, "e": 9268, "s": 9054, "text": "Create a data directory outside the installation directory, which will be used for storing logs, metadata, etc., so that it is to be easily preserved when upgrading Presto. It is defined using the following code −" }, { "code": null, "e": 9289, "s": 9268, "text": "$ cd \n$ mkdir data\n" }, { "code": null, "e": 9415, "s": 9289, "text": "To view the path where it is located, use the command “pwd”. This location will be assigned in the next node.properties file." }, { "code": null, "e": 9503, "s": 9415, "text": "Create an etc directory inside Presto installation directory using the following code −" }, { "code": null, "e": 9542, "s": 9503, "text": "$ cd presto-server-0.149 \n$ mkdir etc\n" }, { "code": null, "e": 9623, "s": 9542, "text": "This directory will hold configuration files. Let’s create each file one by one." }, { "code": null, "e": 9795, "s": 9623, "text": "Presto node properties file contains environmental configuration specific to each node. It is created inside etc directory (etc/node.properties) using the following code −" }, { "code": null, "e": 9952, "s": 9795, "text": "$ cd etc \n$ vi node.properties \n\nnode.environment = production \nnode.id = ffffffff-ffff-ffff-ffff-ffffffffffff \nnode.data-dir = /Users/../workspace/Presto\n" }, { "code": null, "e": 10149, "s": 9952, "text": "After making all the changes, save the file, and quit the terminal. Here node.data is the location path of the above created data directory. node.id represents the unique identifier for each node." }, { "code": null, "e": 10310, "s": 10149, "text": "Create a file “jvm.config” inside etc directory (etc/jvm.config). This file contains a list of command line options used for launching the Java Virtual Machine." }, { "code": null, "e": 10529, "s": 10310, "text": "$ cd etc \n$ vi jvm.config \n\n-server \n-Xmx16G \n-XX:+UseG1GC \n-XX:G1HeapRegionSize = 32M \n-XX:+UseGCOverheadLimit \n-XX:+ExplicitGCInvokesConcurrent \n-XX:+HeapDumpOnOutOfMemoryError \n-XX:OnOutOfMemoryError = kill -9 %p \n" }, { "code": null, "e": 10597, "s": 10529, "text": "After making all the changes, save the file, and quit the terminal." }, { "code": null, "e": 10881, "s": 10597, "text": "Create a file “config.properties” inside etc directory(etc/config.properties). This file contains the configuration of Presto server. If you are setting up a single machine for testing, Presto server can function only as the coordination process as defined using the following code −" }, { "code": null, "e": 11139, "s": 10881, "text": "$ cd etc \n$ vi config.properties \n\ncoordinator = true \nnode-scheduler.include-coordinator = true \nhttp-server.http.port = 8080 \nquery.max-memory = 5GB \nquery.max-memory-per-node = 1GB \ndiscovery-server.enabled = true \ndiscovery.uri = http://localhost:8080\n" }, { "code": null, "e": 11145, "s": 11139, "text": "Here," }, { "code": null, "e": 11172, "s": 11145, "text": "coordinator − master node." }, { "code": null, "e": 11199, "s": 11172, "text": "coordinator − master node." }, { "code": null, "e": 11279, "s": 11199, "text": "node-scheduler.include-coordinator − Allows scheduling work on the coordinator." }, { "code": null, "e": 11359, "s": 11279, "text": "node-scheduler.include-coordinator − Allows scheduling work on the coordinator." }, { "code": null, "e": 11423, "s": 11359, "text": "http-server.http.port − Specifies the port for the HTTP server." }, { "code": null, "e": 11487, "s": 11423, "text": "http-server.http.port − Specifies the port for the HTTP server." }, { "code": null, "e": 11552, "s": 11487, "text": "query.max-memory=5GB − The maximum amount of distributed memory." }, { "code": null, "e": 11617, "s": 11552, "text": "query.max-memory=5GB − The maximum amount of distributed memory." }, { "code": null, "e": 11688, "s": 11617, "text": "query.max-memory-per-node=1GB − The maximum amount of memory per node." }, { "code": null, "e": 11759, "s": 11688, "text": "query.max-memory-per-node=1GB − The maximum amount of memory per node." }, { "code": null, "e": 11858, "s": 11759, "text": "discovery-server.enabled − Presto uses the Discovery service to find all the nodes in the cluster." }, { "code": null, "e": 11957, "s": 11858, "text": "discovery-server.enabled − Presto uses the Discovery service to find all the nodes in the cluster." }, { "code": null, "e": 12005, "s": 11957, "text": "discovery.uri − he URI to the Discovery server." }, { "code": null, "e": 12053, "s": 12005, "text": "discovery.uri − he URI to the Discovery server." }, { "code": null, "e": 12244, "s": 12053, "text": "If you are setting up multiple machine Presto server, Presto will function as both coordination and worker process. Use this configuration setting to test Presto server on multiple machines." }, { "code": null, "e": 12505, "s": 12244, "text": "$ cd etc \n$ vi config.properties \n\ncoordinator = true \nnode-scheduler.include-coordinator = false \nhttp-server.http.port = 8080 \nquery.max-memory = 50GB \nquery.max-memory-per-node = 1GB \ndiscovery-server.enabled = true \ndiscovery.uri = http://localhost:8080 \n" }, { "code": null, "e": 12689, "s": 12505, "text": "$ cd etc \n$ vi config.properties \n\ncoordinator = false \nhttp-server.http.port = 8080 \nquery.max-memory = 50GB \nquery.max-memory-per-node = 1GB \ndiscovery.uri = http://localhost:8080\n" }, { "code": null, "e": 12870, "s": 12689, "text": "Create a file “log.properties” inside etc directory(etc/log.properties). This file contains minimum log level for named logger hierarchies. It is defined using the following code −" }, { "code": null, "e": 12930, "s": 12870, "text": "$ cd etc \n$ vi log.properties \ncom.facebook.presto = INFO\n" }, { "code": null, "e": 13062, "s": 12930, "text": "Save the file and quit the terminal. Here, four log levels are used such as DEBUG, INFO, WARN and ERROR. Default log level is INFO." }, { "code": null, "e": 13286, "s": 13062, "text": "Create a directory “catalog” inside etc directory(etc/catalog). This will be used for mounting data. For example, create etc/catalog/jmx.properties with the following contents to mount the jmx connector as the jmx catalog −" }, { "code": null, "e": 13372, "s": 13286, "text": "$ cd etc \n$ mkdir catalog \n$ cd catalog \n$ vi jmx.properties \nconnector.name = jmx \n" }, { "code": null, "e": 13423, "s": 13372, "text": "Presto can be started using the following command," }, { "code": null, "e": 13446, "s": 13423, "text": "$ bin/launcher start \n" }, { "code": null, "e": 13494, "s": 13446, "text": "Then you will see the response similar to this," }, { "code": null, "e": 13510, "s": 13494, "text": "Started as 840\n" }, { "code": null, "e": 13563, "s": 13510, "text": "To launch Presto server, use the following command −" }, { "code": null, "e": 13583, "s": 13563, "text": "$ bin/launcher run\n" }, { "code": null, "e": 13674, "s": 13583, "text": "After successfully launching Presto server, you can find log files in “var/log” directory." }, { "code": null, "e": 13790, "s": 13674, "text": "launcher.log − This log is created by the launcher and is connected to the stdout and stderr streams of the server." }, { "code": null, "e": 13906, "s": 13790, "text": "launcher.log − This log is created by the launcher and is connected to the stdout and stderr streams of the server." }, { "code": null, "e": 13961, "s": 13906, "text": "server.log − This is the main log file used by Presto." }, { "code": null, "e": 14016, "s": 13961, "text": "server.log − This is the main log file used by Presto." }, { "code": null, "e": 14072, "s": 14016, "text": "http-request.log − HTTP request received by the server." }, { "code": null, "e": 14128, "s": 14072, "text": "http-request.log − HTTP request received by the server." }, { "code": null, "e": 14266, "s": 14128, "text": "As of now, you have successfully installed Presto configuration settings on your machine. Let’s continue the steps to install Presto CLI." }, { "code": null, "e": 14346, "s": 14266, "text": "The Presto CLI provides a terminal-based interactive shell for running queries." }, { "code": null, "e": 14402, "s": 14346, "text": "Download the Presto CLI by visiting the following link," }, { "code": null, "e": 14471, "s": 14402, "text": "https://repo1.maven.org/maven2/com/facebook/presto/presto-cli/0.149/" }, { "code": null, "e": 14544, "s": 14471, "text": "Now “presto-cli-0.149-executable.jar” will be installed on your machine." }, { "code": null, "e": 14830, "s": 14544, "text": "After downloading the presto-cli, copy it to the location which you want to run it from. This location may be any node that has network access to the coordinator. First change the name of the Jar file to Presto. Then make it executable with chmod + x command using the following code −" }, { "code": null, "e": 14895, "s": 14830, "text": "$ mv presto-cli-0.149-executable.jar presto \n$ chmod +x presto\n" }, { "code": null, "e": 14940, "s": 14895, "text": "Now execute CLI using the following command," }, { "code": null, "e": 15093, "s": 14940, "text": "./presto --server localhost:8080 --catalog jmx --schema default \nHere jmx(Java Management Extension) refers to catalog and default referes to schema. \n" }, { "code": null, "e": 15130, "s": 15093, "text": "You will see the following response," }, { "code": null, "e": 15148, "s": 15130, "text": " presto:default>\n" }, { "code": null, "e": 15226, "s": 15148, "text": "Now type “jps” command on your terminal and you will see the running daemons." }, { "code": null, "e": 15330, "s": 15226, "text": "After having performed all the executions, you can stop the presto server using the following command −" }, { "code": null, "e": 15352, "s": 15330, "text": "$ bin/launcher stop \n" }, { "code": null, "e": 15417, "s": 15352, "text": "This chapter will discuss the configuration settings for Presto." }, { "code": null, "e": 15557, "s": 15417, "text": "The Presto Verifier can be used to test Presto against another database (such as MySQL), or to test two Presto clusters against each other." }, { "code": null, "e": 15626, "s": 15557, "text": "Open MySQL server and create a database using the following command." }, { "code": null, "e": 15648, "s": 15626, "text": "create database test " }, { "code": null, "e": 15755, "s": 15648, "text": "Now you have created “test” database in the server. Create the table and load it with the following query." }, { "code": null, "e": 16487, "s": 15755, "text": "CREATE TABLE verifier_queries( \n id INT NOT NULL AUTO_INCREMENT, \n suite VARCHAR(256) NOT NULL, \n name VARCHAR(256), \n test_catalog VARCHAR(256) NOT NULL, \n test_schema VARCHAR(256) NOT NULL, \n test_prequeries TEXT, \n test_query TEXT NOT NULL, \n test_postqueries TEXT, \n test_username VARCHAR(256) NOT NULL default 'verifier-test', \n test_password VARCHAR(256), \n control_catalog VARCHAR(256) NOT NULL, \n control_schema VARCHAR(256) NOT NULL, \n control_prequeries TEXT, \n control_query TEXT NOT NULL, \n control_postqueries TEXT, \n control_username VARCHAR(256) NOT NULL default 'verifier-test', \n control_password VARCHAR(256), \n session_properties_json TEXT, \n PRIMARY KEY (id) \n);" }, { "code": null, "e": 16540, "s": 16487, "text": "Create a properties file to configure the verifier −" }, { "code": null, "e": 16774, "s": 16540, "text": "$ vi config.properties \n\nsuite = mysuite \nquery-database = jdbc:mysql://localhost:3306/tutorials?user=root&password=pwd \ncontrol.gateway = jdbc:presto://localhost:8080 \ntest.gateway = jdbc:presto://localhost:8080 \nthread-count = 1 \n" }, { "code": null, "e": 16885, "s": 16774, "text": "Here, in the query-database field, enter the following details − mysql database name, user name, and password." }, { "code": null, "e": 16951, "s": 16885, "text": "Download Presto-verifier jar file by visiting the following link," }, { "code": null, "e": 17025, "s": 16951, "text": "https://repo1.maven.org/maven2/com/facebook/presto/presto-verifier/0.149/" }, { "code": null, "e": 17111, "s": 17025, "text": "Now the version “presto-verifier-0.149-executable.jar” is downloaded on your machine." }, { "code": null, "e": 17161, "s": 17111, "text": "Execute the JAR file using the following command," }, { "code": null, "e": 17235, "s": 17161, "text": "$ mv presto-verifier-0.149-executable.jar verifier \n$ chmod+x verifier \n" }, { "code": null, "e": 17281, "s": 17235, "text": "Run the verifier using the following command," }, { "code": null, "e": 17314, "s": 17281, "text": "$ ./verifier config.properties \n" }, { "code": null, "e": 17388, "s": 17314, "text": "Let’s create a simple table in “test” database using the following query." }, { "code": null, "e": 17444, "s": 17388, "text": "create table product(id int not null, name varchar(50))" }, { "code": null, "e": 17514, "s": 17444, "text": "After creating a table, insert two records using the following query," }, { "code": null, "e": 17596, "s": 17514, "text": "insert into product values(1,’Phone') \ninsert into product values(2,’Television’)" }, { "code": null, "e": 17716, "s": 17596, "text": "Execute the following sample query in the verifier terminal (./verifier config.propeties) to check the verifier result." }, { "code": null, "e": 17975, "s": 17716, "text": "insert into verifier_queries (suite, test_catalog, test_schema, test_query, \ncontrol_catalog, control_schema, control_query) values \n('mysuite', 'mysql', 'default', 'select * from mysql.test.product', \n'mysql', 'default', 'select * from mysql.test.product');" }, { "code": null, "e": 18160, "s": 17975, "text": "Here, select * from mysql.test.product query refers to mysql catalog, test is database name and product is table name. In this way, you can access mysql connector using Presto server." }, { "code": null, "e": 18389, "s": 18160, "text": "Here, two same select queries are tested against each other to see the performance. Similarly, you can run other queries to test the performance results. You can also connect two Presto clusters to check the performance results." }, { "code": null, "e": 18509, "s": 18389, "text": "In this chapter, we will discuss the administration tools used in Presto. Let’s start with the Web Interface of Presto." }, { "code": null, "e": 18666, "s": 18509, "text": "Presto provides a web interface for monitoring and managing queries. It can be accessed from the port number specified in the coordinator Config Properties." }, { "code": null, "e": 18788, "s": 18666, "text": "Start Presto server and Presto CLI. Then you can access the web interface from the following url − http://localhost:8080/" }, { "code": null, "e": 18836, "s": 18788, "text": "The output will be similar to the above screen." }, { "code": null, "e": 19130, "s": 18836, "text": "Here, the main page has a list of queries along with information like unique query ID, query text, query state, percentage completed, username and source from which this query is originated. Latest queries are running first, then completed or not completed queries are displayed at the bottom." }, { "code": null, "e": 19260, "s": 19130, "text": "If Presto cluster is having any performance-related issues, change your default configuration settings to the following settings." }, { "code": null, "e": 19322, "s": 19260, "text": "task. info -refresh-max-wait − Reduces coordinator work load." }, { "code": null, "e": 19384, "s": 19322, "text": "task. info -refresh-max-wait − Reduces coordinator work load." }, { "code": null, "e": 19463, "s": 19384, "text": "task.max-worker-threads − Splits the process and assigns to each worker nodes." }, { "code": null, "e": 19542, "s": 19463, "text": "task.max-worker-threads − Splits the process and assigns to each worker nodes." }, { "code": null, "e": 19600, "s": 19542, "text": "distributed-joins-enabled − Hash-based distributed joins." }, { "code": null, "e": 19658, "s": 19600, "text": "distributed-joins-enabled − Hash-based distributed joins." }, { "code": null, "e": 19728, "s": 19658, "text": "node-scheduler.network-topology − Sets network topology to scheduler." }, { "code": null, "e": 19798, "s": 19728, "text": "node-scheduler.network-topology − Sets network topology to scheduler." }, { "code": null, "e": 19921, "s": 19798, "text": "Change your default JVM settings to the following settings. This will be helpful for diagnosing garbage collection issues." }, { "code": null, "e": 20311, "s": 19921, "text": "-XX:+PrintGCApplicationConcurrentTime \n-XX:+PrintGCApplicationStoppedTime \n-XX:+PrintGCCause \n-XX:+PrintGCDateStamps \n-XX:+PrintGCTimeStamps \n-XX:+PrintGCDetails \n-XX:+PrintReferenceGC \n-XX:+PrintClassHistogramAfterFullGC \n-XX:+PrintClassHistogramBeforeFullGC \n-XX:PrintFLSStatistics = 2 \n-XX:+PrintAdaptiveSizePolicy \n-XX:+PrintSafepointStatistics \n-XX:PrintSafepointStatisticsCount = 1 \n" }, { "code": null, "e": 20442, "s": 20311, "text": "In this chapter, we will discuss how to create and execute queries on Presto. Let us go through Presto supported basic data types." }, { "code": null, "e": 20504, "s": 20442, "text": "The following table describes the basic data types of Presto." }, { "code": null, "e": 20512, "s": 20504, "text": "VARCHAR" }, { "code": null, "e": 20543, "s": 20512, "text": "Variable length character data" }, { "code": null, "e": 20550, "s": 20543, "text": "BIGINT" }, { "code": null, "e": 20574, "s": 20550, "text": "A 64-bit signed integer" }, { "code": null, "e": 20581, "s": 20574, "text": "DOUBLE" }, { "code": null, "e": 20628, "s": 20581, "text": "A 64-bit floating point double precision value" }, { "code": null, "e": 20636, "s": 20628, "text": "DECIMAL" }, { "code": null, "e": 20838, "s": 20636, "text": "A fixed precision decimal number. For example DECIMAL(10,3) - 10 is precision, i.e. total number of digits and 3 is scale value represented as fractional point. Scale is optional and default value is 0" }, { "code": null, "e": 20846, "s": 20838, "text": "BOOLEAN" }, { "code": null, "e": 20876, "s": 20846, "text": "Boolean values true and false" }, { "code": null, "e": 20886, "s": 20876, "text": "VARBINARY" }, { "code": null, "e": 20914, "s": 20886, "text": "Variable length binary data" }, { "code": null, "e": 20919, "s": 20914, "text": "JSON" }, { "code": null, "e": 20929, "s": 20919, "text": "JSON data" }, { "code": null, "e": 20934, "s": 20929, "text": "DATE" }, { "code": null, "e": 20979, "s": 20934, "text": "Date data type represented as year-month-day" }, { "code": null, "e": 21021, "s": 20979, "text": "TIME, TIMESTAMP, TIMESTAMP with TIME ZONE" }, { "code": null, "e": 21071, "s": 21021, "text": "TIME - Time of the day (hour-min-sec-millisecond)" }, { "code": null, "e": 21108, "s": 21071, "text": "TIMESTAMP - Date and time of the day" }, { "code": null, "e": 21190, "s": 21108, "text": "TIMESTAMP with TIME ZONE - Date and time of the day with time zone from the value" }, { "code": null, "e": 21199, "s": 21190, "text": "INTERVAL" }, { "code": null, "e": 21242, "s": 21199, "text": "Stretch or extend date and time data types" }, { "code": null, "e": 21248, "s": 21242, "text": "ARRAY" }, { "code": null, "e": 21307, "s": 21248, "text": "Array of the given component type. For example, ARRAY[5,7]" }, { "code": null, "e": 21311, "s": 21307, "text": "MAP" }, { "code": null, "e": 21398, "s": 21311, "text": "Map between the given component types. For example, MAP(ARRAY[‘one’,’two’],ARRAY[5,7])" }, { "code": null, "e": 21402, "s": 21398, "text": "ROW" }, { "code": null, "e": 21440, "s": 21402, "text": "Row structure made up of named fields" }, { "code": null, "e": 21492, "s": 21440, "text": "Presto operators are listed in the following table." }, { "code": null, "e": 21551, "s": 21492, "text": "Presto supports arithmetic operators such as +, -, *, /, %" }, { "code": null, "e": 21566, "s": 21551, "text": "<,>,<=,>=,=,<>" }, { "code": null, "e": 21579, "s": 21566, "text": "AND, OR, NOT" }, { "code": null, "e": 21707, "s": 21579, "text": "Range operator is used to test the value in a specific range. Presto supports BETWEEN, IS NULL, IS NOT NULL, GREATEST and LEAST" }, { "code": null, "e": 21854, "s": 21707, "text": "Binary arithmetic decimal operator performs binary arithmetic operation for decimal type Unary decimal operator − The - operator performs negation" }, { "code": null, "e": 21902, "s": 21854, "text": "The ‘||’ operator performs string concatenation" }, { "code": null, "e": 21986, "s": 21902, "text": "Performs arithmetic addition and subtraction operations on date and time data types" }, { "code": null, "e": 22039, "s": 21986, "text": "Subscript operator[] - access an element of an array" }, { "code": null, "e": 22133, "s": 22039, "text": "Concatenation operator || - concatenate an array with an array or an element of the same type" }, { "code": null, "e": 22220, "s": 22133, "text": "Map subscript operator [] - retrieve the value corresponding to a given key from a map" }, { "code": null, "e": 22349, "s": 22220, "text": "As of now we were discussing running some simple basic queries on Presto. This chapter will discuss the important SQL functions." }, { "code": null, "e": 22457, "s": 22349, "text": "Math functions operate on mathematical formulas. Following table describes the list of functions in detail." }, { "code": null, "e": 22489, "s": 22457, "text": "Returns the absolute value of x" }, { "code": null, "e": 22516, "s": 22489, "text": "Returns the cube root of x" }, { "code": null, "e": 22570, "s": 22516, "text": "Returns the x value rounded up to the nearest integer" }, { "code": null, "e": 22578, "s": 22570, "text": "ceil(x)" }, { "code": null, "e": 22599, "s": 22578, "text": "Alias for ceiling(x)" }, { "code": null, "e": 22630, "s": 22599, "text": "Returns the degree value for x" }, { "code": null, "e": 22674, "s": 22630, "text": "Returns the double value for Euler’s number" }, { "code": null, "e": 22681, "s": 22674, "text": "exp(x)" }, { "code": null, "e": 22727, "s": 22681, "text": "Returns the exponent value for Euler’s number" }, { "code": null, "e": 22773, "s": 22727, "text": "Returns x rounded down to the nearest integer" }, { "code": null, "e": 22797, "s": 22773, "text": "from_base(string,radix)" }, { "code": null, "e": 22860, "s": 22797, "text": "Returns the value of string interpreted as a base-radix number" }, { "code": null, "e": 22866, "s": 22860, "text": "ln(x)" }, { "code": null, "e": 22901, "s": 22866, "text": "Returns the natural logarithm of x" }, { "code": null, "e": 22935, "s": 22901, "text": "Returns the base 2 logarithm of x" }, { "code": null, "e": 22944, "s": 22935, "text": "log10(x)" }, { "code": null, "e": 22979, "s": 22944, "text": "Returns the base 10 logarithm of x" }, { "code": null, "e": 22988, "s": 22979, "text": "log(x,y)" }, { "code": null, "e": 23022, "s": 22988, "text": "Returns the base y logarithm of x" }, { "code": null, "e": 23072, "s": 23022, "text": "Returns the modulus (remainder) of n divided by m" }, { "code": null, "e": 23077, "s": 23072, "text": "pi()" }, { "code": null, "e": 23141, "s": 23077, "text": "Returns pi value. The result will be returned as a double value" }, { "code": null, "e": 23183, "s": 23141, "text": "Returns power of value ‘p’ to the x value" }, { "code": null, "e": 23192, "s": 23183, "text": "pow(x,p)" }, { "code": null, "e": 23213, "s": 23192, "text": "Alias for power(x,p)" }, { "code": null, "e": 23252, "s": 23213, "text": "converts the angle x in degree radians" }, { "code": null, "e": 23259, "s": 23252, "text": "rand()" }, { "code": null, "e": 23279, "s": 23259, "text": "Alias for radians()" }, { "code": null, "e": 23311, "s": 23279, "text": "Returns the pseudo-random value" }, { "code": null, "e": 23319, "s": 23311, "text": "rand(n)" }, { "code": null, "e": 23338, "s": 23319, "text": "Alias for random()" }, { "code": null, "e": 23370, "s": 23338, "text": "Returns the rounded value for x" }, { "code": null, "e": 23381, "s": 23370, "text": "round(x,d)" }, { "code": null, "e": 23424, "s": 23381, "text": "x value rounded for the ‘d’ decimal places" }, { "code": null, "e": 23432, "s": 23424, "text": "sign(x)" }, { "code": null, "e": 23472, "s": 23432, "text": "Returns the signum function of x, i.e.," }, { "code": null, "e": 23495, "s": 23472, "text": "0 if the argument is 0" }, { "code": null, "e": 23531, "s": 23495, "text": "1 if the argument is greater than 0" }, { "code": null, "e": 23565, "s": 23531, "text": "-1 if the argument is less than 0" }, { "code": null, "e": 23623, "s": 23565, "text": "For double arguments, the function additionally returns −" }, { "code": null, "e": 23650, "s": 23623, "text": "NaN if the argument is NaN" }, { "code": null, "e": 23681, "s": 23650, "text": "1 if the argument is +Infinity" }, { "code": null, "e": 23713, "s": 23681, "text": "-1 if the argument is -Infinity" }, { "code": null, "e": 23742, "s": 23713, "text": "Returns the square root of x" }, { "code": null, "e": 23812, "s": 23742, "text": "Return type is archer. The result is returned as the base radix for x" }, { "code": null, "e": 23838, "s": 23812, "text": "Truncates the value for x" }, { "code": null, "e": 23925, "s": 23838, "text": "Returns the bin number of x specified bound1 and bound2 bounds and n number of buckets" }, { "code": null, "e": 24003, "s": 23925, "text": "Returns the bin number of x according to the bins specified by the array bins" }, { "code": null, "e": 24108, "s": 24003, "text": "Trigonometric functions arguments are represented as radians(). Following table lists out the functions." }, { "code": null, "e": 24144, "s": 24108, "text": "Returns the inverse cosine value(x)" }, { "code": null, "e": 24152, "s": 24144, "text": "asin(x)" }, { "code": null, "e": 24186, "s": 24152, "text": "Returns the inverse sine value(x)" }, { "code": null, "e": 24194, "s": 24186, "text": "atan(x)" }, { "code": null, "e": 24231, "s": 24194, "text": "Returns the inverse tangent value(x)" }, { "code": null, "e": 24270, "s": 24231, "text": "Returns the inverse tangent value(y/x)" }, { "code": null, "e": 24277, "s": 24270, "text": "cos(x)" }, { "code": null, "e": 24305, "s": 24277, "text": "Returns the cosine value(x)" }, { "code": null, "e": 24344, "s": 24305, "text": "Returns the hyperbolic cosine value(x)" }, { "code": null, "e": 24370, "s": 24344, "text": "Returns the sine value(x)" }, { "code": null, "e": 24377, "s": 24370, "text": "tan(x)" }, { "code": null, "e": 24406, "s": 24377, "text": "Returns the tangent value(x)" }, { "code": null, "e": 24414, "s": 24406, "text": "tanh(x)" }, { "code": null, "e": 24454, "s": 24414, "text": "Returns the hyperbolic tangent value(x)" }, { "code": null, "e": 24507, "s": 24454, "text": "The following table lists out the Bitwise functions." }, { "code": null, "e": 24532, "s": 24507, "text": "Count the number of bits" }, { "code": null, "e": 24584, "s": 24532, "text": "Perform bitwise AND operation for two bits, x and y" }, { "code": null, "e": 24627, "s": 24584, "text": "Bitwise OR operation between two bits x, y" }, { "code": null, "e": 24659, "s": 24627, "text": "Bitwise Not operation for bit x" }, { "code": null, "e": 24687, "s": 24659, "text": "XOR operation for bits x, y" }, { "code": null, "e": 24735, "s": 24687, "text": "Following table lists out the String functions." }, { "code": null, "e": 24765, "s": 24735, "text": "Concatenate the given strings" }, { "code": null, "e": 24804, "s": 24765, "text": "Returns the length of the given string" }, { "code": null, "e": 24848, "s": 24804, "text": "Returns the lowercase format for the string" }, { "code": null, "e": 24898, "s": 24848, "text": "Returns the uppercase format for the given string" }, { "code": null, "e": 24932, "s": 24898, "text": "Left padding for the given string" }, { "code": null, "e": 24979, "s": 24932, "text": "Removes the leading whitespace from the string" }, { "code": null, "e": 25005, "s": 24979, "text": "Replaces the string value" }, { "code": null, "e": 25053, "s": 25005, "text": "Reverses the operation performed for the string" }, { "code": null, "e": 25088, "s": 25053, "text": "Right padding for the given string" }, { "code": null, "e": 25136, "s": 25088, "text": "Removes the trailing whitespace from the string" }, { "code": null, "e": 25214, "s": 25136, "text": "Splits the string on delimiter and returns an array of size at the most limit" }, { "code": null, "e": 25273, "s": 25214, "text": "Splits the string on delimiter and returns the field index" }, { "code": null, "e": 25334, "s": 25273, "text": "Returns the starting position of the substring in the string" }, { "code": null, "e": 25377, "s": 25334, "text": "Returns the substring for the given string" }, { "code": null, "e": 25445, "s": 25377, "text": "Returns the substring for the given string with the specific length" }, { "code": null, "e": 25505, "s": 25445, "text": "Removes the leading and trailing whitespace from the string" }, { "code": null, "e": 25560, "s": 25505, "text": "Following table lists out the Date and Time functions." }, { "code": null, "e": 25585, "s": 25560, "text": "Returns the current date" }, { "code": null, "e": 25610, "s": 25585, "text": "Returns the current time" }, { "code": null, "e": 25640, "s": 25610, "text": "Returns the current timestamp" }, { "code": null, "e": 25669, "s": 25640, "text": "Returns the current timezone" }, { "code": null, "e": 25722, "s": 25669, "text": "Returns the current date,timestamp with the timezone" }, { "code": null, "e": 25745, "s": 25722, "text": "Returns the local time" }, { "code": null, "e": 25773, "s": 25745, "text": "Returns the local timestamp" }, { "code": null, "e": 25837, "s": 25773, "text": "The following table lists out the Regular Expression functions." }, { "code": null, "e": 25906, "s": 25837, "text": "Returns the string matched by the regular expression for the pattern" }, { "code": null, "e": 25989, "s": 25906, "text": "Returns the string matched by the regular expression for the pattern and the group" }, { "code": null, "e": 26067, "s": 25989, "text": "Returns the first substring matched by the regular expression for the pattern" }, { "code": null, "e": 26159, "s": 26067, "text": "Returns the first substring matched by the regular expression for the pattern and the group" }, { "code": null, "e": 26269, "s": 26159, "text": "Returns the string matches for the pattern. If the string is returned, the value will be true otherwise false" }, { "code": null, "e": 26349, "s": 26269, "text": "Replaces the instance of the string matched for the expression with the pattern" }, { "code": null, "e": 26444, "s": 26349, "text": "Replace the instance of the string matched for the expression with the pattern and replacement" }, { "code": null, "e": 26496, "s": 26444, "text": "Splits the regular expression for the given pattern" }, { "code": null, "e": 26542, "s": 26496, "text": "The following table lists out JSON functions." }, { "code": null, "e": 26639, "s": 26542, "text": "Check the value exists in a json array. If the value exists it will return true, otherwise false" }, { "code": null, "e": 26679, "s": 26639, "text": "Get the element for index in json array" }, { "code": null, "e": 26712, "s": 26679, "text": "Returns the length in json array" }, { "code": null, "e": 26746, "s": 26712, "text": "Returns the json structure format" }, { "code": null, "e": 26774, "s": 26746, "text": "Parses the string as a json" }, { "code": null, "e": 26804, "s": 26774, "text": "Returns the size of the value" }, { "code": null, "e": 26853, "s": 26804, "text": "The following table lists out the URL functions." }, { "code": null, "e": 26876, "s": 26853, "text": "Returns the URL’s host" }, { "code": null, "e": 26899, "s": 26876, "text": "Returns the URL’s path" }, { "code": null, "e": 26922, "s": 26899, "text": "Returns the URL’s port" }, { "code": null, "e": 26949, "s": 26922, "text": "Returns the URL’s protocol" }, { "code": null, "e": 26980, "s": 26949, "text": "Returns the URL’s query string" }, { "code": null, "e": 27035, "s": 26980, "text": "The following table lists out the Aggregate functions." }, { "code": null, "e": 27042, "s": 27035, "text": "avg(x)" }, { "code": null, "e": 27078, "s": 27042, "text": "Returns average for the given value" }, { "code": null, "e": 27120, "s": 27078, "text": "Returns the minimum value from two values" }, { "code": null, "e": 27162, "s": 27120, "text": "Returns the maximum value from two values" }, { "code": null, "e": 27187, "s": 27162, "text": "Returns the sum of value" }, { "code": null, "e": 27220, "s": 27187, "text": "Returns the number of input rows" }, { "code": null, "e": 27254, "s": 27220, "text": "Returns the count of input values" }, { "code": null, "e": 27281, "s": 27254, "text": "Returns the checksum for x" }, { "code": null, "e": 27315, "s": 27281, "text": "Returns the arbitrary value for x" }, { "code": null, "e": 27362, "s": 27315, "text": "Following table lists out the Color functions." }, { "code": null, "e": 27418, "s": 27362, "text": "Renders a single bar using rgb low_color and high_color" }, { "code": null, "e": 27463, "s": 27418, "text": "Renders a single bar for the specified width" }, { "code": null, "e": 27510, "s": 27463, "text": "Returns the color value for the entered string" }, { "code": null, "e": 27574, "s": 27510, "text": "Renders value x using the specific color using ANSI color codes" }, { "code": null, "e": 27661, "s": 27574, "text": "Accepts boolean value b and renders a green true or a red false using ANSI color codes" }, { "code": null, "e": 27683, "s": 27661, "text": "rgb(red, green, blue)" }, { "code": null, "e": 27810, "s": 27683, "text": "Returns a color value capturing the RGB value of three component color values supplied as int parameters ranging from 0 to 255" }, { "code": null, "e": 27861, "s": 27810, "text": "The following table lists out the Array functions." }, { "code": null, "e": 27895, "s": 27861, "text": "Finds the max element in an array" }, { "code": null, "e": 27929, "s": 27895, "text": "Finds the min element in an array" }, { "code": null, "e": 27960, "s": 27929, "text": "Sorts the elements in an array" }, { "code": null, "e": 28003, "s": 27960, "text": "Removes the specific element from an array" }, { "code": null, "e": 28027, "s": 28003, "text": "Concatenates two arrays" }, { "code": null, "e": 28121, "s": 28027, "text": "Finds the given elements in an array. True will be returned if it is present, otherwise false" }, { "code": null, "e": 28172, "s": 28121, "text": "Find the position of the given element in an array" }, { "code": null, "e": 28216, "s": 28172, "text": "Performs an intersection between two arrays" }, { "code": null, "e": 28251, "s": 28216, "text": "Returns the array element position" }, { "code": null, "e": 28302, "s": 28251, "text": "Slices the array elements with the specific length" }, { "code": null, "e": 28352, "s": 28302, "text": "The following table lists out Teradata functions." }, { "code": null, "e": 28409, "s": 28352, "text": "Returns the index of the string with the given substring" }, { "code": null, "e": 28489, "s": 28409, "text": "Returns the substring of the given string. You can specify the start index here" }, { "code": null, "e": 28585, "s": 28489, "text": "Returns the substring of the given string for the specific start index and length of the string" }, { "code": null, "e": 28650, "s": 28585, "text": "The MySQL connector is used to query an external MySQL database." }, { "code": null, "e": 28677, "s": 28650, "text": "MySQL server installation." }, { "code": null, "e": 28914, "s": 28677, "text": "Hopefully you have installed mysql server on your machine. To enable mysql properties on Presto server, you must create a file “mysql.properties” in “etc/catalog” directory. Issue the following command to create a mysql.properties file." }, { "code": null, "e": 29086, "s": 28914, "text": "$ cd etc \n$ cd catalog \n$ vi mysql.properties \n\nconnector.name = mysql \nconnection-url = jdbc:mysql://localhost:3306 \nconnection-user = root \nconnection-password = pwd \n" }, { "code": null, "e": 29207, "s": 29086, "text": "Save the file and quit the terminal. In the above file, you must enter your mysql password in connection-password field." }, { "code": null, "e": 29276, "s": 29207, "text": "Open MySQL server and create a database using the following command." }, { "code": null, "e": 29302, "s": 29276, "text": "create database tutorials" }, { "code": null, "e": 29437, "s": 29302, "text": "Now you have created “tutorials” database in the server. To enable database type, use the command “use tutorials” in the query window." }, { "code": null, "e": 29490, "s": 29437, "text": "Let’s create a simple table on “tutorials” database." }, { "code": null, "e": 29574, "s": 29490, "text": "create table author(auth_id int not null, auth_name varchar(50),topic varchar(100))" }, { "code": null, "e": 29646, "s": 29574, "text": "After creating a table, insert three records using the following query." }, { "code": null, "e": 29803, "s": 29646, "text": "insert into author values(1,'Doug Cutting','Hadoop') \ninsert into author values(2,’James Gosling','java') \ninsert into author values(3,'Dennis Ritchie’,'C')" }, { "code": null, "e": 29858, "s": 29803, "text": "To retrieve all the records, type the following query." }, { "code": null, "e": 29879, "s": 29858, "text": "select * from author" }, { "code": null, "e": 30011, "s": 29879, "text": "auth_id auth_name topic \n1 Doug Cutting Hadoop \n2 James Gosling java \n3 Dennis Ritchie C \n" }, { "code": null, "e": 30117, "s": 30011, "text": "As of now, you have queried data using MySQL server. Let’s connect Mysql storage plugin to Presto server." }, { "code": null, "e": 30183, "s": 30117, "text": "Type the following command to connect MySql plugin on Presto CLI." }, { "code": null, "e": 30253, "s": 30183, "text": "./presto --server localhost:8080 --catalog mysql --schema tutorials \n" }, { "code": null, "e": 30294, "s": 30253, "text": "You will receive the following response." }, { "code": null, "e": 30314, "s": 30294, "text": "presto:tutorials> \n" }, { "code": null, "e": 30365, "s": 30314, "text": "Here “tutorials” refers to schema in mysql server." }, { "code": null, "e": 30446, "s": 30365, "text": "To list out all the schemas in mysql, type the following query in Presto server." }, { "code": null, "e": 30489, "s": 30446, "text": "presto:tutorials> show schemas from mysql;" }, { "code": null, "e": 30585, "s": 30489, "text": " Schema \n-------------------- \n information_schema \n performance_schema \n sys \n tutorials\n" }, { "code": null, "e": 30698, "s": 30585, "text": "From this result, we can conclude the first three schemas as predefined and the last one as created by yourself." }, { "code": null, "e": 30760, "s": 30698, "text": "Following query lists out all the tables in tutorials schema." }, { "code": null, "e": 30813, "s": 30760, "text": "presto:tutorials> show tables from mysql.tutorials; " }, { "code": null, "e": 30841, "s": 30813, "text": " Table \n-------- \n author\n" }, { "code": null, "e": 30958, "s": 30841, "text": "We have created only one table in this schema. If you have created multiple tables, it will list out all the tables." }, { "code": null, "e": 31014, "s": 30958, "text": "To describe the table fields, type the following query." }, { "code": null, "e": 31065, "s": 31014, "text": "presto:tutorials> describe mysql.tutorials.author;" }, { "code": null, "e": 31227, "s": 31065, "text": " Column | Type | Comment \n-----------+--------------+--------- \n auth_id | integer | \n auth_name | varchar(50) | \n topic | varchar(100) |\n" }, { "code": null, "e": 31288, "s": 31227, "text": "presto:tutorials> show columns from mysql.tutorials.author; " }, { "code": null, "e": 31450, "s": 31288, "text": " Column | Type | Comment \n-----------+--------------+--------- \n auth_id | integer | \n auth_name | varchar(50) | \n topic | varchar(100) |\n" }, { "code": null, "e": 31520, "s": 31450, "text": "To fetch all the records from mysql table, issue the following query." }, { "code": null, "e": 31577, "s": 31520, "text": "presto:tutorials> select * from mysql.tutorials.author; " }, { "code": null, "e": 31750, "s": 31577, "text": "auth_id | auth_name | topic \n---------+----------------+-------- \n 1 | Doug Cutting | Hadoop \n 2 | James Gosling | java \n 3 | Dennis Ritchie | C\n" }, { "code": null, "e": 31817, "s": 31750, "text": "From this result, you can retrieve mysql server records in Presto." }, { "code": null, "e": 31913, "s": 31817, "text": "Mysql connector doesn’t support create table query but you can create a table using as command." }, { "code": null, "e": 32010, "s": 31913, "text": "presto:tutorials> create table mysql.tutorials.sample as \nselect * from mysql.tutorials.author; " }, { "code": null, "e": 32032, "s": 32010, "text": "CREATE TABLE: 3 rows\n" }, { "code": null, "e": 32150, "s": 32032, "text": "You can’t insert rows directly because this connector has some limitations. It cannot support the following queries −" }, { "code": null, "e": 32157, "s": 32150, "text": "create" }, { "code": null, "e": 32164, "s": 32157, "text": "insert" }, { "code": null, "e": 32171, "s": 32164, "text": "update" }, { "code": null, "e": 32178, "s": 32171, "text": "delete" }, { "code": null, "e": 32183, "s": 32178, "text": "drop" }, { "code": null, "e": 32257, "s": 32183, "text": "To view the records in the newly created table, type the following query." }, { "code": null, "e": 32314, "s": 32257, "text": "presto:tutorials> select * from mysql.tutorials.sample; " }, { "code": null, "e": 32487, "s": 32314, "text": "auth_id | auth_name | topic \n---------+----------------+-------- \n 1 | Doug Cutting | Hadoop \n 2 | James Gosling | java \n 3 | Dennis Ritchie | C\n" }, { "code": null, "e": 32671, "s": 32487, "text": "Java Management Extensions (JMX) gives information about the Java Virtual Machine and software running inside JVM. The JMX connector is used to query JMX information in Presto server." }, { "code": null, "e": 32795, "s": 32671, "text": "As we have already enabled “jmx.properties” file under “etc/catalog” directory. Now connect Prest CLI to enable JMX plugin." }, { "code": null, "e": 32858, "s": 32795, "text": "$ ./presto --server localhost:8080 --catalog jmx --schema jmx " }, { "code": null, "e": 32899, "s": 32858, "text": "You will receive the following response." }, { "code": null, "e": 32913, "s": 32899, "text": "presto:jmx> \n" }, { "code": null, "e": 32977, "s": 32913, "text": "To list out all the schemas in “jmx”, type the following query." }, { "code": null, "e": 33013, "s": 32977, "text": "presto:jmx> show schemas from jmx; " }, { "code": null, "e": 33081, "s": 33013, "text": " Schema \n-------------------- \n information_schema \n current\n" }, { "code": null, "e": 33152, "s": 33081, "text": "To view the tables in the “current” schema, use the following command." }, { "code": null, "e": 33195, "s": 33152, "text": "presto:jmx> show tables from jmx.current; " }, { "code": null, "e": 33782, "s": 33195, "text": " Table \n------------------------------------------------------------------------------\n com.facebook.presto.execution.scheduler:name = nodescheduler\n com.facebook.presto.execution:name = queryexecution\n com.facebook.presto.execution:name = querymanager\n com.facebook.presto.execution:name = remotetaskfactory\n com.facebook.presto.execution:name = taskexecutor\n com.facebook.presto.execution:name = taskmanager\n com.facebook.presto.execution:type = queryqueue,name = global,expansion = global\n ..................\n ...................\n" }, { "code": null, "e": 33853, "s": 33782, "text": "presto:jmx> select * from jmx.current.”java.lang:type = compilation\"; " }, { "code": null, "e": 34252, "s": 33853, "text": "node | compilationtimemonitoringsupported | name | objectname | totalcompilationti\n--------------------------------------+------------------------------------+--------------------------------+----------------------------+-------------------\nffffffff-ffff-ffff-ffff-ffffffffffff | true | HotSpot 64-Bit Tiered Compilers | java.lang:type=Compilation | 1276\n" }, { "code": null, "e": 34340, "s": 34252, "text": "presto:jmx> select * from jmx.current.\"com.facebook.presto.server:name = taskresource\";" }, { "code": null, "e": 34767, "s": 34340, "text": " node | readfromoutputbuffertime.alltime.count \n | readfromoutputbuffertime.alltime.max | readfromoutputbuffertime.alltime.maxer\n --------------------------------------+---------------------------------------+--------------------------------------+--------------------------------------- \n ffffffff-ffff-ffff-ffff-ffffffffffff | 92.0 | 1.009106149 | \n" }, { "code": null, "e": 34840, "s": 34767, "text": "The Hive connector allows querying data stored in a Hive data warehouse." }, { "code": null, "e": 34847, "s": 34840, "text": "Hadoop" }, { "code": null, "e": 34852, "s": 34847, "text": "Hive" }, { "code": null, "e": 35025, "s": 34852, "text": "Hopefully you have installed Hadoop and Hive on your machine. Start all the services one by one in the new terminal. Then, start hive metastore using the following command," }, { "code": null, "e": 35051, "s": 35025, "text": "hive --service metastore\n" }, { "code": null, "e": 35119, "s": 35051, "text": "Presto uses Hive metastore service to get the hive table’s details." }, { "code": null, "e": 35209, "s": 35119, "text": "Create a file “hive.properties” under “etc/catalog” directory. Use the following command." }, { "code": null, "e": 35331, "s": 35209, "text": "$ cd etc \n$ cd catalog \n$ vi hive.properties \n\nconnector.name = hive-cdh4 \nhive.metastore.uri = thrift://localhost:9083\n" }, { "code": null, "e": 35398, "s": 35331, "text": "After making all the changes, save the file and quit the terminal." }, { "code": null, "e": 35452, "s": 35398, "text": "Create a database in Hive using the following query −" }, { "code": null, "e": 35484, "s": 35452, "text": "hive> CREATE SCHEMA tutorials; " }, { "code": null, "e": 35569, "s": 35484, "text": "After the database is created, you can verify it using the “show databases” command." }, { "code": null, "e": 35667, "s": 35569, "text": "Create Table is a statement used to create a table in Hive. For example, use the following query." }, { "code": null, "e": 35773, "s": 35667, "text": "hive> create table author(auth_id int, auth_name varchar(50), \ntopic varchar(100) STORED AS SEQUENCEFILE;" }, { "code": null, "e": 35832, "s": 35773, "text": "Following query is used to insert records in hive’s table." }, { "code": null, "e": 35949, "s": 35832, "text": "hive> insert into table author values (1,’ Doug Cutting’,Hadoop),\n(2,’ James Gosling’,java),(3,’ Dennis Ritchie’,C);" }, { "code": null, "e": 36034, "s": 35949, "text": "You can start Presto CLI to connect Hive storage plugin using the following command." }, { "code": null, "e": 36105, "s": 36034, "text": "$ ./presto --server localhost:8080 --catalog hive —schema tutorials; \n" }, { "code": null, "e": 36146, "s": 36105, "text": "You will receive the following response." }, { "code": null, "e": 36166, "s": 36146, "text": "presto:tutorials >\n" }, { "code": null, "e": 36241, "s": 36166, "text": "To list out all the schemas in Hive connector, type the following command." }, { "code": null, "e": 36284, "s": 36241, "text": "presto:tutorials > show schemas from hive;" }, { "code": null, "e": 36307, "s": 36284, "text": "default \n\ntutorials \n" }, { "code": null, "e": 36382, "s": 36307, "text": "To list out all the tables in “tutorials” schema, use the following query." }, { "code": null, "e": 36435, "s": 36382, "text": "presto:tutorials > show tables from hive.tutorials; " }, { "code": null, "e": 36443, "s": 36435, "text": "author\n" }, { "code": null, "e": 36511, "s": 36443, "text": "Following query is used to fetch all the records from hive’s table." }, { "code": null, "e": 36568, "s": 36511, "text": "presto:tutorials > select * from hive.tutorials.author; " }, { "code": null, "e": 36741, "s": 36568, "text": "auth_id | auth_name | topic \n---------+----------------+-------- \n 1 | Doug Cutting | Hadoop \n 2 | James Gosling | java \n 3 | Dennis Ritchie | C\n" }, { "code": null, "e": 36826, "s": 36741, "text": "The Kafka Connector for Presto allows to access data from Apache Kafka using Presto." }, { "code": null, "e": 36900, "s": 36826, "text": "Download and install the latest version of the following Apache projects." }, { "code": null, "e": 36917, "s": 36900, "text": "Apache ZooKeeper" }, { "code": null, "e": 36930, "s": 36917, "text": "Apache Kafka" }, { "code": null, "e": 36982, "s": 36930, "text": "Start ZooKeeper server using the following command." }, { "code": null, "e": 37043, "s": 36982, "text": "$ bin/zookeeper-server-start.sh config/zookeeper.properties\n" }, { "code": null, "e": 37079, "s": 37043, "text": "Now, ZooKeeper starts port on 2181." }, { "code": null, "e": 37140, "s": 37079, "text": "Start Kafka in another terminal using the following command." }, { "code": null, "e": 37194, "s": 37140, "text": "$ bin/kafka-server-start.sh config/server.properties\n" }, { "code": null, "e": 37244, "s": 37194, "text": "After kafka starts, it uses the port number 9092." }, { "code": null, "e": 37362, "s": 37244, "text": "$ curl -o kafka-tpch \nhttps://repo1.maven.org/maven2/de/softwareforge/kafka_tpch_0811/1.0/kafka_tpch_ \n0811-1.0.sh \n" }, { "code": null, "e": 37491, "s": 37362, "text": "Now you have downloaded the loader from Maven central using the above command. You will get a similar response as the following." }, { "code": null, "e": 38162, "s": 37491, "text": "% Total % Received % Xferd Average Speed Time Time Time Current \n Dload Upload Total Spent Left Speed \n 0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0 \n 5 21.6M 5 1279k 0 0 83898 0 0:04:30 0:00:15 0:04:15 129k\n 6 21.6M 6 1407k 0 0 86656 0 0:04:21 0:00:16 0:04:05 131k \n 24 21.6M 24 5439k 0 0 124k 0 0:02:57 0:00:43 0:02:14 175k \n 24 21.6M 24 5439k 0 0 124k 0 0:02:58 0:00:43 0:02:15 160k \n 25 21.6M 25 5736k 0 0 128k 0 0:02:52 0:00:44 0:02:08 181k \n .............................\n" }, { "code": null, "e": 38216, "s": 38162, "text": "Then, make it executable using the following command," }, { "code": null, "e": 38240, "s": 38216, "text": "$ chmod 755 kafka-tpch\n" }, { "code": null, "e": 38341, "s": 38240, "text": "Run the kafka-tpch program to preload a number of topics with tpch data using the following command." }, { "code": null, "e": 38420, "s": 38341, "text": "$ ./kafka-tpch load --brokers localhost:9092 --prefix tpch. --tpch-type tiny \n" }, { "code": null, "e": 39271, "s": 38420, "text": "2016-07-13T16:15:52.083+0530 INFO main io.airlift.log.Logging Logging \nto stderr\n2016-07-13T16:15:52.124+0530 INFO main de.softwareforge.kafka.LoadCommand\nProcessing tables: [customer, orders, lineitem, part, partsupp, supplier,\nnation, region]\n2016-07-13T16:15:52.834+0530 INFO pool-1-thread-1\nde.softwareforge.kafka.LoadCommand Loading table 'customer' into topic 'tpch.customer'...\n2016-07-13T16:15:52.834+0530 INFO pool-1-thread-2\nde.softwareforge.kafka.LoadCommand Loading table 'orders' into topic 'tpch.orders'...\n2016-07-13T16:15:52.834+0530 INFO pool-1-thread-3\nde.softwareforge.kafka.LoadCommand Loading table 'lineitem' into topic 'tpch.lineitem'...\n2016-07-13T16:15:52.834+0530 INFO pool-1-thread-4\nde.softwareforge.kafka.LoadCommand Loading table 'part' into topic 'tpch.part'...\n...........................\n............................\n" }, { "code": null, "e": 39345, "s": 39271, "text": "Now, Kafka tables customers,orders,supplier, etc., are loaded using tpch." }, { "code": null, "e": 39426, "s": 39345, "text": "Let’s add the following Kafka connector configuration settings on Presto server." }, { "code": null, "e": 39649, "s": 39426, "text": "connector.name = kafka \n\nkafka.nodes = localhost:9092 \n\nkafka.table-names = tpch.customer,tpch.orders,tpch.lineitem,tpch.part,tpch.partsupp, \ntpch.supplier,tpch.nation,tpch.region \n\nkafka.hide-internal-columns = false \n" }, { "code": null, "e": 39727, "s": 39649, "text": "In the above configuration, Kafka tables are loaded using Kafka-tpch program." }, { "code": null, "e": 39773, "s": 39727, "text": "Start Presto CLI using the following command," }, { "code": null, "e": 39839, "s": 39773, "text": "$ ./presto --server localhost:8080 --catalog kafka —schema tpch;\n" }, { "code": null, "e": 39933, "s": 39839, "text": "Here “tpch\" is a schema for Kafka connector and you will receive a response as the following." }, { "code": null, "e": 39947, "s": 39933, "text": "presto:tpch>\n" }, { "code": null, "e": 40006, "s": 39947, "text": "Following query lists out all the tables in “tpch” schema." }, { "code": null, "e": 40032, "s": 40006, "text": "presto:tpch> show tables;" }, { "code": null, "e": 40131, "s": 40032, "text": " Table \n---------- \n customer \n lineitem \n nation \n orders\n part \n partsupp \n region \n supplier \n" }, { "code": null, "e": 40175, "s": 40131, "text": "Following query describes “customer” table." }, { "code": null, "e": 40208, "s": 40175, "text": "presto:tpch> describe customer; " }, { "code": null, "e": 40949, "s": 40208, "text": " Column | Type | Comment \n-------------------+---------+--------------------------------------------- \n _partition_id | bigint | Partition Id \n _partition_offset | bigint | Offset for the message within the partition \n _segment_start | bigint | Segment start offset \n _segment_end | bigint | Segment end offset \n _segment_count | bigint | Running message count per segment \n _key | varchar | Key text \n _key_corrupt | boolean | Key data is corrupt \n _key_length | bigint | Total number of key bytes \n _message | varchar | Message text \n _message_corrupt | boolean | Message data is corrupt \n _message_length | bigint | Total number of message bytes \n" }, { "code": null, "e": 41009, "s": 40949, "text": "Presto’s JDBC interface is used to access Java application." }, { "code": null, "e": 41039, "s": 41009, "text": "Install presto-jdbc-0.150.jar" }, { "code": null, "e": 41106, "s": 41039, "text": "You can download the JDBC jar file by visiting the following link," }, { "code": null, "e": 41176, "s": 41106, "text": "https://repo1.maven.org/maven2/com/facebook/presto/presto-jdbc/0.150/" }, { "code": null, "e": 41267, "s": 41176, "text": "After the jar file has been downloaded, add it to the class path of your Java application." }, { "code": null, "e": 41328, "s": 41267, "text": "Let’s create a simple java application using JDBC interface." }, { "code": null, "e": 41359, "s": 41328, "text": "Coding − PrestoJdbcSample.java" }, { "code": null, "e": 42704, "s": 41359, "text": "import java.sql.*; \nimport com.facebook.presto.jdbc.PrestoDriver; \n\n//import presto jdbc driver packages here. \npublic class PrestoJdbcSample { \n public static void main(String[] args) { \n Connection connection = null; \n Statement statement = null; \n try { \n \n Class.forName(\"com.facebook.presto.jdbc.PrestoDriver\"); \n connection = DriverManager.getConnection(\n \"jdbc:presto://localhost:8080/mysql/tutorials\", \"tutorials\", “\"); \n \n //connect mysql server tutorials database here \n statement = connection.createStatement(); \n String sql; \n sql = \"select auth_id, auth_name from mysql.tutorials.author”; \n \n //select mysql table author table two columns \n ResultSet resultSet = statement.executeQuery(sql); \n while(resultSet.next()){ \n int id = resultSet.getInt(\"auth_id\"); \n String name = resultSet.getString(“auth_name\"); \n System.out.print(\"ID: \" + id + \";\\nName: \" + name + \"\\n\"); \n } \n \n resultSet.close(); \n statement.close(); \n connection.close(); \n \n }catch(SQLException sqlException){ \n sqlException.printStackTrace(); \n }catch(Exception exception){ \n exception.printStackTrace(); \n } \n } \n}" }, { "code": null, "e": 42870, "s": 42704, "text": "Save the file and quit the application. Now, start Presto server in one terminal and open a new terminal to compile and execute the result. Following are the steps −" }, { "code": null, "e": 42959, "s": 42870, "text": "~/Workspace/presto/presto-jdbc $ javac -cp presto-jdbc-0.149.jar PrestoJdbcSample.java\n" }, { "code": null, "e": 43044, "s": 42959, "text": "~/Workspace/presto/presto-jdbc $ java -cp .:presto-jdbc-0.149.jar PrestoJdbcSample\n" }, { "code": null, "e": 43167, "s": 43044, "text": "INFO: Logging initialized @146ms \nID: 1; \nName: Doug Cutting \nID: 2; \nName: James Gosling \nID: 3; \nName: Dennis Ritchie \n" }, { "code": null, "e": 43225, "s": 43167, "text": "Create a Maven project to develop Presto custom function." }, { "code": null, "e": 43301, "s": 43225, "text": "Create SimpleFunctionsFactory class to implement FunctionFactory interface." }, { "code": null, "e": 43995, "s": 43301, "text": "package com.tutorialspoint.simple.functions; \n\nimport com.facebook.presto.metadata.FunctionFactory; \nimport com.facebook.presto.metadata.FunctionListBuilder; \nimport com.facebook.presto.metadata.SqlFunction; \nimport com.facebook.presto.spi.type.TypeManager; \nimport java.util.List; \n\npublic class SimpleFunctionFactory implements FunctionFactory { \n \n private final TypeManager typeManager; \n public SimpleFunctionFactory(TypeManager typeManager) { \n this.typeManager = typeManager; \n } \n @Override \n \n public List<SqlFunction> listFunctions() { \n return new FunctionListBuilder(typeManager) \n .scalar(SimpleFunctions.class) \n .getFunctions(); \n } \n}" }, { "code": null, "e": 44063, "s": 43995, "text": "Create a SimpleFunctionsPlugin class to implement Plugin interface." }, { "code": null, "e": 44951, "s": 44063, "text": "package com.tutorialspoint.simple.functions; \n\nimport com.facebook.presto.metadata.FunctionFactory; \nimport com.facebook.presto.spi.Plugin; \nimport com.facebook.presto.spi.type.TypeManager; \nimport com.google.common.collect.ImmutableList; \nimport javax.inject.Inject; \nimport java.util.List; \nimport static java.util.Objects.requireNonNull; \n\npublic class SimpleFunctionsPlugin implements Plugin { \n private TypeManager typeManager; \n @Inject \n \n public void setTypeManager(TypeManager typeManager) { \n this.typeManager = requireNonNull(typeManager, \"typeManager is null”); \n //Inject TypeManager class here \n } \n @Override \n \n public <T> List<T> getServices(Class<T> type){ \n if (type == FunctionFactory.class) { \n return ImmutableList.of(type.cast(new SimpleFunctionFactory(typeManager))); \n } \n return ImmutableList.of(); \n } \n}" }, { "code": null, "e": 45024, "s": 44951, "text": "Create a resource file which is specified in the implementation package." }, { "code": null, "e": 45085, "s": 45024, "text": "(com.tutorialspoint.simple.functions.SimpleFunctionsPlugin)\n" }, { "code": null, "e": 45145, "s": 45085, "text": "Now move to the resource file location @ /path/to/resource/" }, { "code": null, "e": 45167, "s": 45145, "text": "Then add the changes," }, { "code": null, "e": 45200, "s": 45167, "text": "com.facebook.presto.spi.Plugin \n" }, { "code": null, "e": 45248, "s": 45200, "text": "Add the following dependencies to pom.xml file." }, { "code": null, "e": 46989, "s": 45248, "text": "<?xml version = \"1.0\"?> \n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n \n <modelVersion>4.0.0</modelVersion> \n <groupId>com.tutorialspoint.simple.functions</groupId> \n <artifactId>presto-simple-functions</artifactId> \n <packaging>jar</packaging> \n <version>1.0</version>\n <name>presto-simple-functions</name>\n <description>Simple test functions for Presto</description> \n <properties> \n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties> \n <dependencies> \n <dependency> \n <groupId>com.facebook.presto</groupId> \n <artifactId>presto-spi</artifactId>\n <version>0.149</version> \n </dependency> \n <dependency> \n <groupId>com.facebook.presto</groupId> \n <artifactId>presto-main</artifactId> \n <version>0.149</version> \n </dependency> \n <dependency> \n <groupId>javax.inject</groupId> \n <artifactId>javax.inject</artifactId> \n <version>1</version> \n </dependency> \n <dependency> \n <groupId>com.google.guava</groupId> \n <artifactId>guava</artifactId> \n <version>19.0</version> \n </dependency> \n </dependencies> \n <build> \n <finalName>presto-simple-functions</finalName> \n <plugins> \n <!-- Make this jar executable --> \n <plugin> \n <groupId>org.apache.maven.plugins</groupId> \n <artifactId>maven-jar-plugin</artifactId> \n <version>2.3.2</version> \n </plugin> \n </plugins> \n </build> \n</project>" }, { "code": null, "e": 47043, "s": 46989, "text": "Create SimpleFunctions class using Presto attributes." }, { "code": null, "e": 47786, "s": 47043, "text": "package com.tutorialspoint.simple.functions; \n\nimport com.facebook.presto.operator.Description; \nimport com.facebook.presto.operator.scalar.ScalarFunction; \nimport com.facebook.presto.operator.scalar.StringFunctions; \nimport com.facebook.presto.spi.type.StandardTypes; \nimport com.facebook.presto.type.LiteralParameters; \nimport com.facebook.presto.type.SqlType; \n\npublic final class SimpleFunctions { \n private SimpleFunctions() { \n } \n \n @Description(\"Returns summation of two numbers\") \n @ScalarFunction(“mysum\") \n //function name \n @SqlType(StandardTypes.BIGINT) \n \n public static long sum(@SqlType(StandardTypes.BIGINT) long num1, \n @SqlType(StandardTypes.BIGINT) long num2) { \n return num1 + num2; \n } \n}" }, { "code": null, "e": 47970, "s": 47786, "text": "After the application is created compile and execute the application. It will produce the JAR file. Copy the file and move the JAR file into the target Presto server plugin directory." }, { "code": null, "e": 47983, "s": 47970, "text": "mvn compile\n" }, { "code": null, "e": 47996, "s": 47983, "text": "mvn package\n" }, { "code": null, "e": 48114, "s": 47996, "text": "Now restart Presto server and connect Presto client. Then execute the custom function application as explained below," }, { "code": null, "e": 48159, "s": 48114, "text": "$ ./presto --catalog mysql --schema default\n" }, { "code": null, "e": 48196, "s": 48159, "text": "presto:default> select mysum(10,10);" }, { "code": null, "e": 48221, "s": 48196, "text": " _col0 \n------- \n 20 \n" }, { "code": null, "e": 48256, "s": 48221, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 48275, "s": 48256, "text": " Arnab Chakraborty" }, { "code": null, "e": 48310, "s": 48275, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 48331, "s": 48310, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 48364, "s": 48331, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 48377, "s": 48364, "text": " Nilay Mehta" }, { "code": null, "e": 48412, "s": 48377, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 48430, "s": 48412, "text": " Bigdata Engineer" }, { "code": null, "e": 48463, "s": 48430, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 48481, "s": 48463, "text": " Bigdata Engineer" }, { "code": null, "e": 48514, "s": 48481, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 48532, "s": 48514, "text": " Bigdata Engineer" }, { "code": null, "e": 48539, "s": 48532, "text": " Print" }, { "code": null, "e": 48550, "s": 48539, "text": " Add Notes" } ]
FuzzyWuzzy: How to Measure String Distance on Python | by Luciano Strika | Towards Data Science
Python’s FuzzyWuzzy library is used for measuring the similarity between two strings. Here’s how you can start using it too. Sometimes, we need to see whether two strings are the same. When comparing an entered password’s hash to the one stored in your login database, ‘similarity’ just won’t cut it. Other times, however, things can get a bit... fuzzier. If my customer’s name is Albert Thompson, but he pays with a Credit Card under the name of Albert G. Thompson, should I be calling the police to report fraud? Should “The Lord of the Rings II: The Two Towers” and “The Lord of the Rings 2: the 2 Towers” be treated as two completely separate books by a website? Are Austria and Australia really two different countries? Okay, I may have gotten carried away with that last one, but you get the idea. What we want is some function that measures how similar two strings are, but is robust to small changes. This problem is as common as it sounds: scientists have been coming up with solutions to it for a long while. One of the most intuitive ones is the Jaccard distance. It can be generalized to a distance measure for any two sets. It is measured with the following formula: That is, how many elements are on either set, but not shared by both, divided by the total count of distinct elements. For instance, given the strings “Albert” and “Alberto”, it will report a similarity of 85.7%, since they share 6 letters out of a total of 7. However, this is not a measure specifically tailored for strings. It will fail in many use-cases, since it doesn’t really take ordering into account. For example two anagrams, like “rail safety” and “fairy tales”, will always have a 100% match, even if those strings are quite different. Invented by the Russian Scientist Vladimir Levenshtein in the ’60s, this measure is a bit more intuitive: it counts how many substitutions are needed, given a string u, to transform it into v. For this method, a substitution is defined as: Erasing a character. Adding one. Replacing a character with another one. The minimum amount of these operations that need to be done to u in order to turn it into v, correspond to the Levenshtein distance between those two strings. It can be obtained recursively with this formula: Where i and j are indexes to the last character of the substring we’ll be comparing. The second term in the last expression is equal to 1 if those characters are different, and 0 if they’re the same. This is the measure Python’s FuzzyWuzzy library uses. To obtain the similarity ratio between two strings, all we have to do is this: from fuzzywuzzy import fuzzsimilarity = fuzz.ratio("hello","world") You probably noticed I said ratio. The ratio method will always return a number between 0 and 100 (yeah, I’d have preferred it to be between 0 and 1, or call it a percentage, but to each their own). It can be shown that the Levenshtein distance is at most the length of the longest string: replace all characters in the shorter one with the first part of the longer one, and then add the remaining ones. That’s how we can normalize the distance to return a ratio, so that the number won’t fluctuate enormously given inputs with different sizes. This solves some of the previously mentioned problems: fuzz.ratio("Albert Thompson", "Albert G. Thompson") #91%fuzz.ratio("The Lord of the Rings II: The Two Towers", "The Lord of the Rings 2: the 2 Towers") #88% Even if it may bring a few new ones: #88% for two different countriesfuzz.ratio("Austria","Australia")#57% but it's the same countryfuzz.ratio("Czechia","Czech Republic") Python’s FuzzyWuzzy library provides us not only with the vanilla Levenshtein distance, but also with a few other methods we can make use of. The partial_ratio method calculates the FuzzyWuzzy ratio for all substrings of the longer string with the length of the shorter one, and then returns the highest match. For instance, fuzz.partial_ratio("abc","a") == min([fuzz.ratio( char, "a") for char in "abc"]) This has some interesting effects: fuzz.partial_ratio("Thomas and His Friends", "Thomas") #100%fuzz.partial_ratio("Batman vs Superman", "Batman") #100% Effectively, the partial_ratio method could be a fuzzy replacement to the contains string method, just as the regular ratio may replace the equals method. However, it will fail for strings that are similar, but whose words appear in a different order. Even a slight order change will break it. #72% with basically the same ideafuzz.partial_ratio("Peanut Butter and Jelly", "Jelly and Peanut Butter") #86% with a random (carefully selected) stringfuzz.partial_ratio("Peanut Butter and Jelly", "Otter and Hell") The Token Sort Ratio divides both strings into words, then joins those again alphanumerically, before calling the regular ratio on them. This means: fuzz.partial_ratio("Batman vs Superman", "Superman vs Batman") #100%fuzz.partial_ratio("a b c", "c b a") #100% The Token Set Ratio separates each string into words, turns both lists into sets (discarding repeated words) and then sorts those before doing the ratio. This way not only do we rule out shared words, we also account for repetitions. fuzz.token_set_ratio("fun","fun fun fun") #100%fuzz.token_set_ratio("Lord the Rings of", "Lord of the Rings") #100% Python’s FuzzyWuzzy library can be a very useful tool to have under your belt. Both for customer’s names matching, or acting as a poor man’s word embedding, it can save you a lot of trouble or help with your Machine Learning model’s feature engineering. However, since it requires preprocessing (like turning both strings to lowercase) and doesn’t take synonyms into account, it may not be the best solution for cases where actual NLP or Clustering methods may be needed. I hope you’ve found this article helpful, and let me know if you find another use for FuzzyWuzzy in your job! Follow me on Twitter or Medium to stay up to date with more Python tutorials, tips and tricks. If you found this article useful, please consider supporting my site by helping me pay for its hosting. Your donation will be of great help. Originally published at www.datastuff.tech on April 15, 2019.
[ { "code": null, "e": 297, "s": 172, "text": "Python’s FuzzyWuzzy library is used for measuring the similarity between two strings. Here’s how you can start using it too." }, { "code": null, "e": 473, "s": 297, "text": "Sometimes, we need to see whether two strings are the same. When comparing an entered password’s hash to the one stored in your login database, ‘similarity’ just won’t cut it." }, { "code": null, "e": 528, "s": 473, "text": "Other times, however, things can get a bit... fuzzier." }, { "code": null, "e": 897, "s": 528, "text": "If my customer’s name is Albert Thompson, but he pays with a Credit Card under the name of Albert G. Thompson, should I be calling the police to report fraud? Should “The Lord of the Rings II: The Two Towers” and “The Lord of the Rings 2: the 2 Towers” be treated as two completely separate books by a website? Are Austria and Australia really two different countries?" }, { "code": null, "e": 976, "s": 897, "text": "Okay, I may have gotten carried away with that last one, but you get the idea." }, { "code": null, "e": 1191, "s": 976, "text": "What we want is some function that measures how similar two strings are, but is robust to small changes. This problem is as common as it sounds: scientists have been coming up with solutions to it for a long while." }, { "code": null, "e": 1352, "s": 1191, "text": "One of the most intuitive ones is the Jaccard distance. It can be generalized to a distance measure for any two sets. It is measured with the following formula:" }, { "code": null, "e": 1471, "s": 1352, "text": "That is, how many elements are on either set, but not shared by both, divided by the total count of distinct elements." }, { "code": null, "e": 1613, "s": 1471, "text": "For instance, given the strings “Albert” and “Alberto”, it will report a similarity of 85.7%, since they share 6 letters out of a total of 7." }, { "code": null, "e": 1679, "s": 1613, "text": "However, this is not a measure specifically tailored for strings." }, { "code": null, "e": 1901, "s": 1679, "text": "It will fail in many use-cases, since it doesn’t really take ordering into account. For example two anagrams, like “rail safety” and “fairy tales”, will always have a 100% match, even if those strings are quite different." }, { "code": null, "e": 2094, "s": 1901, "text": "Invented by the Russian Scientist Vladimir Levenshtein in the ’60s, this measure is a bit more intuitive: it counts how many substitutions are needed, given a string u, to transform it into v." }, { "code": null, "e": 2141, "s": 2094, "text": "For this method, a substitution is defined as:" }, { "code": null, "e": 2162, "s": 2141, "text": "Erasing a character." }, { "code": null, "e": 2174, "s": 2162, "text": "Adding one." }, { "code": null, "e": 2214, "s": 2174, "text": "Replacing a character with another one." }, { "code": null, "e": 2373, "s": 2214, "text": "The minimum amount of these operations that need to be done to u in order to turn it into v, correspond to the Levenshtein distance between those two strings." }, { "code": null, "e": 2423, "s": 2373, "text": "It can be obtained recursively with this formula:" }, { "code": null, "e": 2623, "s": 2423, "text": "Where i and j are indexes to the last character of the substring we’ll be comparing. The second term in the last expression is equal to 1 if those characters are different, and 0 if they’re the same." }, { "code": null, "e": 2677, "s": 2623, "text": "This is the measure Python’s FuzzyWuzzy library uses." }, { "code": null, "e": 2756, "s": 2677, "text": "To obtain the similarity ratio between two strings, all we have to do is this:" }, { "code": null, "e": 2824, "s": 2756, "text": "from fuzzywuzzy import fuzzsimilarity = fuzz.ratio(\"hello\",\"world\")" }, { "code": null, "e": 3023, "s": 2824, "text": "You probably noticed I said ratio. The ratio method will always return a number between 0 and 100 (yeah, I’d have preferred it to be between 0 and 1, or call it a percentage, but to each their own)." }, { "code": null, "e": 3228, "s": 3023, "text": "It can be shown that the Levenshtein distance is at most the length of the longest string: replace all characters in the shorter one with the first part of the longer one, and then add the remaining ones." }, { "code": null, "e": 3369, "s": 3228, "text": "That’s how we can normalize the distance to return a ratio, so that the number won’t fluctuate enormously given inputs with different sizes." }, { "code": null, "e": 3424, "s": 3369, "text": "This solves some of the previously mentioned problems:" }, { "code": null, "e": 3591, "s": 3424, "text": "fuzz.ratio(\"Albert Thompson\", \"Albert G. Thompson\") #91%fuzz.ratio(\"The Lord of the Rings II: The Two Towers\", \"The Lord of the Rings 2: the 2 Towers\") #88%" }, { "code": null, "e": 3628, "s": 3591, "text": "Even if it may bring a few new ones:" }, { "code": null, "e": 3762, "s": 3628, "text": "#88% for two different countriesfuzz.ratio(\"Austria\",\"Australia\")#57% but it's the same countryfuzz.ratio(\"Czechia\",\"Czech Republic\")" }, { "code": null, "e": 3904, "s": 3762, "text": "Python’s FuzzyWuzzy library provides us not only with the vanilla Levenshtein distance, but also with a few other methods we can make use of." }, { "code": null, "e": 4073, "s": 3904, "text": "The partial_ratio method calculates the FuzzyWuzzy ratio for all substrings of the longer string with the length of the shorter one, and then returns the highest match." }, { "code": null, "e": 4087, "s": 4073, "text": "For instance," }, { "code": null, "e": 4174, "s": 4087, "text": "fuzz.partial_ratio(\"abc\",\"a\") == min([fuzz.ratio( char, \"a\") for char in \"abc\"])" }, { "code": null, "e": 4209, "s": 4174, "text": "This has some interesting effects:" }, { "code": null, "e": 4326, "s": 4209, "text": "fuzz.partial_ratio(\"Thomas and His Friends\", \"Thomas\") #100%fuzz.partial_ratio(\"Batman vs Superman\", \"Batman\") #100%" }, { "code": null, "e": 4481, "s": 4326, "text": "Effectively, the partial_ratio method could be a fuzzy replacement to the contains string method, just as the regular ratio may replace the equals method." }, { "code": null, "e": 4620, "s": 4481, "text": "However, it will fail for strings that are similar, but whose words appear in a different order. Even a slight order change will break it." }, { "code": null, "e": 4855, "s": 4620, "text": "#72% with basically the same ideafuzz.partial_ratio(\"Peanut Butter and Jelly\", \"Jelly and Peanut Butter\") #86% with a random (carefully selected) stringfuzz.partial_ratio(\"Peanut Butter and Jelly\", \"Otter and Hell\")" }, { "code": null, "e": 4992, "s": 4855, "text": "The Token Sort Ratio divides both strings into words, then joins those again alphanumerically, before calling the regular ratio on them." }, { "code": null, "e": 5004, "s": 4992, "text": "This means:" }, { "code": null, "e": 5115, "s": 5004, "text": "fuzz.partial_ratio(\"Batman vs Superman\", \"Superman vs Batman\") #100%fuzz.partial_ratio(\"a b c\", \"c b a\") #100%" }, { "code": null, "e": 5269, "s": 5115, "text": "The Token Set Ratio separates each string into words, turns both lists into sets (discarding repeated words) and then sorts those before doing the ratio." }, { "code": null, "e": 5349, "s": 5269, "text": "This way not only do we rule out shared words, we also account for repetitions." }, { "code": null, "e": 5465, "s": 5349, "text": "fuzz.token_set_ratio(\"fun\",\"fun fun fun\") #100%fuzz.token_set_ratio(\"Lord the Rings of\", \"Lord of the Rings\") #100%" }, { "code": null, "e": 5719, "s": 5465, "text": "Python’s FuzzyWuzzy library can be a very useful tool to have under your belt. Both for customer’s names matching, or acting as a poor man’s word embedding, it can save you a lot of trouble or help with your Machine Learning model’s feature engineering." }, { "code": null, "e": 5937, "s": 5719, "text": "However, since it requires preprocessing (like turning both strings to lowercase) and doesn’t take synonyms into account, it may not be the best solution for cases where actual NLP or Clustering methods may be needed." }, { "code": null, "e": 6047, "s": 5937, "text": "I hope you’ve found this article helpful, and let me know if you find another use for FuzzyWuzzy in your job!" }, { "code": null, "e": 6142, "s": 6047, "text": "Follow me on Twitter or Medium to stay up to date with more Python tutorials, tips and tricks." }, { "code": null, "e": 6283, "s": 6142, "text": "If you found this article useful, please consider supporting my site by helping me pay for its hosting. Your donation will be of great help." } ]
Set the speed of the hover effect with CSS
To set the speed of the hover, use the transition-duration property. To set the hover, use the :hover selector. You can try to run the following code to speed the hover effect − Live Demo <!DOCTYPE html> <html> <head> <style> .btn { background-color: yellow; color: black; text-align: center; font-size: 15px; padding: 20px; border-radius: 15px; border: 3px dashed blue; transition-duration: 2s; } .btn:hover { background-color: orange; color: black; border: 3px solid blue; } </style> </head> <body> <h2>Result</h2> <p>Click below for result:</p> <button class = "btn">Result</button> </body> </html>
[ { "code": null, "e": 1174, "s": 1062, "text": "To set the speed of the hover, use the transition-duration property. To set the hover, use the :hover selector." }, { "code": null, "e": 1240, "s": 1174, "text": "You can try to run the following code to speed the hover effect −" }, { "code": null, "e": 1250, "s": 1240, "text": "Live Demo" }, { "code": null, "e": 1874, "s": 1250, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .btn {\n background-color: yellow;\n color: black;\n text-align: center;\n font-size: 15px;\n padding: 20px;\n border-radius: 15px;\n border: 3px dashed blue;\n transition-duration: 2s;\n }\n .btn:hover {\n background-color: orange;\n color: black;\n border: 3px solid blue;\n }\n </style>\n </head>\n <body>\n <h2>Result</h2>\n <p>Click below for result:</p>\n <button class = \"btn\">Result</button>\n </body>\n</html>" } ]
Print all internal nodes of a Binary tree - GeeksforGeeks
28 Jun, 2021 Given a Binary tree, the task is to print all the internal nodes in a tree. An internal node is a node which carries at least one child or in other words, an internal node is not a leaf node. Here we intend to print all such internal nodes in level order. Consider the following Binary Tree: Input: Output: 15 10 20 The way to solve this involves a BFS of the tree. The algorithm is as follows: Do a level order traversal by pushing nodes in the queue one by one. Pop the elements from the queue one by one and keep a track of following cases: The node has a left child only.The node has a right child only.The node has both left and right child.The node has no children at all. The node has a left child only.The node has a right child only.The node has both left and right child.The node has no children at all. The node has a left child only. The node has a right child only. The node has both left and right child. The node has no children at all. Except for case 4, print the data in the node for all the other 3 cases. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print all internal// nodes in tree#include <bits/stdc++.h>using namespace std; // A node in the Binary treestruct Node { int data; Node *left, *right; Node(int data) { left = right = NULL; this->data = data; }}; // Function to print all internal nodes// in level order from left to rightvoid printInternalNodes(Node* root){ // Using a queue for a level order traversal queue<Node*> q; q.push(root); while (!q.empty()) { // Check and pop the element in // the front of the queue Node* curr = q.front(); q.pop(); // The variable flag keeps track of // whether a node is an internal node bool isInternal = 0; // The node has a left child if (curr->left) { isInternal = 1; q.push(curr->left); } // The node has a right child if (curr->right) { isInternal = 1; q.push(curr->right); } // In case the node has either a left // or right child or both print the data if (isInternal) cout << curr->data << " "; }} // Driver program to build a sample treeint main(){ Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->right->left = new Node(5); root->right->right = new Node(6); root->right->right->right = new Node(10); root->right->right->left = new Node(7); root->right->left->left = new Node(8); root->right->left->right = new Node(9); // A call to the function printInternalNodes(root); return 0;} // Java program to print all internal// nodes in treeimport java.util.*;class GfG{ // A node in the Binary treestatic class Node{ int data; Node left, right; Node(int data) { left = right = null; this.data = data; }} // Function to print all internal nodes// in level order from left to rightstatic void printInternalNodes(Node root){ // Using a queue for a level order traversal Queue<Node> q = new LinkedList<Node>(); q.add(root); while (!q.isEmpty()) { // Check and pop the element in // the front of the queue Node curr = q.peek(); q.remove(); // The variable flag keeps track of // whether a node is an internal node boolean isInternal = false; // The node has a left child if (curr.left != null) { isInternal = true; q.add(curr.left); } // The node has a right child if (curr.right != null) { isInternal = true; q.add(curr.right); } // In case the node has either a left // or right child or both print the data if (isInternal == true) System.out.print(curr.data + " "); }} // Driver codepublic static void main(String[] args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.right.right = new Node(10); root.right.right.left = new Node(7); root.right.left.left = new Node(8); root.right.left.right = new Node(9); // A call to the function printInternalNodes(root);}} // This code is contributed by// Prerna Saini. # Python3 program to print all internal# nodes in tree # A node in the Binary treeclass new_Node: # Constructor to create a new_Node def __init__(self, data): self.data = data self.left = None self.right = None # Function to print all internal nodes# in level order from left to rightdef printInternalNodes(root): # Using a queue for a level order traversal q = [] q.append(root) while (len(q)): # Check and pop the element in # the front of the queue curr = q[0] q.pop(0) # The variable flag keeps track of # whether a node is an internal node isInternal = 0 # The node has a left child if (curr.left): isInternal = 1 q.append(curr.left) # The node has a right child if (curr.right): isInternal = 1 q.append(curr.right) # In case the node has either a left # or right child or both print the data if (isInternal): print(curr.data, end = " ") # Driver Coderoot = new_Node(1)root.left = new_Node(2)root.right = new_Node(3)root.left.left = new_Node(4)root.right.left = new_Node(5)root.right.right = new_Node(6)root.right.right.right = new_Node(10)root.right.right.left = new_Node(7)root.right.left.left = new_Node(8)root.right.left.right = new_Node(9) # A call to the functionprintInternalNodes(root) # This code is contributed by SHUBHAMSINGH10 // C# program to print all internal// nodes in treeusing System;using System.Collections.Generic; class GFG{ // A node in the Binary treepublic class Node{ public int data; public Node left, right; public Node(int data) { left = right = null; this.data = data; }} // Function to print all internal nodes// in level order from left to rightstatic void printInternalNodes(Node root){ // Using a queue for a level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { // Check and pop the element in // the front of the queue Node curr = q.Peek(); q.Dequeue(); // The variable flag keeps track of // whether a node is an internal node Boolean isInternal = false; // The node has a left child if (curr.left != null) { isInternal = true; q.Enqueue(curr.left); } // The node has a right child if (curr.right != null) { isInternal = true; q.Enqueue(curr.right); } // In case the node has either a left // or right child or both print the data if (isInternal == true) Console.Write(curr.data + " "); }} // Driver codepublic static void Main(String[] args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.right.right = new Node(10); root.right.right.left = new Node(7); root.right.left.left = new Node(8); root.right.left.right = new Node(9); // A call to the function printInternalNodes(root);}} // This code contributed by Rajput-Ji <script> // JavaScript program to print all internal nodes in tree // A node in the Binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to print all internal nodes // in level order from left to right function printInternalNodes(root) { // Using a queue for a level order traversal let q = []; q.push(root); while (q.length > 0) { // Check and pop the element in // the front of the queue let curr = q[0]; q.shift(); // The variable flag keeps track of // whether a node is an internal node let isInternal = false; // The node has a left child if (curr.left != null) { isInternal = true; q.push(curr.left); } // The node has a right child if (curr.right != null) { isInternal = true; q.push(curr.right); } // In case the node has either a left // or right child or both print the data if (isInternal == true) document.write(curr.data + " "); } } let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.right.right = new Node(10); root.right.right.left = new Node(7); root.right.left.left = new Node(8); root.right.left.right = new Node(9); // A call to the function printInternalNodes(root); </script> 1 2 3 5 6 prerna saini Rajput-Ji SHUBHAMSINGH10 nidhi_biet mukesh07 tree-level-order Data Structures Tree Data Structures Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class TCS NQT Coding Sheet Hash Functions and list/types of Hash functions Building an undirected graph and finding shortest path using Dictionaries in Python Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24663, "s": 24635, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24956, "s": 24663, "text": "Given a Binary tree, the task is to print all the internal nodes in a tree. An internal node is a node which carries at least one child or in other words, an internal node is not a leaf node. Here we intend to print all such internal nodes in level order. Consider the following Binary Tree: " }, { "code": null, "e": 24965, "s": 24956, "text": "Input: " }, { "code": null, "e": 24982, "s": 24965, "text": "Output: 15 10 20" }, { "code": null, "e": 25065, "s": 24984, "text": "The way to solve this involves a BFS of the tree. The algorithm is as follows: " }, { "code": null, "e": 25134, "s": 25065, "text": "Do a level order traversal by pushing nodes in the queue one by one." }, { "code": null, "e": 25349, "s": 25134, "text": "Pop the elements from the queue one by one and keep a track of following cases: The node has a left child only.The node has a right child only.The node has both left and right child.The node has no children at all." }, { "code": null, "e": 25484, "s": 25349, "text": "The node has a left child only.The node has a right child only.The node has both left and right child.The node has no children at all." }, { "code": null, "e": 25516, "s": 25484, "text": "The node has a left child only." }, { "code": null, "e": 25549, "s": 25516, "text": "The node has a right child only." }, { "code": null, "e": 25589, "s": 25549, "text": "The node has both left and right child." }, { "code": null, "e": 25622, "s": 25589, "text": "The node has no children at all." }, { "code": null, "e": 25695, "s": 25622, "text": "Except for case 4, print the data in the node for all the other 3 cases." }, { "code": null, "e": 25747, "s": 25695, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25751, "s": 25747, "text": "C++" }, { "code": null, "e": 25756, "s": 25751, "text": "Java" }, { "code": null, "e": 25764, "s": 25756, "text": "Python3" }, { "code": null, "e": 25767, "s": 25764, "text": "C#" }, { "code": null, "e": 25778, "s": 25767, "text": "Javascript" }, { "code": "// C++ program to print all internal// nodes in tree#include <bits/stdc++.h>using namespace std; // A node in the Binary treestruct Node { int data; Node *left, *right; Node(int data) { left = right = NULL; this->data = data; }}; // Function to print all internal nodes// in level order from left to rightvoid printInternalNodes(Node* root){ // Using a queue for a level order traversal queue<Node*> q; q.push(root); while (!q.empty()) { // Check and pop the element in // the front of the queue Node* curr = q.front(); q.pop(); // The variable flag keeps track of // whether a node is an internal node bool isInternal = 0; // The node has a left child if (curr->left) { isInternal = 1; q.push(curr->left); } // The node has a right child if (curr->right) { isInternal = 1; q.push(curr->right); } // In case the node has either a left // or right child or both print the data if (isInternal) cout << curr->data << \" \"; }} // Driver program to build a sample treeint main(){ Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->right->left = new Node(5); root->right->right = new Node(6); root->right->right->right = new Node(10); root->right->right->left = new Node(7); root->right->left->left = new Node(8); root->right->left->right = new Node(9); // A call to the function printInternalNodes(root); return 0;}", "e": 27409, "s": 25778, "text": null }, { "code": "// Java program to print all internal// nodes in treeimport java.util.*;class GfG{ // A node in the Binary treestatic class Node{ int data; Node left, right; Node(int data) { left = right = null; this.data = data; }} // Function to print all internal nodes// in level order from left to rightstatic void printInternalNodes(Node root){ // Using a queue for a level order traversal Queue<Node> q = new LinkedList<Node>(); q.add(root); while (!q.isEmpty()) { // Check and pop the element in // the front of the queue Node curr = q.peek(); q.remove(); // The variable flag keeps track of // whether a node is an internal node boolean isInternal = false; // The node has a left child if (curr.left != null) { isInternal = true; q.add(curr.left); } // The node has a right child if (curr.right != null) { isInternal = true; q.add(curr.right); } // In case the node has either a left // or right child or both print the data if (isInternal == true) System.out.print(curr.data + \" \"); }} // Driver codepublic static void main(String[] args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.right.right = new Node(10); root.right.right.left = new Node(7); root.right.left.left = new Node(8); root.right.left.right = new Node(9); // A call to the function printInternalNodes(root);}} // This code is contributed by// Prerna Saini.", "e": 29132, "s": 27409, "text": null }, { "code": "# Python3 program to print all internal# nodes in tree # A node in the Binary treeclass new_Node: # Constructor to create a new_Node def __init__(self, data): self.data = data self.left = None self.right = None # Function to print all internal nodes# in level order from left to rightdef printInternalNodes(root): # Using a queue for a level order traversal q = [] q.append(root) while (len(q)): # Check and pop the element in # the front of the queue curr = q[0] q.pop(0) # The variable flag keeps track of # whether a node is an internal node isInternal = 0 # The node has a left child if (curr.left): isInternal = 1 q.append(curr.left) # The node has a right child if (curr.right): isInternal = 1 q.append(curr.right) # In case the node has either a left # or right child or both print the data if (isInternal): print(curr.data, end = \" \") # Driver Coderoot = new_Node(1)root.left = new_Node(2)root.right = new_Node(3)root.left.left = new_Node(4)root.right.left = new_Node(5)root.right.right = new_Node(6)root.right.right.right = new_Node(10)root.right.right.left = new_Node(7)root.right.left.left = new_Node(8)root.right.left.right = new_Node(9) # A call to the functionprintInternalNodes(root) # This code is contributed by SHUBHAMSINGH10", "e": 30631, "s": 29132, "text": null }, { "code": "// C# program to print all internal// nodes in treeusing System;using System.Collections.Generic; class GFG{ // A node in the Binary treepublic class Node{ public int data; public Node left, right; public Node(int data) { left = right = null; this.data = data; }} // Function to print all internal nodes// in level order from left to rightstatic void printInternalNodes(Node root){ // Using a queue for a level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { // Check and pop the element in // the front of the queue Node curr = q.Peek(); q.Dequeue(); // The variable flag keeps track of // whether a node is an internal node Boolean isInternal = false; // The node has a left child if (curr.left != null) { isInternal = true; q.Enqueue(curr.left); } // The node has a right child if (curr.right != null) { isInternal = true; q.Enqueue(curr.right); } // In case the node has either a left // or right child or both print the data if (isInternal == true) Console.Write(curr.data + \" \"); }} // Driver codepublic static void Main(String[] args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.right.right = new Node(10); root.right.right.left = new Node(7); root.right.left.left = new Node(8); root.right.left.right = new Node(9); // A call to the function printInternalNodes(root);}} // This code contributed by Rajput-Ji", "e": 32397, "s": 30631, "text": null }, { "code": "<script> // JavaScript program to print all internal nodes in tree // A node in the Binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to print all internal nodes // in level order from left to right function printInternalNodes(root) { // Using a queue for a level order traversal let q = []; q.push(root); while (q.length > 0) { // Check and pop the element in // the front of the queue let curr = q[0]; q.shift(); // The variable flag keeps track of // whether a node is an internal node let isInternal = false; // The node has a left child if (curr.left != null) { isInternal = true; q.push(curr.left); } // The node has a right child if (curr.right != null) { isInternal = true; q.push(curr.right); } // In case the node has either a left // or right child or both print the data if (isInternal == true) document.write(curr.data + \" \"); } } let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.right.right = new Node(10); root.right.right.left = new Node(7); root.right.left.left = new Node(8); root.right.left.right = new Node(9); // A call to the function printInternalNodes(root); </script>", "e": 34131, "s": 32397, "text": null }, { "code": null, "e": 34141, "s": 34131, "text": "1 2 3 5 6" }, { "code": null, "e": 34156, "s": 34143, "text": "prerna saini" }, { "code": null, "e": 34166, "s": 34156, "text": "Rajput-Ji" }, { "code": null, "e": 34181, "s": 34166, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 34192, "s": 34181, "text": "nidhi_biet" }, { "code": null, "e": 34201, "s": 34192, "text": "mukesh07" }, { "code": null, "e": 34218, "s": 34201, "text": "tree-level-order" }, { "code": null, "e": 34234, "s": 34218, "text": "Data Structures" }, { "code": null, "e": 34239, "s": 34234, "text": "Tree" }, { "code": null, "e": 34255, "s": 34239, "text": "Data Structures" }, { "code": null, "e": 34260, "s": 34255, "text": "Tree" }, { "code": null, "e": 34358, "s": 34260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34367, "s": 34358, "text": "Comments" }, { "code": null, "e": 34380, "s": 34367, "text": "Old Comments" }, { "code": null, "e": 34416, "s": 34380, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 34475, "s": 34416, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 34496, "s": 34475, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 34544, "s": 34496, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 34628, "s": 34544, "text": "Building an undirected graph and finding shortest path using Dictionaries in Python" }, { "code": null, "e": 34678, "s": 34628, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 34713, "s": 34678, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 34742, "s": 34713, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 34776, "s": 34742, "text": "Level Order Binary Tree Traversal" } ]
Data Backup and Restoration in Cassandra - GeeksforGeeks
23 Dec, 2019 In this article, we will discuss how we can Backup and Restore our data and also discuss how many ways we can restore our data in Cassandra. We can restore our data by using a snapshot and by using sstableloader utility and by using a nodetool refresh. Let’s discuss one by one. First, we are going to create keyspace for backup the data. Let’s discuss this with a sample exercise. Creating a keyspace: create keyspace backup_copy with replication = { 'class' : 'SimpleStrategy', 'replication_factor': 2 }; Now, here we are using backup_copy keyspace. use backup_copy ; Now, we are going to create the table for backup purposes. In below given CQL query facebook_user is a table name in which login_time, user_name, and post are the fields.Let’s have a look. create table facebook_user ( login_time timeuuid primary key, user_name text, post set<text> ); Let’s see the table schema. describe table facebook_user; Output: Now, we are going to insert some data for backup and restore purposes. let’s have a look. Insert into facebook_user(login_time, user_name, post) values(now(), 'Ashish', {'join webinar at 10:00 am'}); Insert into facebook_user(login_time, user_name, post) values(now(), 'Rana', {'join Cassandra meetup at 10:00 am'}); Now, let’s Verify the records have been persisted successfully with the select command. let’s have a look. select * from facebook_user; Output: To take a snapshot, we need to use the nodetool utility: nodetool -h localhost -p 7199 snapshot facebook_user Here, 7199 is a port no. Requested creating a snapshot for facebook_user. Snapshot directory: 1205514051242 The output shows that running nodetool snapshot over a local node has created a snapshot 1205514051242 under the $CASSANDRA_DATA_DIR/backup_copy/facebook_user folder. Here $CASSANDRA_DATA_DIR is the value defined in Cassandra.yaml file for data_file_directories properties To restore data first we need to delete some data that we can restore. let’s have a look. truncate facebook_user; Restore data by using the sstableloader utility:To begin, we need to copy all .db files in the Snapshot directory into a folder which should be in sync with the database schema, meaning keyspace/table name. Here in our case, it should be the user’s folder facebook_user under backup_copy(/home/Ashish/backup_copy/facebook_user). Now, let’s execute the sstableloader. $CASSANDRA_HOME/bin/sstableloader -d localhost /home/Ashish/backup_copy/facebook_user Now, here this is how it will execute. let’s have a look. Established connection to initial hosts Opening sstables and calculating sections to stream Streaming relevant part of /home/Ashish/backup_copy/facebook_user/facebook_user-jb-1-Data.db to [/127.0.0.1, /127.0.0.2, /127.0.0.3] progress: [/127.0.0.2 1/1 (100%)] [/127.0.0.3 1/1 (100%)] [total: 100% - 0MB/s (avg: 0MB/s)] Once it completes, we can verify whether the data has been restored by running the select command.Once the above CQL query completes, we can verify whether the data has been restored by using the following CQL query given below. select * from backup_copy.facebook_user; Output: Using nodetool refresh:This is one of the ways that we can restore our data by using nodetool refresh utility and it is different from sstableloader method. In this, we need to manually copy .db files in Cassandra data directory. To run the nodetool refresh command use the following CQL query given below. let’s have a look. $CASSANDRA_HOME/bin/nodetool refresh backup_copy facebook_user Using clearsnapshot: $CASSANDRA_HOME/bin/nodetool -h localhost -p 7199 clearsnapshot Apache BigData DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database Introduction of B-Tree Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of ER Model CTE in SQL SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between Primary Key and Foreign Key Third Normal Form (3NF)
[ { "code": null, "e": 23689, "s": 23661, "text": "\n23 Dec, 2019" }, { "code": null, "e": 23942, "s": 23689, "text": "In this article, we will discuss how we can Backup and Restore our data and also discuss how many ways we can restore our data in Cassandra. We can restore our data by using a snapshot and by using sstableloader utility and by using a nodetool refresh." }, { "code": null, "e": 23968, "s": 23942, "text": "Let’s discuss one by one." }, { "code": null, "e": 24071, "s": 23968, "text": "First, we are going to create keyspace for backup the data. Let’s discuss this with a sample exercise." }, { "code": null, "e": 24092, "s": 24071, "text": "Creating a keyspace:" }, { "code": null, "e": 24220, "s": 24092, "text": "create keyspace backup_copy \nwith replication = { 'class' : 'SimpleStrategy', \n 'replication_factor': 2 }; " }, { "code": null, "e": 24265, "s": 24220, "text": "Now, here we are using backup_copy keyspace." }, { "code": null, "e": 24285, "s": 24265, "text": "use backup_copy ; " }, { "code": null, "e": 24474, "s": 24285, "text": "Now, we are going to create the table for backup purposes. In below given CQL query facebook_user is a table name in which login_time, user_name, and post are the fields.Let’s have a look." }, { "code": null, "e": 24581, "s": 24474, "text": "create table facebook_user\n (\n login_time timeuuid primary key, \n user_name text, \n post set<text>\n ); " }, { "code": null, "e": 24609, "s": 24581, "text": "Let’s see the table schema." }, { "code": null, "e": 24640, "s": 24609, "text": "describe table facebook_user; " }, { "code": null, "e": 24648, "s": 24640, "text": "Output:" }, { "code": null, "e": 24738, "s": 24648, "text": "Now, we are going to insert some data for backup and restore purposes. let’s have a look." }, { "code": null, "e": 24969, "s": 24738, "text": "Insert into facebook_user(login_time, user_name, post) \nvalues(now(), 'Ashish', {'join webinar at 10:00 am'});\n\nInsert into facebook_user(login_time, user_name, post) \nvalues(now(), 'Rana', {'join Cassandra meetup at 10:00 am'}); " }, { "code": null, "e": 25076, "s": 24969, "text": "Now, let’s Verify the records have been persisted successfully with the select command. let’s have a look." }, { "code": null, "e": 25107, "s": 25076, "text": "select * \nfrom facebook_user; " }, { "code": null, "e": 25115, "s": 25107, "text": "Output:" }, { "code": null, "e": 25172, "s": 25115, "text": "To take a snapshot, we need to use the nodetool utility:" }, { "code": null, "e": 25226, "s": 25172, "text": "nodetool -h localhost -p 7199 snapshot facebook_user " }, { "code": null, "e": 25251, "s": 25226, "text": "Here, 7199 is a port no." }, { "code": null, "e": 25300, "s": 25251, "text": "Requested creating a snapshot for facebook_user." }, { "code": null, "e": 25334, "s": 25300, "text": "Snapshot directory: 1205514051242" }, { "code": null, "e": 25607, "s": 25334, "text": "The output shows that running nodetool snapshot over a local node has created a snapshot 1205514051242 under the $CASSANDRA_DATA_DIR/backup_copy/facebook_user folder. Here $CASSANDRA_DATA_DIR is the value defined in Cassandra.yaml file for data_file_directories properties" }, { "code": null, "e": 25697, "s": 25607, "text": "To restore data first we need to delete some data that we can restore. let’s have a look." }, { "code": null, "e": 25722, "s": 25697, "text": "truncate facebook_user; " }, { "code": null, "e": 26051, "s": 25722, "text": "Restore data by using the sstableloader utility:To begin, we need to copy all .db files in the Snapshot directory into a folder which should be in sync with the database schema, meaning keyspace/table name. Here in our case, it should be the user’s folder facebook_user under backup_copy(/home/Ashish/backup_copy/facebook_user)." }, { "code": null, "e": 26089, "s": 26051, "text": "Now, let’s execute the sstableloader." }, { "code": null, "e": 26176, "s": 26089, "text": "$CASSANDRA_HOME/bin/sstableloader -d localhost /home/Ashish/backup_copy/facebook_user " }, { "code": null, "e": 26234, "s": 26176, "text": "Now, here this is how it will execute. let’s have a look." }, { "code": null, "e": 26553, "s": 26234, "text": "Established connection to initial hosts\nOpening sstables and calculating sections to stream\nStreaming relevant part of /home/Ashish/backup_copy/facebook_user/facebook_user-jb-1-Data.db to\n[/127.0.0.1, /127.0.0.2, /127.0.0.3]\nprogress: [/127.0.0.2 1/1 (100%)] [/127.0.0.3 1/1 (100%)] [total: 100% - 0MB/s (avg: 0MB/s)] " }, { "code": null, "e": 26782, "s": 26553, "text": "Once it completes, we can verify whether the data has been restored by running the select command.Once the above CQL query completes, we can verify whether the data has been restored by using the following CQL query given below." }, { "code": null, "e": 26825, "s": 26782, "text": "select * \nfrom backup_copy.facebook_user; " }, { "code": null, "e": 26833, "s": 26825, "text": "Output:" }, { "code": null, "e": 27063, "s": 26833, "text": "Using nodetool refresh:This is one of the ways that we can restore our data by using nodetool refresh utility and it is different from sstableloader method. In this, we need to manually copy .db files in Cassandra data directory." }, { "code": null, "e": 27159, "s": 27063, "text": "To run the nodetool refresh command use the following CQL query given below. let’s have a look." }, { "code": null, "e": 27223, "s": 27159, "text": "$CASSANDRA_HOME/bin/nodetool refresh backup_copy facebook_user " }, { "code": null, "e": 27244, "s": 27223, "text": "Using clearsnapshot:" }, { "code": null, "e": 27309, "s": 27244, "text": "$CASSANDRA_HOME/bin/nodetool -h localhost -p 7199 clearsnapshot " }, { "code": null, "e": 27316, "s": 27309, "text": "Apache" }, { "code": null, "e": 27324, "s": 27316, "text": "BigData" }, { "code": null, "e": 27329, "s": 27324, "text": "DBMS" }, { "code": null, "e": 27334, "s": 27329, "text": "DBMS" }, { "code": null, "e": 27432, "s": 27334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27441, "s": 27432, "text": "Comments" }, { "code": null, "e": 27454, "s": 27441, "text": "Old Comments" }, { "code": null, "e": 27485, "s": 27454, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 27508, "s": 27485, "text": "Introduction of B-Tree" }, { "code": null, "e": 27561, "s": 27508, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27619, "s": 27561, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 27644, "s": 27619, "text": "Introduction of ER Model" }, { "code": null, "e": 27655, "s": 27644, "text": "CTE in SQL" }, { "code": null, "e": 27667, "s": 27655, "text": "SQL | Views" }, { "code": null, "e": 27712, "s": 27667, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27759, "s": 27712, "text": "Difference between Primary Key and Foreign Key" } ]
Image based Steganography using Python?
Steganography is a technique of hiding information behind the scene. It’s is not like cryptography which focuses on encrypting data(through different algorithms like SHA1, MD5 etc), steganography focuses more on hiding the data (data can be a file, image, message or video) within another file, image, message or video to avoid any attraction. So in this we’ll try to create a simple python program that hides the information behind the image without noticiable changes in the looks of the image. There are two main parts of the program – first is a decoding function that can extract secret information from an image file and second is a encoding function that will encode secret messages into images. We use the Python Pillow library for this purpose (you can openCv or others too ☺). You can install it using pip, just run pip install pillow in your command prompt: $pip install pillow Pixels are the smallest individual element of an image. So, each pixel represents a part of the original image. It means, higher the pixel-higher or much accurate representations of the actual picture. In a black and white image (not greyscale), black pixel has a value 1 and a white pixel as a value of 0. Whereas in colored images, they have three main color components(RGB- Red, Green, Blue), with pixel values of 0-255 for each pixel. So a pixel of (255, 255, 255) will represent a white and (0,0,0) means black. As the maximum number an 8-bit binary number can represent 255, is the maximum number we can go. As the base of binary-number is 2, we can convert the binary number into decimal very easily. Let, our binary number is 01010101, then its equivalent decimal number(base 10) will be: 26 +24 + 22 + 20 = 64 + 16 + 4 + 1 = 85 You can test above – binary to decimal conversion in your python terminal too. >>> print(0b01010101) 85 >>> type(0b01010101) <class 'int'> >>> 0b01010101 85 >>> 0b01010110 86 How we gona achieve it: Step 1: Import the required library/package. Step 2: Open the file or Image Step 3: Encode some text into the source Image & then save it. Step 4: Check both the images (with and without hidden data file) and see if there is any visible changes. Step 5: Decode the image- to extract data from the image Implementation of above steps: >>> #Import the required library >>> from PIL import Image >>> import stepic >>> I have used the stepic library for encoding and decoding purpose. You can install the stepic library using pip: >>> #Open Image or file in which you want to hide your data >>> im = Image.open('TajMahal.png') >>> >>> #Encode some text into your Image file and save it in another file >>> im1 = stepic.encode(im, b'Hello Python') >>> im1.save('TajMahal.png', 'PNG') >>> >>> #Now is the time to check both images and see if there is any visible changes >>> im1 = Image.open('TajMahal.png') >>> im1.show() Image with hidden text: Actual image: >>> im.show() >>>' >>> >>> #Decode the image so as to extract the hidden data from the image >>> im2 = Image.open('TajMahal.png') >>> stegoImage = stepic.decode(im2) >>> stegoImage 'Hello Python' So we see how easy is to hide the text behind the image. You can use other input items like video or other formats like jpeg and you can use other libraries to give you the same results, Happy Steganography with Python ☺.
[ { "code": null, "e": 1406, "s": 1062, "text": "Steganography is a technique of hiding information behind the scene. It’s is not like cryptography which focuses on encrypting data(through different algorithms like SHA1, MD5 etc), steganography focuses more on hiding the data (data can be a file, image, message or video) within another file, image, message or video to avoid any attraction." }, { "code": null, "e": 1765, "s": 1406, "text": "So in this we’ll try to create a simple python program that hides the information behind the image without noticiable changes in the looks of the image. There are two main parts of the program – first is a decoding function that can extract secret information from an image file and second is a encoding function that will encode secret messages into images." }, { "code": null, "e": 1931, "s": 1765, "text": "We use the Python Pillow library for this purpose (you can openCv or others too ☺). You can install it using pip, just run pip install pillow in your command prompt:" }, { "code": null, "e": 1951, "s": 1931, "text": "$pip install pillow" }, { "code": null, "e": 2153, "s": 1951, "text": "Pixels are the smallest individual element of an image. So, each pixel represents a part of the original image. It means, higher the pixel-higher or much accurate representations of the actual picture." }, { "code": null, "e": 2565, "s": 2153, "text": "In a black and white image (not greyscale), black pixel has a value 1 and a white pixel as a value of 0. Whereas in colored images, they have three main color components(RGB- Red, Green, Blue), with pixel values of 0-255 for each pixel. So a pixel of (255, 255, 255) will represent a white and (0,0,0) means black. As the maximum number an 8-bit binary number can represent 255, is the maximum number we can go." }, { "code": null, "e": 2748, "s": 2565, "text": "As the base of binary-number is 2, we can convert the binary number into decimal very easily. Let, our binary number is 01010101, then its equivalent decimal number(base 10) will be:" }, { "code": null, "e": 2788, "s": 2748, "text": "26 +24 + 22 + 20 = 64 + 16 + 4 + 1 = 85" }, { "code": null, "e": 2867, "s": 2788, "text": "You can test above – binary to decimal conversion in your python terminal too." }, { "code": null, "e": 2963, "s": 2867, "text": ">>> print(0b01010101)\n85\n>>> type(0b01010101)\n<class 'int'>\n>>> 0b01010101\n85\n>>> 0b01010110\n86" }, { "code": null, "e": 2987, "s": 2963, "text": "How we gona achieve it:" }, { "code": null, "e": 3290, "s": 2987, "text": "Step 1: Import the required library/package.\nStep 2: Open the file or Image\nStep 3: Encode some text into the source Image & then save it.\nStep 4: Check both the images (with and without hidden data file) and see if there is any visible changes.\nStep 5: Decode the image- to extract data from the image" }, { "code": null, "e": 3321, "s": 3290, "text": "Implementation of above steps:" }, { "code": null, "e": 3402, "s": 3321, "text": ">>> #Import the required library\n>>> from PIL import Image\n>>> import stepic\n>>>" }, { "code": null, "e": 3514, "s": 3402, "text": "I have used the stepic library for encoding and decoding purpose. You can install the stepic library using pip:" }, { "code": null, "e": 3904, "s": 3514, "text": ">>> #Open Image or file in which you want to hide your data\n>>> im = Image.open('TajMahal.png')\n>>>\n>>> #Encode some text into your Image file and save it in another file\n>>> im1 = stepic.encode(im, b'Hello Python')\n>>> im1.save('TajMahal.png', 'PNG')\n>>>\n>>> #Now is the time to check both images and see if there is any visible changes\n>>> im1 = Image.open('TajMahal.png')\n>>> im1.show()" }, { "code": null, "e": 3928, "s": 3904, "text": "Image with hidden text:" }, { "code": null, "e": 3961, "s": 3928, "text": "Actual image:\n>>> im.show()\n>>>'" }, { "code": null, "e": 4138, "s": 3961, "text": ">>>\n>>> #Decode the image so as to extract the hidden data from the image\n>>> im2 = Image.open('TajMahal.png')\n>>> stegoImage = stepic.decode(im2)\n>>> stegoImage\n'Hello Python'" }, { "code": null, "e": 4360, "s": 4138, "text": "So we see how easy is to hide the text behind the image. You can use other input items like video or other formats like jpeg and you can use other libraries to give you the same results, Happy Steganography with Python ☺." } ]
Flutter - Deployment
This chapter explains how to deploy Flutter application in both Android and iOS platforms. Change the application name using android:label entry in android manifest file. Android app manifest file, AndroidManifest.xml is located in <app dir>/android/app/src/main. It contains entire details about an android application. We can set the application name using android:label entry. Change the application name using android:label entry in android manifest file. Android app manifest file, AndroidManifest.xml is located in <app dir>/android/app/src/main. It contains entire details about an android application. We can set the application name using android:label entry. Change launcher icon using android:icon entry in manifest file. Change launcher icon using android:icon entry in manifest file. Sign the app using standard option as necessary. Sign the app using standard option as necessary. Enable Proguard and Obfuscation using standard option, if necessary. Enable Proguard and Obfuscation using standard option, if necessary. Create a release APK file by running below command − Create a release APK file by running below command − cd /path/to/my/application flutter build apk You can see an output as shown below − You can see an output as shown below − Initializing gradle... 8.6s Resolving dependencies... 19.9s Calling mockable JAR artifact transform to create file: /Users/.gradle/caches/transforms-1/files-1.1/android.jar/ c30932f130afbf3fd90c131ef9069a0b/android.jar with input /Users/Library/Android/sdk/platforms/android-28/android.jar Running Gradle task 'assembleRelease'... Running Gradle task 'assembleRelease'... Done 85.7s Built build/app/outputs/apk/release/app-release.apk (4.8MB). Install the APK on a device using the following command − Install the APK on a device using the following command − flutter install Publish the application into Google Playstore by creating an appbundle and push it into playstore using standard methods. Publish the application into Google Playstore by creating an appbundle and push it into playstore using standard methods. flutter build appbundle Register the iOS application in App Store Connect using standard method. Save the =Bundle ID used while registering the application. Register the iOS application in App Store Connect using standard method. Save the =Bundle ID used while registering the application. Update Display name in the XCode project setting to set the application name. Update Display name in the XCode project setting to set the application name. Update Bundle Identifier in the XCode project setting to set the bundle id, which we used in step 1. Update Bundle Identifier in the XCode project setting to set the bundle id, which we used in step 1. Code sign as necessary using standard method. Code sign as necessary using standard method. Add a new app icon as necessary using standard method. Add a new app icon as necessary using standard method. Generate IPA file using the following command − Generate IPA file using the following command − flutter build ios Now, you can see the following output − Now, you can see the following output − Building com.example.MyApp for device (ios-release)... Automatically signing iOS for device deployment using specified development team in Xcode project: Running Xcode build... 23.5s ...................... Test the application by pushing the application, IPA file into TestFlight using standard method. Test the application by pushing the application, IPA file into TestFlight using standard method. Finally, push the application into App Store using standard method. Finally, push the application into App Store using standard method. 34 Lectures 4 hours Sriyank Siddhartha 117 Lectures 10 hours Frahaan Hussain 27 Lectures 1 hours Skillbakerystudios 17 Lectures 51 mins Harsh Kumar Khatri 17 Lectures 1.5 hours Pramila Rawat 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2309, "s": 2218, "text": "This chapter explains how to deploy Flutter application in both Android and iOS platforms." }, { "code": null, "e": 2598, "s": 2309, "text": "Change the application name using android:label entry in android manifest file. Android app manifest file, AndroidManifest.xml is located in <app dir>/android/app/src/main. It contains entire details about an android application. We can set the application name using android:label entry." }, { "code": null, "e": 2887, "s": 2598, "text": "Change the application name using android:label entry in android manifest file. Android app manifest file, AndroidManifest.xml is located in <app dir>/android/app/src/main. It contains entire details about an android application. We can set the application name using android:label entry." }, { "code": null, "e": 2951, "s": 2887, "text": "Change launcher icon using android:icon entry in manifest file." }, { "code": null, "e": 3015, "s": 2951, "text": "Change launcher icon using android:icon entry in manifest file." }, { "code": null, "e": 3064, "s": 3015, "text": "Sign the app using standard option as necessary." }, { "code": null, "e": 3113, "s": 3064, "text": "Sign the app using standard option as necessary." }, { "code": null, "e": 3182, "s": 3113, "text": "Enable Proguard and Obfuscation using standard option, if necessary." }, { "code": null, "e": 3251, "s": 3182, "text": "Enable Proguard and Obfuscation using standard option, if necessary." }, { "code": null, "e": 3304, "s": 3251, "text": "Create a release APK file by running below command −" }, { "code": null, "e": 3357, "s": 3304, "text": "Create a release APK file by running below command −" }, { "code": null, "e": 3404, "s": 3357, "text": "cd /path/to/my/application \nflutter build apk\n" }, { "code": null, "e": 3443, "s": 3404, "text": "You can see an output as shown below −" }, { "code": null, "e": 3482, "s": 3443, "text": "You can see an output as shown below −" }, { "code": null, "e": 4078, "s": 3482, "text": "Initializing gradle... 8.6s \nResolving dependencies... 19.9s \nCalling mockable JAR artifact transform to create file: \n/Users/.gradle/caches/transforms-1/files-1.1/android.jar/ \nc30932f130afbf3fd90c131ef9069a0b/android.jar with input \n/Users/Library/Android/sdk/platforms/android-28/android.jar \nRunning Gradle task 'assembleRelease'... \nRunning Gradle task 'assembleRelease'... \nDone 85.7s \nBuilt build/app/outputs/apk/release/app-release.apk (4.8MB).\n" }, { "code": null, "e": 4136, "s": 4078, "text": "Install the APK on a device using the following command −" }, { "code": null, "e": 4194, "s": 4136, "text": "Install the APK on a device using the following command −" }, { "code": null, "e": 4211, "s": 4194, "text": "flutter install\n" }, { "code": null, "e": 4333, "s": 4211, "text": "Publish the application into Google Playstore by creating an appbundle and push it into playstore using standard methods." }, { "code": null, "e": 4455, "s": 4333, "text": "Publish the application into Google Playstore by creating an appbundle and push it into playstore using standard methods." }, { "code": null, "e": 4480, "s": 4455, "text": "flutter build appbundle\n" }, { "code": null, "e": 4613, "s": 4480, "text": "Register the iOS application in App Store Connect using standard method. Save the =Bundle ID used while registering the application." }, { "code": null, "e": 4746, "s": 4613, "text": "Register the iOS application in App Store Connect using standard method. Save the =Bundle ID used while registering the application." }, { "code": null, "e": 4824, "s": 4746, "text": "Update Display name in the XCode project setting to set the application name." }, { "code": null, "e": 4902, "s": 4824, "text": "Update Display name in the XCode project setting to set the application name." }, { "code": null, "e": 5003, "s": 4902, "text": "Update Bundle Identifier in the XCode project setting to set the bundle id, which we used in step 1." }, { "code": null, "e": 5104, "s": 5003, "text": "Update Bundle Identifier in the XCode project setting to set the bundle id, which we used in step 1." }, { "code": null, "e": 5150, "s": 5104, "text": "Code sign as necessary using standard method." }, { "code": null, "e": 5196, "s": 5150, "text": "Code sign as necessary using standard method." }, { "code": null, "e": 5251, "s": 5196, "text": "Add a new app icon as necessary using standard method." }, { "code": null, "e": 5306, "s": 5251, "text": "Add a new app icon as necessary using standard method." }, { "code": null, "e": 5354, "s": 5306, "text": "Generate IPA file using the following command −" }, { "code": null, "e": 5402, "s": 5354, "text": "Generate IPA file using the following command −" }, { "code": null, "e": 5421, "s": 5402, "text": "flutter build ios\n" }, { "code": null, "e": 5461, "s": 5421, "text": "Now, you can see the following output −" }, { "code": null, "e": 5501, "s": 5461, "text": "Now, you can see the following output −" }, { "code": null, "e": 5746, "s": 5501, "text": "Building com.example.MyApp for device (ios-release)... \nAutomatically signing iOS for device deployment \nusing specified development team in Xcode project: \nRunning Xcode build... 23.5s \n......................\n" }, { "code": null, "e": 5843, "s": 5746, "text": "Test the application by pushing the application, IPA file into TestFlight using standard method." }, { "code": null, "e": 5940, "s": 5843, "text": "Test the application by pushing the application, IPA file into TestFlight using standard method." }, { "code": null, "e": 6008, "s": 5940, "text": "Finally, push the application into App Store using standard method." }, { "code": null, "e": 6076, "s": 6008, "text": "Finally, push the application into App Store using standard method." }, { "code": null, "e": 6109, "s": 6076, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6129, "s": 6109, "text": " Sriyank Siddhartha" }, { "code": null, "e": 6164, "s": 6129, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 6181, "s": 6164, "text": " Frahaan Hussain" }, { "code": null, "e": 6214, "s": 6181, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 6234, "s": 6214, "text": " Skillbakerystudios" }, { "code": null, "e": 6266, "s": 6234, "text": "\n 17 Lectures \n 51 mins\n" }, { "code": null, "e": 6286, "s": 6266, "text": " Harsh Kumar Khatri" }, { "code": null, "e": 6321, "s": 6286, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6336, "s": 6321, "text": " Pramila Rawat" }, { "code": null, "e": 6372, "s": 6336, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 6387, "s": 6372, "text": " Rahul Agarwal" }, { "code": null, "e": 6394, "s": 6387, "text": " Print" }, { "code": null, "e": 6405, "s": 6394, "text": " Add Notes" } ]
C# Linq Sum() Method
Find the sum of elements using the Linq Sum() method. Here’s our list with integer elements. List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88}; Now find the sum using the Sum() method. list.AsQueryable().Sum(); The following is an example to find the sum of elements of a list with integer elements. Live Demo using System; using System.Linq; using System.Collections.Generic; public class Demo { public static void Main() { List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88}; int res = list.AsQueryable().Sum(); Console.WriteLine("Sum = {0}", res); } } Sum = 495
[ { "code": null, "e": 1116, "s": 1062, "text": "Find the sum of elements using the Linq Sum() method." }, { "code": null, "e": 1155, "s": 1116, "text": "Here’s our list with integer elements." }, { "code": null, "e": 1217, "s": 1155, "text": "List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88};" }, { "code": null, "e": 1258, "s": 1217, "text": "Now find the sum using the Sum() method." }, { "code": null, "e": 1284, "s": 1258, "text": "list.AsQueryable().Sum();" }, { "code": null, "e": 1373, "s": 1284, "text": "The following is an example to find the sum of elements of a list with integer elements." }, { "code": null, "e": 1384, "s": 1373, "text": " Live Demo" }, { "code": null, "e": 1662, "s": 1384, "text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88};\n int res = list.AsQueryable().Sum();\n Console.WriteLine(\"Sum = {0}\", res);\n }\n}" }, { "code": null, "e": 1672, "s": 1662, "text": "Sum = 495" } ]
Keyboard shortcuts with Tkinter in Python 3
Tkinter window contains many inbuilt functionalities and features which can be taken and used for various application development. There might be cases when we have to run a particular part of the application with the help of some key or function. It can be achieved by binding a particular key with the callback that contains the functions for the operation. The key can be anything from Mouse Buttons to Keyboard Keys. We can even bind the callback with Keyboard Key Combinations. #Import the Tkinter Library from tkinter import * #Create an instance of Tkinter Frame win = Tk() #Set the geometry of window win.geometry("700x350") #Define a callback function for exit def quit_program(e): win.destroy() #Add a Label widget label = Label(win, text= "Press Ctrl + x to Exit", font= ('Helvetica 15 bold')) label.pack(pady= 40) #Bind the Keyboard shortcut Key win.bind('<Control-x>', quit_program) win.mainloop() In the above code, we have added a combination of Keys. Pressing the keys will close the window.
[ { "code": null, "e": 1545, "s": 1062, "text": "Tkinter window contains many inbuilt functionalities and features which can be taken and used for various application development. There might be cases when we have to run a particular part of the application with the help of some key or function. It can be achieved by binding a particular key with the callback that contains the functions for the operation. The key can be anything from Mouse Buttons to Keyboard Keys. We can even bind the callback with Keyboard Key Combinations." }, { "code": null, "e": 1981, "s": 1545, "text": "#Import the Tkinter Library\nfrom tkinter import *\n\n#Create an instance of Tkinter Frame\nwin = Tk()\n\n#Set the geometry of window\nwin.geometry(\"700x350\")\n\n#Define a callback function for exit\ndef quit_program(e):\n win.destroy()\n\n#Add a Label widget\nlabel = Label(win, text= \"Press Ctrl + x to Exit\", font= ('Helvetica 15 bold'))\nlabel.pack(pady= 40)\n\n#Bind the Keyboard shortcut Key\nwin.bind('<Control-x>', quit_program)\nwin.mainloop()" }, { "code": null, "e": 2078, "s": 1981, "text": "In the above code, we have added a combination of Keys. Pressing the keys will close the window." } ]
MySQL Error ERROR 1099 (HY000): Table was locked with a READ lock and can't be updated
To get rid of LOCK TABLES query, you need to use UNLOCK TABLES. Let us create a table − mysql> create table demo6 −> ( −> country_name varchar(100 −> ) −> ); Query OK, 0 rows affected (1.51 sec) Insert some records into the table with the help of insert command − mysql> insert into demo6 values('US'); Query OK, 1 row affected (0.11 sec) mysql> insert into demo6 values('UK'); Query OK, 1 row affected (0.08 sec) mysql> insert into demo6 values('AUS'); Query OK, 1 row affected (0.11 sec) Display records from the table using select statement − mysql> select *from demo6; This will produce the following output − +--------------+ | country_name | +--------------+ | US | | UK | | AUS | +--------------+ 3 rows in set (0.00 sec) Here, I have a lock on the above table only for read operator. Following is the query − mysql> lock tables demo6 read; Query OK, 0 rows affected (0.00 sec) Following is the error when you try to insert on the above table − mysql> insert into demo6 values('IND'); ERROR 1099 (HY000): Table 'demo6' was locked with a READ lock and can't be updated If you use UNLOCK TABLES, then you can insert records in the same table − mysql> UNLOCK TABLES; Query OK, 0 rows affected (0.00 sec) Insert some records into the table with the help of insert command − mysql> insert into demo6 values('IND'); Query OK, 1 row affected (0.09 sec) Display records from the table using select statement − mysql> select *from demo6; This will produce the following output − +--------------+ | country_name | +--------------+ | US | | UK | | AUS | | IND | +--------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1126, "s": 1062, "text": "To get rid of LOCK TABLES query, you need to use UNLOCK TABLES." }, { "code": null, "e": 1150, "s": 1126, "text": "Let us create a table −" }, { "code": null, "e": 1257, "s": 1150, "text": "mysql> create table demo6\n−> (\n−> country_name varchar(100\n−> )\n−> );\nQuery OK, 0 rows affected (1.51 sec)" }, { "code": null, "e": 1326, "s": 1257, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 1554, "s": 1326, "text": "mysql> insert into demo6 values('US');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into demo6 values('UK');\nQuery OK, 1 row affected (0.08 sec)\n\nmysql> insert into demo6 values('AUS');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1610, "s": 1554, "text": "Display records from the table using select statement −" }, { "code": null, "e": 1637, "s": 1610, "text": "mysql> select *from demo6;" }, { "code": null, "e": 1678, "s": 1637, "text": "This will produce the following output −" }, { "code": null, "e": 1822, "s": 1678, "text": "+--------------+\n| country_name |\n+--------------+\n| US |\n| UK |\n| AUS |\n+--------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1910, "s": 1822, "text": "Here, I have a lock on the above table only for read operator. Following is the query −" }, { "code": null, "e": 1978, "s": 1910, "text": "mysql> lock tables demo6 read;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2045, "s": 1978, "text": "Following is the error when you try to insert on the above table −" }, { "code": null, "e": 2168, "s": 2045, "text": "mysql> insert into demo6 values('IND');\nERROR 1099 (HY000): Table 'demo6' was locked with a READ lock and can't be updated" }, { "code": null, "e": 2242, "s": 2168, "text": "If you use UNLOCK TABLES, then you can insert records in the same table −" }, { "code": null, "e": 2301, "s": 2242, "text": "mysql> UNLOCK TABLES;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2370, "s": 2301, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 2446, "s": 2370, "text": "mysql> insert into demo6 values('IND');\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 2502, "s": 2446, "text": "Display records from the table using select statement −" }, { "code": null, "e": 2529, "s": 2502, "text": "mysql> select *from demo6;" }, { "code": null, "e": 2570, "s": 2529, "text": "This will produce the following output −" }, { "code": null, "e": 2731, "s": 2570, "text": "+--------------+\n| country_name |\n+--------------+\n| US |\n| UK |\n| AUS |\n| IND |\n+--------------+\n4 rows in set (0.00 sec)" } ]
Python PIL | Image.frombuffer() method
07 Aug, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. PIL.Image.frombuffer() Creates an image memory referencing pixel data in a byte buffer. Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a BytesIO object, and use open() to load it. Syntax: PIL.Image.frombuffer(mode, size, data, decoder_name=’raw’, *args) Parameters:mode – The image mode. See: Modessize – The image size.data – A byte buffer containing raw data for the given mode.decoder_name – What decoder to use.args – Additional parameters for the given decoder. For the default encoder (“raw”), it’s recommended that you provide the full set of parameters:frombuffer(mode, size, data, "raw", mode, 0, 1) Returns: An Image object. Image Used: # importing image object from PILfrom PIL import Image # creating an image objectim = Image.open(r"C:\Users\System-Pc\Desktop\rose.jpg")im1 = im.tobytes("xbm", "rgb")img = Image.frombuffer("L", (4, 4), im1, 'raw', "L", 0, 1) # creating list img2 = list(img.getdata())print(img2) Output: [48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48] Another Example: Here we use another image. Image Used: # importing image object from PILfrom PIL import Image # creating an image objectim = Image.open(r"C:\Users\System-Pc\Desktop\ellipse1.png")im1 = im.tobytes("xbm", "rgb")img = Image.frombuffer("L", (10, 10), im1, 'raw', "L", 0, 1) # creating list img2 = list(img.getdata())print(img2) Output: [48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 10, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56] Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Aug, 2019" }, { "code": null, "e": 355, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images." }, { "code": null, "e": 443, "s": 355, "text": "PIL.Image.frombuffer() Creates an image memory referencing pixel data in a byte buffer." }, { "code": null, "e": 613, "s": 443, "text": "Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a BytesIO object, and use open() to load it." }, { "code": null, "e": 687, "s": 613, "text": "Syntax: PIL.Image.frombuffer(mode, size, data, decoder_name=’raw’, *args)" }, { "code": null, "e": 1042, "s": 687, "text": "Parameters:mode – The image mode. See: Modessize – The image size.data – A byte buffer containing raw data for the given mode.decoder_name – What decoder to use.args – Additional parameters for the given decoder. For the default encoder (“raw”), it’s recommended that you provide the full set of parameters:frombuffer(mode, size, data, \"raw\", mode, 0, 1)" }, { "code": null, "e": 1068, "s": 1042, "text": "Returns: An Image object." }, { "code": null, "e": 1080, "s": 1068, "text": "Image Used:" }, { "code": " # importing image object from PILfrom PIL import Image # creating an image objectim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\rose.jpg\")im1 = im.tobytes(\"xbm\", \"rgb\")img = Image.frombuffer(\"L\", (4, 4), im1, 'raw', \"L\", 0, 1) # creating list img2 = list(img.getdata())print(img2)", "e": 1366, "s": 1080, "text": null }, { "code": null, "e": 1374, "s": 1366, "text": "Output:" }, { "code": null, "e": 1448, "s": 1374, "text": "[48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48]" }, { "code": null, "e": 1492, "s": 1448, "text": "Another Example: Here we use another image." }, { "code": null, "e": 1504, "s": 1492, "text": "Image Used:" }, { "code": " # importing image object from PILfrom PIL import Image # creating an image objectim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\ellipse1.png\")im1 = im.tobytes(\"xbm\", \"rgb\")img = Image.frombuffer(\"L\", (10, 10), im1, 'raw', \"L\", 0, 1) # creating list img2 = list(img.getdata())print(img2)", "e": 1797, "s": 1504, "text": null }, { "code": null, "e": 1805, "s": 1797, "text": "Output:" }, { "code": null, "e": 2226, "s": 1805, "text": "[48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 10, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56]" }, { "code": null, "e": 2237, "s": 2226, "text": "Python-pil" }, { "code": null, "e": 2244, "s": 2237, "text": "Python" }, { "code": null, "e": 2342, "s": 2244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2374, "s": 2342, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2401, "s": 2374, "text": "Python Classes and Objects" }, { "code": null, "e": 2422, "s": 2401, "text": "Python OOPs Concepts" }, { "code": null, "e": 2445, "s": 2422, "text": "Introduction To PYTHON" }, { "code": null, "e": 2501, "s": 2445, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2543, "s": 2501, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2574, "s": 2543, "text": "Python | os.path.join() method" }, { "code": null, "e": 2616, "s": 2574, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2655, "s": 2616, "text": "Python | Get unique values from a list" } ]
Generic Trees(N-array Trees)
28 Sep, 2020 Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and the very first node’s address will be stored in a separate pointer called root. The Generic trees are the N-ary trees which have the following properties: 1. Many children at every node. 2. The number of nodes for each node is not known in advance. Example: Generic Tree To represent the above tree, we have to consider the worst case, that is the node with maximum children (in above example, 6 children) and allocate that many pointers for each node.The node representation based on this method can be written as: C //Node declarationstruct Node{ int data; struct Node *firstchild; struct Node *secondchild; struct Node *thirdchild; struct Node *fourthchild; struct Node *fifthchild; struct Node *sixthchild;} Disadvantages of the above representation are: Memory Wastage – All the pointers are not required in all the cases. Hence, there is lot of memory wastage.Unknown number of children – The number of children for each node is not known in advance. Memory Wastage – All the pointers are not required in all the cases. Hence, there is lot of memory wastage. Unknown number of children – The number of children for each node is not known in advance. Simple Approach: For storing the address of children in a node we can use an array or linked list. But we will face some issues with both of them. In Linked list, we can not randomly access any child’s address. So it will be expensive.In array, we can randomly access the address of any child, but we can store only fixed number of children’s addresses in it. In Linked list, we can not randomly access any child’s address. So it will be expensive. In array, we can randomly access the address of any child, but we can store only fixed number of children’s addresses in it. Better Approach: We can use Dynamic Arrays for storing the address of children’s address. We can randomly access any child’s address and the size of the vector is also not fixed. C //Node declarationstruct Node{ int data; vector<Node*> children;} First child / Next sibling representation In the first child/next sibling representation, the steps taken are: At each node-link the children of the same parent(siblings) from left to right. Remove the links from parent to all children except the first child. Since we have a link between children, we do not need extra links from parents to all the children. This representation allows us to traverse all the elements by starting at the first child of the parent. FIRST CHILD/NEXT SIBLING REPRESENTATION The node declaration for first child / next sibling representation can be written as: C //Node declarationstruct Node{ int data; struct Node *firstChild; struct Node *nextSibling;} Advantages: Memory efficient – No extra links are required, hence a lot of memory is saved. Treated as binary trees – Since we are able to convert any generic tree to binary representation, we can treat all generic trees with a first child/next sibling representation as binary trees. Instead of left and right pointers, we just use firstChild and nextSibling. Many algorithms can be expressed more easily because it is just a binary tree. Each node is of fixed size no auxiliary array or vector is required. Height of generic tree from parent array Generic tree – level order traversal priyankashrm7302 n-ary-tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Introduction to Data Structures Introduction to Tree Data Structure Inorder Tree Traversal without Recursion What is Data Structure: Types, Classifications and Applications Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Sep, 2020" }, { "code": null, "e": 433, "s": 54, "text": "Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and the very first node’s address will be stored in a separate pointer called root." }, { "code": null, "e": 509, "s": 433, "text": "The Generic trees are the N-ary trees which have the following properties: " }, { "code": null, "e": 553, "s": 509, "text": " 1. Many children at every node." }, { "code": null, "e": 627, "s": 553, "text": " 2. The number of nodes for each node is not known in advance." }, { "code": null, "e": 638, "s": 627, "text": "Example: " }, { "code": null, "e": 651, "s": 638, "text": "Generic Tree" }, { "code": null, "e": 897, "s": 651, "text": "To represent the above tree, we have to consider the worst case, that is the node with maximum children (in above example, 6 children) and allocate that many pointers for each node.The node representation based on this method can be written as: " }, { "code": null, "e": 899, "s": 897, "text": "C" }, { "code": "//Node declarationstruct Node{ int data; struct Node *firstchild; struct Node *secondchild; struct Node *thirdchild; struct Node *fourthchild; struct Node *fifthchild; struct Node *sixthchild;}", "e": 1107, "s": 899, "text": null }, { "code": null, "e": 1155, "s": 1107, "text": "Disadvantages of the above representation are: " }, { "code": null, "e": 1353, "s": 1155, "text": "Memory Wastage – All the pointers are not required in all the cases. Hence, there is lot of memory wastage.Unknown number of children – The number of children for each node is not known in advance." }, { "code": null, "e": 1461, "s": 1353, "text": "Memory Wastage – All the pointers are not required in all the cases. Hence, there is lot of memory wastage." }, { "code": null, "e": 1552, "s": 1461, "text": "Unknown number of children – The number of children for each node is not known in advance." }, { "code": null, "e": 1570, "s": 1552, "text": "Simple Approach: " }, { "code": null, "e": 1700, "s": 1570, "text": "For storing the address of children in a node we can use an array or linked list. But we will face some issues with both of them." }, { "code": null, "e": 1913, "s": 1700, "text": "In Linked list, we can not randomly access any child’s address. So it will be expensive.In array, we can randomly access the address of any child, but we can store only fixed number of children’s addresses in it." }, { "code": null, "e": 2002, "s": 1913, "text": "In Linked list, we can not randomly access any child’s address. So it will be expensive." }, { "code": null, "e": 2127, "s": 2002, "text": "In array, we can randomly access the address of any child, but we can store only fixed number of children’s addresses in it." }, { "code": null, "e": 2144, "s": 2127, "text": "Better Approach:" }, { "code": null, "e": 2306, "s": 2144, "text": "We can use Dynamic Arrays for storing the address of children’s address. We can randomly access any child’s address and the size of the vector is also not fixed." }, { "code": null, "e": 2308, "s": 2306, "text": "C" }, { "code": "//Node declarationstruct Node{ int data; vector<Node*> children;}", "e": 2380, "s": 2308, "text": null }, { "code": null, "e": 2422, "s": 2380, "text": "First child / Next sibling representation" }, { "code": null, "e": 2493, "s": 2422, "text": " In the first child/next sibling representation, the steps taken are: " }, { "code": null, "e": 2573, "s": 2493, "text": "At each node-link the children of the same parent(siblings) from left to right." }, { "code": null, "e": 2642, "s": 2573, "text": "Remove the links from parent to all children except the first child." }, { "code": null, "e": 2848, "s": 2642, "text": "Since we have a link between children, we do not need extra links from parents to all the children. This representation allows us to traverse all the elements by starting at the first child of the parent. " }, { "code": null, "e": 2888, "s": 2848, "text": "FIRST CHILD/NEXT SIBLING REPRESENTATION" }, { "code": null, "e": 2976, "s": 2888, "text": "The node declaration for first child / next sibling representation can be written as: " }, { "code": null, "e": 2978, "s": 2976, "text": "C" }, { "code": "//Node declarationstruct Node{ int data; struct Node *firstChild; struct Node *nextSibling;}", "e": 3080, "s": 2978, "text": null }, { "code": null, "e": 3093, "s": 3080, "text": "Advantages: " }, { "code": null, "e": 3173, "s": 3093, "text": "Memory efficient – No extra links are required, hence a lot of memory is saved." }, { "code": null, "e": 3442, "s": 3173, "text": "Treated as binary trees – Since we are able to convert any generic tree to binary representation, we can treat all generic trees with a first child/next sibling representation as binary trees. Instead of left and right pointers, we just use firstChild and nextSibling." }, { "code": null, "e": 3521, "s": 3442, "text": "Many algorithms can be expressed more easily because it is just a binary tree." }, { "code": null, "e": 3590, "s": 3521, "text": "Each node is of fixed size no auxiliary array or vector is required." }, { "code": null, "e": 3668, "s": 3590, "text": "Height of generic tree from parent array Generic tree – level order traversal" }, { "code": null, "e": 3685, "s": 3668, "text": "priyankashrm7302" }, { "code": null, "e": 3696, "s": 3685, "text": "n-ary-tree" }, { "code": null, "e": 3701, "s": 3696, "text": "Tree" }, { "code": null, "e": 3706, "s": 3701, "text": "Tree" }, { "code": null, "e": 3804, "s": 3706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3854, "s": 3804, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 3889, "s": 3854, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 3923, "s": 3889, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 3952, "s": 3923, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 3984, "s": 3952, "text": "Introduction to Data Structures" }, { "code": null, "e": 4020, "s": 3984, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 4061, "s": 4020, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 4125, "s": 4061, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 4187, "s": 4125, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" } ]
host command in Linux with examples
21 May, 2019 host command in Linux system is used for DNS (Domain Name System) lookup operations. In simple words, this command is used to find the IP address of a particular domain name or if you want to find out the domain name of a particular IP address the host command becomes handy. You can also find more specific details of a domain by specifying the corresponding option along with the domain name. Syntax: host [-aCdlriTWV] [-c class] [-N ndots] [-t type] [-W time] [-R number] [-m flag] hostname [server] host command without any option: It will print the general syntax of the command along with the various options that can be used with the host command as well as gives a brief description about each option. Example: Different options with the host command: host domain_name: This will print the IP address details of the specified domain.Example:host geeksforgeeks.org Example: host geeksforgeeks.org host IP_Address: This will display the domain details of the specified IP Address.Example:host 52.25.109.230 Example: host 52.25.109.230 -a or -v: It used to specify the query type or enables the verbose output.Example:host -a geeksforgeeks.org Example: host -a geeksforgeeks.org -t : It is used to specify the type of query.Example 1:host -t ns geeksforgeeks.org Example 2: To print SOA recordhost -t SOA geeksforgeeks.org Example 3: To print txt recordhost -t txt geeksforgeeks.org Example 1: host -t ns geeksforgeeks.org Example 2: To print SOA record host -t SOA geeksforgeeks.org Example 3: To print txt record host -t txt geeksforgeeks.org -C : In order to compare the SOA records on authoritative nameservers.Example:host -C geeksforgeeks.org Example: host -C geeksforgeeks.org -R : In order to specify the number of retries you can do in case one try fails. If anyone try succeeds then the command stops.Example:host -R 3 geeksforgeeks.org Example: host -R 3 geeksforgeeks.org -l :In order to list all hosts in a domain.For this command to work you need to be either an admin or a node server.Example:host -l geeksforgeeks.org Example: host -l geeksforgeeks.org linux-command Linux-networking-commands 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 SORT command in Linux/Unix 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
[ { "code": null, "e": 53, "s": 25, "text": "\n21 May, 2019" }, { "code": null, "e": 448, "s": 53, "text": "host command in Linux system is used for DNS (Domain Name System) lookup operations. In simple words, this command is used to find the IP address of a particular domain name or if you want to find out the domain name of a particular IP address the host command becomes handy. You can also find more specific details of a domain by specifying the corresponding option along with the domain name." }, { "code": null, "e": 456, "s": 448, "text": "Syntax:" }, { "code": null, "e": 562, "s": 456, "text": "host [-aCdlriTWV] [-c class] [-N ndots] [-t type] [-W time]\n [-R number] [-m flag] hostname [server]\n" }, { "code": null, "e": 769, "s": 562, "text": "host command without any option: It will print the general syntax of the command along with the various options that can be used with the host command as well as gives a brief description about each option." }, { "code": null, "e": 778, "s": 769, "text": "Example:" }, { "code": null, "e": 819, "s": 778, "text": "Different options with the host command:" }, { "code": null, "e": 931, "s": 819, "text": "host domain_name: This will print the IP address details of the specified domain.Example:host geeksforgeeks.org" }, { "code": null, "e": 940, "s": 931, "text": "Example:" }, { "code": null, "e": 963, "s": 940, "text": "host geeksforgeeks.org" }, { "code": null, "e": 1072, "s": 963, "text": "host IP_Address: This will display the domain details of the specified IP Address.Example:host 52.25.109.230" }, { "code": null, "e": 1081, "s": 1072, "text": "Example:" }, { "code": null, "e": 1100, "s": 1081, "text": "host 52.25.109.230" }, { "code": null, "e": 1209, "s": 1100, "text": "-a or -v: It used to specify the query type or enables the verbose output.Example:host -a geeksforgeeks.org " }, { "code": null, "e": 1218, "s": 1209, "text": "Example:" }, { "code": null, "e": 1245, "s": 1218, "text": "host -a geeksforgeeks.org " }, { "code": null, "e": 1453, "s": 1245, "text": "-t : It is used to specify the type of query.Example 1:host -t ns geeksforgeeks.org Example 2: To print SOA recordhost -t SOA geeksforgeeks.org Example 3: To print txt recordhost -t txt geeksforgeeks.org " }, { "code": null, "e": 1464, "s": 1453, "text": "Example 1:" }, { "code": null, "e": 1495, "s": 1464, "text": "host -t ns geeksforgeeks.org " }, { "code": null, "e": 1526, "s": 1495, "text": "Example 2: To print SOA record" }, { "code": null, "e": 1558, "s": 1526, "text": "host -t SOA geeksforgeeks.org " }, { "code": null, "e": 1589, "s": 1558, "text": "Example 3: To print txt record" }, { "code": null, "e": 1621, "s": 1589, "text": "host -t txt geeksforgeeks.org " }, { "code": null, "e": 1726, "s": 1621, "text": "-C : In order to compare the SOA records on authoritative nameservers.Example:host -C geeksforgeeks.org " }, { "code": null, "e": 1735, "s": 1726, "text": "Example:" }, { "code": null, "e": 1762, "s": 1735, "text": "host -C geeksforgeeks.org " }, { "code": null, "e": 1926, "s": 1762, "text": "-R : In order to specify the number of retries you can do in case one try fails. If anyone try succeeds then the command stops.Example:host -R 3 geeksforgeeks.org " }, { "code": null, "e": 1935, "s": 1926, "text": "Example:" }, { "code": null, "e": 1964, "s": 1935, "text": "host -R 3 geeksforgeeks.org " }, { "code": null, "e": 2115, "s": 1964, "text": "-l :In order to list all hosts in a domain.For this command to work you need to be either an admin or a node server.Example:host -l geeksforgeeks.org " }, { "code": null, "e": 2124, "s": 2115, "text": "Example:" }, { "code": null, "e": 2151, "s": 2124, "text": "host -l geeksforgeeks.org " }, { "code": null, "e": 2165, "s": 2151, "text": "linux-command" }, { "code": null, "e": 2191, "s": 2165, "text": "Linux-networking-commands" }, { "code": null, "e": 2198, "s": 2191, "text": "Picked" }, { "code": null, "e": 2209, "s": 2198, "text": "Linux-Unix" }, { "code": null, "e": 2307, "s": 2209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2342, "s": 2307, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 2377, "s": 2342, "text": "tar command in Linux with examples" }, { "code": null, "e": 2413, "s": 2377, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2454, "s": 2413, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 2490, "s": 2454, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2528, "s": 2490, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2566, "s": 2528, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2592, "s": 2566, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2627, "s": 2592, "text": "scp command in Linux with Examples" } ]
Python | Union of two or more Lists
21 Nov, 2018 Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on.Examples: Maintained repetition only Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] Output : [23, 15, 2, 14, 14, 16, 20, 52, 2, 48, 15, 12, 26, 32, 47, 54] Maintained repetition and order Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] Output : [2, 2, 12, 14, 14, 15, 15, 16, 20, 23, 26, 32, 47, 48, 52, 54] Without repetition Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] Output : [32, 2, 12, 14, 15, 16, 48, 47, 20, 52, 54, 23, 26] Union of three lists Input : lst1 = [23, 15, 2, 14, 14, 16, 20 ,52] lst2 = [2, 48, 15, 12, 26, 32, 47, 54] lst3 = [4, 78, 5, 6, 9, 25, 64, 32, 59] Output : [32, 64, 2, 4, 5, 6, 9, 12, 14, 15, 16, 48, 47, 78, 20, 52, 54, 23, 25, 26, 59] Maintaining Repetition We can simply use the plus “+” operator inorder to combine two list into one. This will reflect the repetition. # Python program to illustrate union# Maintained repetition def Union(lst1, lst2): final_list = lst1 + lst2 return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]print(Union(lst1, lst2)) Output: [23, 15, 2, 14, 14, 16, 20, 52, 2, 48, 15, 12, 26, 32, 47, 54] Maintaining both Repetition and Order To maintain the order of appearance in the new list we need to use the sorted() function, passing the addition of two lists(plus operated, as in the previous problem) as parameters. # Python program to illustrate union# Maintained repetition and order def Union(lst1, lst2): final_list = sorted(lst1 + lst2) return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]print(Union(lst1, lst2)) Output: [2, 2, 12, 14, 14, 15, 15, 16, 20, 23, 26, 32, 47, 48, 52, 54] Without Repetition To get rid of all the repetitive elements from the initial list, we use the set() function on both the lists, individually. Then we add them using the “+” operator and pass as a new list. # Python program to illustrate union# Without repetition def Union(lst1, lst2): final_list = list(set(lst1) | set(lst2)) return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]print(Union(lst1, lst2)) Output: [32, 2, 12, 14, 15, 16, 48, 47, 20, 52, 54, 23, 26] More than two lists We can also make an union of more than two lists. This can be done efficiently by using both the set() and union() function, simultaneously, as shown in the below example. This also takes care of the repetition and prevents them. # Python program to illustrate union# Union of three listsdef Union(lst1, lst2, lst3): final_list = list(set().union(lst1, lst2, lst3)) return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]lst3 = [4, 78, 5, 6, 9, 25, 64, 32, 59]print(Union(lst1, lst2, lst3)) Output: [32, 64, 2, 4, 5, 6, 9, 12, 14, 15, 16, 48, 47, 78, 20, 52, 54, 23, 25, 26, 59] Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Nov, 2018" }, { "code": null, "e": 384, "s": 53, "text": "Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on.Examples:" }, { "code": null, "e": 1172, "s": 384, "text": "Maintained repetition only\nInput : \nlst1 = [23, 15, 2, 14, 14, 16, 20 ,52]\nlst2 = [2, 48, 15, 12, 26, 32, 47, 54]\nOutput :\n[23, 15, 2, 14, 14, 16, 20, 52, 2, 48, \n15, 12, 26, 32, 47, 54]\n\nMaintained repetition and order\nInput : \nlst1 = [23, 15, 2, 14, 14, 16, 20 ,52]\nlst2 = [2, 48, 15, 12, 26, 32, 47, 54]\nOutput :\n[2, 2, 12, 14, 14, 15, 15, 16, 20, 23, \n26, 32, 47, 48, 52, 54]\n\nWithout repetition\nInput : \nlst1 = [23, 15, 2, 14, 14, 16, 20 ,52]\nlst2 = [2, 48, 15, 12, 26, 32, 47, 54]\nOutput :\n[32, 2, 12, 14, 15, 16, 48, 47, 20, 52, 54, 23, 26]\n\nUnion of three lists\nInput : \nlst1 = [23, 15, 2, 14, 14, 16, 20 ,52]\nlst2 = [2, 48, 15, 12, 26, 32, 47, 54]\nlst3 = [4, 78, 5, 6, 9, 25, 64, 32, 59]\nOutput :\n[32, 64, 2, 4, 5, 6, 9, 12, 14, 15, 16, \n48, 47, 78, 20, 52, 54, 23, 25, 26, 59]\n" }, { "code": null, "e": 1195, "s": 1172, "text": "Maintaining Repetition" }, { "code": null, "e": 1307, "s": 1195, "text": "We can simply use the plus “+” operator inorder to combine two list into one. This will reflect the repetition." }, { "code": "# Python program to illustrate union# Maintained repetition def Union(lst1, lst2): final_list = lst1 + lst2 return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]print(Union(lst1, lst2))", "e": 1554, "s": 1307, "text": null }, { "code": null, "e": 1562, "s": 1554, "text": "Output:" }, { "code": null, "e": 1627, "s": 1562, "text": "[23, 15, 2, 14, 14, 16, 20, 52, 2, 48, 15, \n12, 26, 32, 47, 54]\n" }, { "code": null, "e": 1665, "s": 1627, "text": "Maintaining both Repetition and Order" }, { "code": null, "e": 1847, "s": 1665, "text": "To maintain the order of appearance in the new list we need to use the sorted() function, passing the addition of two lists(plus operated, as in the previous problem) as parameters." }, { "code": "# Python program to illustrate union# Maintained repetition and order def Union(lst1, lst2): final_list = sorted(lst1 + lst2) return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]print(Union(lst1, lst2))", "e": 2112, "s": 1847, "text": null }, { "code": null, "e": 2120, "s": 2112, "text": "Output:" }, { "code": null, "e": 2184, "s": 2120, "text": "[2, 2, 12, 14, 14, 15, 15, 16, 20, 23, 26, 32, 47, 48, 52, 54]\n" }, { "code": null, "e": 2203, "s": 2184, "text": "Without Repetition" }, { "code": null, "e": 2391, "s": 2203, "text": "To get rid of all the repetitive elements from the initial list, we use the set() function on both the lists, individually. Then we add them using the “+” operator and pass as a new list." }, { "code": "# Python program to illustrate union# Without repetition def Union(lst1, lst2): final_list = list(set(lst1) | set(lst2)) return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]print(Union(lst1, lst2))", "e": 2651, "s": 2391, "text": null }, { "code": null, "e": 2659, "s": 2651, "text": "Output:" }, { "code": null, "e": 2713, "s": 2659, "text": "[32, 2, 12, 14, 15, 16, 48, 47, 20, \n52, 54, 23, 26]\n" }, { "code": null, "e": 2733, "s": 2713, "text": "More than two lists" }, { "code": null, "e": 2963, "s": 2733, "text": "We can also make an union of more than two lists. This can be done efficiently by using both the set() and union() function, simultaneously, as shown in the below example. This also takes care of the repetition and prevents them." }, { "code": "# Python program to illustrate union# Union of three listsdef Union(lst1, lst2, lst3): final_list = list(set().union(lst1, lst2, lst3)) return final_list # Driver Codelst1 = [23, 15, 2, 14, 14, 16, 20 ,52]lst2 = [2, 48, 15, 12, 26, 32, 47, 54]lst3 = [4, 78, 5, 6, 9, 25, 64, 32, 59]print(Union(lst1, lst2, lst3))", "e": 3283, "s": 2963, "text": null }, { "code": null, "e": 3291, "s": 3283, "text": "Output:" }, { "code": null, "e": 3373, "s": 3291, "text": "[32, 64, 2, 4, 5, 6, 9, 12, 14, 15, 16, \n48, 47, 78, 20, 52, 54, 23, 25, 26, 59]\n" }, { "code": null, "e": 3394, "s": 3373, "text": "Python list-programs" }, { "code": null, "e": 3406, "s": 3394, "text": "python-list" }, { "code": null, "e": 3413, "s": 3406, "text": "Python" }, { "code": null, "e": 3425, "s": 3413, "text": "python-list" }, { "code": null, "e": 3523, "s": 3425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3541, "s": 3523, "text": "Python Dictionary" }, { "code": null, "e": 3583, "s": 3541, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3605, "s": 3583, "text": "Enumerate() in Python" }, { "code": null, "e": 3640, "s": 3605, "text": "Read a file line by line in Python" }, { "code": null, "e": 3666, "s": 3640, "text": "Python String | replace()" }, { "code": null, "e": 3698, "s": 3666, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3727, "s": 3698, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3754, "s": 3727, "text": "Python Classes and Objects" }, { "code": null, "e": 3784, "s": 3754, "text": "Iterate over a list in Python" } ]
VLOOKUP On Multiple Criteria Columns Using Helper Method & CHOOSE Function
09 Sep, 2021 In this article, we will see how we can combine multiple values, and use them as lookup criteria for searching specific value(s) in the excel dataset. For this purpose, we will use the VLOOKUP formula, the most basic formula to perform a lookup for value(s) on excel. We will see a modified form of VLOOKUP to perform a lookup using multiple values. First, let us see a general formula: Formula: =VLOOKUP(v1&v2,dataset_part,column,0) Here, Here v1 and v2 signify those two cells, which will be used for lookup in combination. The Dataset_part signify the starting cell value and the ending cell value, upon which lookup is to be performed. This can consist of the whole dataset as well. The column signifies from which column the value has to be picked up. Here 0 signifies the approximation of lookup in vlookup. It can be set to 1 to enable approximation. Now, let us see in brief, or a summary, how VLOOKUP will work in the Multiple Criteria Column. Here, we have 2 ways of modifying VLOOKUP to make it capable of doing a lookup on multiple criteria, they are: Helper Column.CHOOSE function. Helper Column. CHOOSE function. Helper column will be a sort of redundant work, as we have to provide merged values of those columns on which VLOOKUP is doing the lookup, or we can use concatenation to concat the columns values. It should be kept in mind that the helper column should be the first column of our data. The CHOOSE function is usually preferred over creating a helper column in smaller datasets. Now, let us see an example in both ways. Now, let’s suppose we have this dataset with us. On the left side, the main dataset is written, and on the right side, a record has to be taken out from the main database. Now, you can either use CONCATENATE function, or you can manually write the merged values of your criteria columns in the helper column. Here, we want to know the area of study of RIZWAN AHMAD. But, we don’t know any other method than VLOOKUP to perform this. So, we will use VLOOKUP to achieve this. First, let us see the formula and understand it argument by argument. =VLOOKUP(H1&H2,A2:D5,4,0) The output of this will be: Now, we achieved the correct result, but how? Let’s look at it. H1&H2: The name is divided into 2 cells, which have been taken from criteria cells. A2:D5: The data is taken from this range. 4: This is the column number from which data will be retrieved,i.e from the AREA column. 0: This signifies that the approximation of lookup is turned off. Here, the thing to keep in mind is that the helper column should always be created on the first column of the dataset. Now, as discussed the helper column is not very much suited for smaller datasets. So, we will use CHOOSE function along with VLOOKUP to achieve the multiple criteria lookup. Now, let’s suppose the given dataset is big, and we want to know the area of study of RIZWAN AHMAD, so for this, we will use CHOOSE function, which will help us create a 2D array, in which the search criteria values and other arguments will be stored and used. Considering this dataset, the formula will be: =VLOOKUP(H1&&H2,CHOOSE({1,2},B2:B5&&C2:C5,D2:D5),2,0) Inserting this formula in H3, we will obtain the same output as obtained above. Now, how did this formula worked? Let’s look at argument by argument. H1&&H2: This will be the required value of searching. As we did not use the helper column, so we have to use the concatenated result. So, we used “&” to join or concatenate the name. {1,2}: This will create a 2D array, which will store the concatenated names, and the column of AREA, from which value will be fetched. B2:B5&&C2:C5: This will concatenate the two name columns and will store them in the first column of the 2D array created by the CHOOSE function. D2:D5: This will put the values of the AREA column in the second column of the 2D array created by CHOOSE function. 2: This number signifies which column of the 2D array has to be used to fetch the value, so in our case, it is the 2nd column(AREA). 0: This signifies that the approximation of lookup is turned off. Note: If you want some separation between the concatenation, you can use any symbol, a blank space inside the “”(double quotes). Note that it should be placed in between && values, which are used for merging. So, for example, when merging H1 AND H2, but with some separation of blank space, we can write it as–>H1&” “&H2. For large datasets, the helper column is preferred over CHOOSE function for doing multiple criteria lookup with VLOOKUP. Excel-functions Picked Advanced Computer Subject Articles Excel MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Basics of API Testing Using Postman Copying Files to and from Docker Containers Getting Started with System Design Markov Decision Process Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) Time Complexity and Space Complexity
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Sep, 2021" }, { "code": null, "e": 378, "s": 28, "text": "In this article, we will see how we can combine multiple values, and use them as lookup criteria for searching specific value(s) in the excel dataset. For this purpose, we will use the VLOOKUP formula, the most basic formula to perform a lookup for value(s) on excel. We will see a modified form of VLOOKUP to perform a lookup using multiple values." }, { "code": null, "e": 415, "s": 378, "text": "First, let us see a general formula:" }, { "code": null, "e": 424, "s": 415, "text": "Formula:" }, { "code": null, "e": 462, "s": 424, "text": "=VLOOKUP(v1&v2,dataset_part,column,0)" }, { "code": null, "e": 468, "s": 462, "text": "Here," }, { "code": null, "e": 554, "s": 468, "text": "Here v1 and v2 signify those two cells, which will be used for lookup in combination." }, { "code": null, "e": 715, "s": 554, "text": "The Dataset_part signify the starting cell value and the ending cell value, upon which lookup is to be performed. This can consist of the whole dataset as well." }, { "code": null, "e": 785, "s": 715, "text": "The column signifies from which column the value has to be picked up." }, { "code": null, "e": 887, "s": 785, "text": "Here 0 signifies the approximation of lookup in vlookup. It can be set to 1 to enable approximation." }, { "code": null, "e": 1093, "s": 887, "text": "Now, let us see in brief, or a summary, how VLOOKUP will work in the Multiple Criteria Column. Here, we have 2 ways of modifying VLOOKUP to make it capable of doing a lookup on multiple criteria, they are:" }, { "code": null, "e": 1124, "s": 1093, "text": "Helper Column.CHOOSE function." }, { "code": null, "e": 1139, "s": 1124, "text": "Helper Column." }, { "code": null, "e": 1156, "s": 1139, "text": "CHOOSE function." }, { "code": null, "e": 1534, "s": 1156, "text": "Helper column will be a sort of redundant work, as we have to provide merged values of those columns on which VLOOKUP is doing the lookup, or we can use concatenation to concat the columns values. It should be kept in mind that the helper column should be the first column of our data. The CHOOSE function is usually preferred over creating a helper column in smaller datasets." }, { "code": null, "e": 1575, "s": 1534, "text": "Now, let us see an example in both ways." }, { "code": null, "e": 2118, "s": 1575, "text": "Now, let’s suppose we have this dataset with us. On the left side, the main dataset is written, and on the right side, a record has to be taken out from the main database. Now, you can either use CONCATENATE function, or you can manually write the merged values of your criteria columns in the helper column. Here, we want to know the area of study of RIZWAN AHMAD. But, we don’t know any other method than VLOOKUP to perform this. So, we will use VLOOKUP to achieve this. First, let us see the formula and understand it argument by argument." }, { "code": null, "e": 2144, "s": 2118, "text": "=VLOOKUP(H1&H2,A2:D5,4,0)" }, { "code": null, "e": 2172, "s": 2144, "text": "The output of this will be:" }, { "code": null, "e": 2236, "s": 2172, "text": "Now, we achieved the correct result, but how? Let’s look at it." }, { "code": null, "e": 2320, "s": 2236, "text": "H1&H2: The name is divided into 2 cells, which have been taken from criteria cells." }, { "code": null, "e": 2362, "s": 2320, "text": "A2:D5: The data is taken from this range." }, { "code": null, "e": 2451, "s": 2362, "text": "4: This is the column number from which data will be retrieved,i.e from the AREA column." }, { "code": null, "e": 2517, "s": 2451, "text": "0: This signifies that the approximation of lookup is turned off." }, { "code": null, "e": 2636, "s": 2517, "text": "Here, the thing to keep in mind is that the helper column should always be created on the first column of the dataset." }, { "code": null, "e": 2810, "s": 2636, "text": "Now, as discussed the helper column is not very much suited for smaller datasets. So, we will use CHOOSE function along with VLOOKUP to achieve the multiple criteria lookup." }, { "code": null, "e": 3071, "s": 2810, "text": "Now, let’s suppose the given dataset is big, and we want to know the area of study of RIZWAN AHMAD, so for this, we will use CHOOSE function, which will help us create a 2D array, in which the search criteria values and other arguments will be stored and used." }, { "code": null, "e": 3118, "s": 3071, "text": "Considering this dataset, the formula will be:" }, { "code": null, "e": 3172, "s": 3118, "text": "=VLOOKUP(H1&&H2,CHOOSE({1,2},B2:B5&&C2:C5,D2:D5),2,0)" }, { "code": null, "e": 3322, "s": 3172, "text": "Inserting this formula in H3, we will obtain the same output as obtained above. Now, how did this formula worked? Let’s look at argument by argument." }, { "code": null, "e": 3505, "s": 3322, "text": "H1&&H2: This will be the required value of searching. As we did not use the helper column, so we have to use the concatenated result. So, we used “&” to join or concatenate the name." }, { "code": null, "e": 3640, "s": 3505, "text": "{1,2}: This will create a 2D array, which will store the concatenated names, and the column of AREA, from which value will be fetched." }, { "code": null, "e": 3785, "s": 3640, "text": "B2:B5&&C2:C5: This will concatenate the two name columns and will store them in the first column of the 2D array created by the CHOOSE function." }, { "code": null, "e": 3901, "s": 3785, "text": "D2:D5: This will put the values of the AREA column in the second column of the 2D array created by CHOOSE function." }, { "code": null, "e": 4034, "s": 3901, "text": "2: This number signifies which column of the 2D array has to be used to fetch the value, so in our case, it is the 2nd column(AREA)." }, { "code": null, "e": 4100, "s": 4034, "text": "0: This signifies that the approximation of lookup is turned off." }, { "code": null, "e": 4422, "s": 4100, "text": "Note: If you want some separation between the concatenation, you can use any symbol, a blank space inside the “”(double quotes). Note that it should be placed in between && values, which are used for merging. So, for example, when merging H1 AND H2, but with some separation of blank space, we can write it as–>H1&” “&H2." }, { "code": null, "e": 4543, "s": 4422, "text": "For large datasets, the helper column is preferred over CHOOSE function for doing multiple criteria lookup with VLOOKUP." }, { "code": null, "e": 4559, "s": 4543, "text": "Excel-functions" }, { "code": null, "e": 4566, "s": 4559, "text": "Picked" }, { "code": null, "e": 4592, "s": 4566, "text": "Advanced Computer Subject" }, { "code": null, "e": 4601, "s": 4592, "text": "Articles" }, { "code": null, "e": 4607, "s": 4601, "text": "Excel" }, { "code": null, "e": 4611, "s": 4607, "text": "MCQ" }, { "code": null, "e": 4709, "s": 4611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4745, "s": 4709, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 4781, "s": 4745, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 4825, "s": 4781, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 4860, "s": 4825, "text": "Getting Started with System Design" }, { "code": null, "e": 4884, "s": 4860, "text": "Markov Decision Process" }, { "code": null, "e": 4934, "s": 4884, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 4981, "s": 4934, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 5017, "s": 4981, "text": "find command in Linux with examples" }, { "code": null, "e": 5070, "s": 5017, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" } ]
Paper Cut into Minimum Number of Squares
22 Jun, 2022 Given a paper of size, A x B. Task is to cut the paper into squares of any size. Find the minimum number of squares that can be cut from the paper. Examples: Input : 13 x 29 Output : 9 Explanation : 2 (squares of size 13x13) + 4 (squares of size 3x3) + 3 (squares of size 1x1)=9 Input : 4 x 5 Output : 5 Explanation : 1 (squares of size 4x4) + 4 (squares of size 1x1) We know that if we want to cut a minimum number of squares from the paper then we would have to cut the largest square possible from the paper first and the largest square will have the same side as the smaller side of the paper. For example, if the paper has the size 13 x 29, then the maximum square will be of side 13. so we can cut 2 square of size 13 x 13 (29/13 = 2). Now remaining paper will have size 3 x 13. Similarly, we can cut the remaining paper by using 4 squares of size 3 x 3 and 3 squares of 1 x 1. So a minimum of 9 squares can be cut from the Paper of size 13 x 29. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to find minimum number of squares// to cut a paper.#include<bits/stdc++.h>using namespace std; // Returns min number of squares neededint minimumSquare(int a, int b){ long long result = 0, rem = 0; // swap if a is small size side . if (a < b) swap(a, b); // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += a/b; long long rem = a % b; a = b; b = rem; } return result;} // Driver codeint main(){ int n = 13, m = 29; cout << minimumSquare(n, m); return 0;} // Java program to find minimum// number of squares to cut a paper.class GFG{ // To swap two numbersstatic void swap(int a,int b){ int temp = a; a = b; b = temp;} // Returns min number of squares neededstatic int minimumSquare(int a, int b){ int result = 0, rem = 0; // swap if a is small size side . if (a < b) swap(a, b); // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += a/b; rem = a % b; a = b; b = rem; } return result;} // Driver codepublic static void main(String[] args){ int n = 13, m = 29; System.out.println(minimumSquare(n, m));}} //This code is contributed by Smitha Dinesh Semwal. # Python 3 program to find minimum# number of squares to cut a paper. # Returns min number of squares neededdef minimumSquare(a, b): result = 0 rem = 0 # swap if a is small size side . if (a < b): a, b = b, a # Iterate until small size side is # greater then 0 while (b > 0): # Update result result += int(a / b) rem = int(a % b) a = b b = rem return result # Driver coden = 13m = 29 print(minimumSquare(n, m)) # This code is contributed by# Smitha Dinesh Semwal // C# program to find minimum// number of squares to cut a paper.using System; class GFG{ // To swap two numbersstatic void swap(int a, int b){ int temp = a; a = b; b = temp;} // Returns min number of squares neededstatic int minimumSquare(int a, int b){ int result = 0, rem = 0; // swap if a is small size side . if (a < b) swap(a, b); // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += a / b; rem = a % b; a = b; b = rem; } return result;} // Driver codepublic static void Main(String[] args){ int n = 13, m = 29; Console.WriteLine(minimumSquare(n, m));}} // This code is contributed by 29AjayKumar <script> // Javascript program to find// minimum number of squares// to cut a paper. // Returns min number of squares neededfunction minimumSquare(a, b){ let result = 0, rem = 0; // swap if a is small size side . if (a < b) { let temp = a; a = b; b = temp; } // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += parseInt(a/b); let rem = a % b; a = b; b = rem; } return result;} // Driver code let n = 13, m = 29; document.write(minimumSquare(n, m)); </script> Output: 9 Time Complexity: O(log(max(a,b))) Auxiliary Space: O(1) Note that the above Greedy solution doesn’t always produce an optimal result. For example, if the input is 36 x 30, the above algorithm would produce output 6, but we can cut the paper into 5 squares 1) Three squares of size 12 x 12 2) Two squares of size 18 x 18. Thanks to Sergey V. Pereslavtsev for pointing out the above case.This article is contributed by Aarti_Rathi and Kuldeep Singh(kulli_d_coder). 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. 29AjayKumar rishavmahato348 codewithrathi Combinatorial Geometric Greedy Mathematical Greedy Mathematical Combinatorial Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number Count of subsets with sum equal to X Combinational Sum Program for distance between two points on earth Find if two rectangles overlap Check whether triangle is valid or not if sides are given Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Program for Point of Intersection of Two Lines
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 214, "s": 54, "text": "Given a paper of size, A x B. Task is to cut the paper into squares of any size. Find the minimum number of squares that can be cut from the paper. Examples: " }, { "code": null, "e": 432, "s": 214, "text": "Input : 13 x 29\nOutput : 9\nExplanation : \n2 (squares of size 13x13) + \n4 (squares of size 3x3) + \n3 (squares of size 1x1)=9\n\nInput : 4 x 5\nOutput : 5\nExplanation : \n1 (squares of size 4x4) + \n4 (squares of size 1x1)" }, { "code": null, "e": 1020, "s": 434, "text": "We know that if we want to cut a minimum number of squares from the paper then we would have to cut the largest square possible from the paper first and the largest square will have the same side as the smaller side of the paper. For example, if the paper has the size 13 x 29, then the maximum square will be of side 13. so we can cut 2 square of size 13 x 13 (29/13 = 2). Now remaining paper will have size 3 x 13. Similarly, we can cut the remaining paper by using 4 squares of size 3 x 3 and 3 squares of 1 x 1. So a minimum of 9 squares can be cut from the Paper of size 13 x 29. " }, { "code": null, "e": 1073, "s": 1020, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 1077, "s": 1073, "text": "C++" }, { "code": null, "e": 1082, "s": 1077, "text": "Java" }, { "code": null, "e": 1090, "s": 1082, "text": "Python3" }, { "code": null, "e": 1093, "s": 1090, "text": "C#" }, { "code": null, "e": 1104, "s": 1093, "text": "Javascript" }, { "code": "// C++ program to find minimum number of squares// to cut a paper.#include<bits/stdc++.h>using namespace std; // Returns min number of squares neededint minimumSquare(int a, int b){ long long result = 0, rem = 0; // swap if a is small size side . if (a < b) swap(a, b); // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += a/b; long long rem = a % b; a = b; b = rem; } return result;} // Driver codeint main(){ int n = 13, m = 29; cout << minimumSquare(n, m); return 0;}", "e": 1701, "s": 1104, "text": null }, { "code": "// Java program to find minimum// number of squares to cut a paper.class GFG{ // To swap two numbersstatic void swap(int a,int b){ int temp = a; a = b; b = temp;} // Returns min number of squares neededstatic int minimumSquare(int a, int b){ int result = 0, rem = 0; // swap if a is small size side . if (a < b) swap(a, b); // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += a/b; rem = a % b; a = b; b = rem; } return result;} // Driver codepublic static void main(String[] args){ int n = 13, m = 29; System.out.println(minimumSquare(n, m));}} //This code is contributed by Smitha Dinesh Semwal.", "e": 2434, "s": 1701, "text": null }, { "code": "# Python 3 program to find minimum# number of squares to cut a paper. # Returns min number of squares neededdef minimumSquare(a, b): result = 0 rem = 0 # swap if a is small size side . if (a < b): a, b = b, a # Iterate until small size side is # greater then 0 while (b > 0): # Update result result += int(a / b) rem = int(a % b) a = b b = rem return result # Driver coden = 13m = 29 print(minimumSquare(n, m)) # This code is contributed by# Smitha Dinesh Semwal", "e": 2973, "s": 2434, "text": null }, { "code": "// C# program to find minimum// number of squares to cut a paper.using System; class GFG{ // To swap two numbersstatic void swap(int a, int b){ int temp = a; a = b; b = temp;} // Returns min number of squares neededstatic int minimumSquare(int a, int b){ int result = 0, rem = 0; // swap if a is small size side . if (a < b) swap(a, b); // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += a / b; rem = a % b; a = b; b = rem; } return result;} // Driver codepublic static void Main(String[] args){ int n = 13, m = 29; Console.WriteLine(minimumSquare(n, m));}} // This code is contributed by 29AjayKumar", "e": 3714, "s": 2973, "text": null }, { "code": "<script> // Javascript program to find// minimum number of squares// to cut a paper. // Returns min number of squares neededfunction minimumSquare(a, b){ let result = 0, rem = 0; // swap if a is small size side . if (a < b) { let temp = a; a = b; b = temp; } // Iterate until small size side is // greater then 0 while (b > 0) { // Update result result += parseInt(a/b); let rem = a % b; a = b; b = rem; } return result;} // Driver code let n = 13, m = 29; document.write(minimumSquare(n, m)); </script>", "e": 4314, "s": 3714, "text": null }, { "code": null, "e": 4323, "s": 4314, "text": "Output: " }, { "code": null, "e": 4325, "s": 4323, "text": "9" }, { "code": null, "e": 4381, "s": 4325, "text": "Time Complexity: O(log(max(a,b))) Auxiliary Space: O(1)" }, { "code": null, "e": 4646, "s": 4381, "text": "Note that the above Greedy solution doesn’t always produce an optimal result. For example, if the input is 36 x 30, the above algorithm would produce output 6, but we can cut the paper into 5 squares 1) Three squares of size 12 x 12 2) Two squares of size 18 x 18." }, { "code": null, "e": 5039, "s": 4646, "text": "Thanks to Sergey V. Pereslavtsev for pointing out the above case.This article is contributed by Aarti_Rathi and Kuldeep Singh(kulli_d_coder). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5165, "s": 5039, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5177, "s": 5165, "text": "29AjayKumar" }, { "code": null, "e": 5193, "s": 5177, "text": "rishavmahato348" }, { "code": null, "e": 5207, "s": 5193, "text": "codewithrathi" }, { "code": null, "e": 5221, "s": 5207, "text": "Combinatorial" }, { "code": null, "e": 5231, "s": 5221, "text": "Geometric" }, { "code": null, "e": 5238, "s": 5231, "text": "Greedy" }, { "code": null, "e": 5251, "s": 5238, "text": "Mathematical" }, { "code": null, "e": 5258, "s": 5251, "text": "Greedy" }, { "code": null, "e": 5271, "s": 5258, "text": "Mathematical" }, { "code": null, "e": 5285, "s": 5271, "text": "Combinatorial" }, { "code": null, "e": 5295, "s": 5285, "text": "Geometric" }, { "code": null, "e": 5393, "s": 5295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5453, "s": 5393, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5491, "s": 5453, "text": "Permutation and Combination in Python" }, { "code": null, "e": 5519, "s": 5491, "text": "Factorial of a large number" }, { "code": null, "e": 5556, "s": 5519, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 5574, "s": 5556, "text": "Combinational Sum" }, { "code": null, "e": 5623, "s": 5574, "text": "Program for distance between two points on earth" }, { "code": null, "e": 5654, "s": 5623, "text": "Find if two rectangles overlap" }, { "code": null, "e": 5712, "s": 5654, "text": "Check whether triangle is valid or not if sides are given" }, { "code": null, "e": 5763, "s": 5712, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" } ]
LocalDate of() method in Java with Examples
21 May, 2020 The of(int, int, int) method of LocalDate class in Java is used to create an instance of LocalDate from the input year, month and day of the month. In this method, all the three parameters are passed in the form of integer.Syntax:public static LocalDate of(int year, int month, int dayOfMonth) Parameters: This method accepts three parameters:year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of integer type and represents the month of the year. It varies from 1(JANUARY) to 12(DECEMBER).dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or if the day-of-month is invalid for the month-year.Below programs illustrate the of(int month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print full date System.out.println("Date: " + localdate); }}Output:Date: 2020-05-13 Program 2:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print year only System.out.println("Year: " + localdate.getYear()); }}Output:Year: 2020 The of(int, Month, int) method of LocalDate class in Java is used to obtain an instance of LocalDate from the input year, month and day. In this method, the parameters year and day are passed as integers but the month is passes as an instance.Syntax:public static LocalDate of(int year, Month month, int dayOfMonth) Parameters: This method accepts three parameters.year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of Month type and represents the month of the year. It varies from JANUARY to DECEMBER.dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or the day-of-month is invalid for the month-year.Below programs illustrate the of(Month month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print full date System.out.println("Date: " + localdate); }}Output:Date: 2020-05-13 Program 2:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print month only System.out.println("Month: " + localdate.getMonth()); }}Output:Month: MAY The of(int, int, int) method of LocalDate class in Java is used to create an instance of LocalDate from the input year, month and day of the month. In this method, all the three parameters are passed in the form of integer.Syntax:public static LocalDate of(int year, int month, int dayOfMonth) Parameters: This method accepts three parameters:year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of integer type and represents the month of the year. It varies from 1(JANUARY) to 12(DECEMBER).dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or if the day-of-month is invalid for the month-year.Below programs illustrate the of(int month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print full date System.out.println("Date: " + localdate); }}Output:Date: 2020-05-13 Program 2:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print year only System.out.println("Year: " + localdate.getYear()); }}Output:Year: 2020 Syntax: public static LocalDate of(int year, int month, int dayOfMonth) Parameters: This method accepts three parameters: year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR. month – It is of integer type and represents the month of the year. It varies from 1(JANUARY) to 12(DECEMBER). dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31. Return Value: This method returns the localdate. Exceptions: This method throws DateTimeException if any field value is out of range or if the day-of-month is invalid for the month-year. Below programs illustrate the of(int month) method in Java:Program 1: // Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print full date System.out.println("Date: " + localdate); }} Date: 2020-05-13 Program 2: // Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print year only System.out.println("Year: " + localdate.getYear()); }} Year: 2020 The of(int, Month, int) method of LocalDate class in Java is used to obtain an instance of LocalDate from the input year, month and day. In this method, the parameters year and day are passed as integers but the month is passes as an instance.Syntax:public static LocalDate of(int year, Month month, int dayOfMonth) Parameters: This method accepts three parameters.year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of Month type and represents the month of the year. It varies from JANUARY to DECEMBER.dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or the day-of-month is invalid for the month-year.Below programs illustrate the of(Month month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print full date System.out.println("Date: " + localdate); }}Output:Date: 2020-05-13 Program 2:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print month only System.out.println("Month: " + localdate.getMonth()); }}Output:Month: MAY Syntax: public static LocalDate of(int year, Month month, int dayOfMonth) Parameters: This method accepts three parameters. year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR. month – It is of Month type and represents the month of the year. It varies from JANUARY to DECEMBER. dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31. Return Value: This method returns the localdate. Exceptions: This method throws DateTimeException if any field value is out of range or the day-of-month is invalid for the month-year. Below programs illustrate the of(Month month) method in Java:Program 1: // Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print full date System.out.println("Date: " + localdate); }} Date: 2020-05-13 Program 2: // Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print month only System.out.println("Month: " + localdate.getMonth()); }} Month: MAY References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, int, int)https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, java.time.Month, int) https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, int, int) https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, java.time.Month, int) Java-Functions Java-LocalDate Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2020" }, { "code": null, "e": 3612, "s": 28, "text": "The of(int, int, int) method of LocalDate class in Java is used to create an instance of LocalDate from the input year, month and day of the month. In this method, all the three parameters are passed in the form of integer.Syntax:public static LocalDate of(int year,\n int month,\n int dayOfMonth)\nParameters: This method accepts three parameters:year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of integer type and represents the month of the year. It varies from 1(JANUARY) to 12(DECEMBER).dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or if the day-of-month is invalid for the month-year.Below programs illustrate the of(int month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print full date System.out.println(\"Date: \" + localdate); }}Output:Date: 2020-05-13\nProgram 2:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print year only System.out.println(\"Year: \" + localdate.getYear()); }}Output:Year: 2020\nThe of(int, Month, int) method of LocalDate class in Java is used to obtain an instance of LocalDate from the input year, month and day. In this method, the parameters year and day are passed as integers but the month is passes as an instance.Syntax:public static LocalDate of(int year,\n Month month,\n int dayOfMonth)\nParameters: This method accepts three parameters.year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of Month type and represents the month of the year. It varies from JANUARY to DECEMBER.dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or the day-of-month is invalid for the month-year.Below programs illustrate the of(Month month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print full date System.out.println(\"Date: \" + localdate); }}Output:Date: 2020-05-13\nProgram 2:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print month only System.out.println(\"Month: \" + localdate.getMonth()); }}Output:Month: MAY\n" }, { "code": null, "e": 5373, "s": 3612, "text": "The of(int, int, int) method of LocalDate class in Java is used to create an instance of LocalDate from the input year, month and day of the month. In this method, all the three parameters are passed in the form of integer.Syntax:public static LocalDate of(int year,\n int month,\n int dayOfMonth)\nParameters: This method accepts three parameters:year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of integer type and represents the month of the year. It varies from 1(JANUARY) to 12(DECEMBER).dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or if the day-of-month is invalid for the month-year.Below programs illustrate the of(int month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print full date System.out.println(\"Date: \" + localdate); }}Output:Date: 2020-05-13\nProgram 2:// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print year only System.out.println(\"Year: \" + localdate.getYear()); }}Output:Year: 2020\n" }, { "code": null, "e": 5381, "s": 5373, "text": "Syntax:" }, { "code": null, "e": 5500, "s": 5381, "text": "public static LocalDate of(int year,\n int month,\n int dayOfMonth)\n" }, { "code": null, "e": 5550, "s": 5500, "text": "Parameters: This method accepts three parameters:" }, { "code": null, "e": 5641, "s": 5550, "text": "year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR." }, { "code": null, "e": 5752, "s": 5641, "text": "month – It is of integer type and represents the month of the year. It varies from 1(JANUARY) to 12(DECEMBER)." }, { "code": null, "e": 5848, "s": 5752, "text": "dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31." }, { "code": null, "e": 5897, "s": 5848, "text": "Return Value: This method returns the localdate." }, { "code": null, "e": 6035, "s": 5897, "text": "Exceptions: This method throws DateTimeException if any field value is out of range or if the day-of-month is invalid for the month-year." }, { "code": null, "e": 6105, "s": 6035, "text": "Below programs illustrate the of(int month) method in Java:Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print full date System.out.println(\"Date: \" + localdate); }}", "e": 6469, "s": 6105, "text": null }, { "code": null, "e": 6487, "s": 6469, "text": "Date: 2020-05-13\n" }, { "code": null, "e": 6498, "s": 6487, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalDate.of(int month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of(2020, 5, 13); // print year only System.out.println(\"Year: \" + localdate.getYear()); }}", "e": 6898, "s": 6498, "text": null }, { "code": null, "e": 6910, "s": 6898, "text": "Year: 2020\n" }, { "code": null, "e": 8734, "s": 6910, "text": "The of(int, Month, int) method of LocalDate class in Java is used to obtain an instance of LocalDate from the input year, month and day. In this method, the parameters year and day are passed as integers but the month is passes as an instance.Syntax:public static LocalDate of(int year,\n Month month,\n int dayOfMonth)\nParameters: This method accepts three parameters.year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR.month – It is of Month type and represents the month of the year. It varies from JANUARY to DECEMBER.dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31.Return Value: This method returns the localdate.Exceptions: This method throws DateTimeException if any field value is out of range or the day-of-month is invalid for the month-year.Below programs illustrate the of(Month month) method in Java:Program 1:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print full date System.out.println(\"Date: \" + localdate); }}Output:Date: 2020-05-13\nProgram 2:// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print month only System.out.println(\"Month: \" + localdate.getMonth()); }}Output:Month: MAY\n" }, { "code": null, "e": 8742, "s": 8734, "text": "Syntax:" }, { "code": null, "e": 8863, "s": 8742, "text": "public static LocalDate of(int year,\n Month month,\n int dayOfMonth)\n" }, { "code": null, "e": 8913, "s": 8863, "text": "Parameters: This method accepts three parameters." }, { "code": null, "e": 9004, "s": 8913, "text": "year – It is of integer type and represents the year. It varies from MIN_YEAR to MAX_YEAR." }, { "code": null, "e": 9106, "s": 9004, "text": "month – It is of Month type and represents the month of the year. It varies from JANUARY to DECEMBER." }, { "code": null, "e": 9202, "s": 9106, "text": "dayOfMonth – It is of integer type and represents the day of the month. It varies from 1 to 31." }, { "code": null, "e": 9251, "s": 9202, "text": "Return Value: This method returns the localdate." }, { "code": null, "e": 9386, "s": 9251, "text": "Exceptions: This method throws DateTimeException if any field value is out of range or the day-of-month is invalid for the month-year." }, { "code": null, "e": 9458, "s": 9386, "text": "Below programs illustrate the of(Month month) method in Java:Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print full date System.out.println(\"Date: \" + localdate); }}", "e": 9859, "s": 9458, "text": null }, { "code": null, "e": 9877, "s": 9859, "text": "Date: 2020-05-13\n" }, { "code": null, "e": 9888, "s": 9877, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalDate.of(Month month) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create LocalDate object LocalDate localdate = LocalDate.of( 2020, Month.MAY, 13); // print month only System.out.println(\"Month: \" + localdate.getMonth()); }}", "e": 10302, "s": 9888, "text": null }, { "code": null, "e": 10314, "s": 10302, "text": "Month: MAY\n" }, { "code": null, "e": 10326, "s": 10314, "text": "References:" }, { "code": null, "e": 10509, "s": 10326, "text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, int, int)https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, java.time.Month, int)" }, { "code": null, "e": 10595, "s": 10509, "text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, int, int)" }, { "code": null, "e": 10693, "s": 10595, "text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#of(int, java.time.Month, int)" }, { "code": null, "e": 10708, "s": 10693, "text": "Java-Functions" }, { "code": null, "e": 10723, "s": 10708, "text": "Java-LocalDate" }, { "code": null, "e": 10728, "s": 10723, "text": "Java" }, { "code": null, "e": 10733, "s": 10728, "text": "Java" }, { "code": null, "e": 10831, "s": 10733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10862, "s": 10831, "text": "How to iterate any Map in Java" }, { "code": null, "e": 10881, "s": 10862, "text": "Interfaces in Java" }, { "code": null, "e": 10911, "s": 10881, "text": "HashMap in Java with Examples" }, { "code": null, "e": 10929, "s": 10911, "text": "ArrayList in Java" }, { "code": null, "e": 10944, "s": 10929, "text": "Stream In Java" }, { "code": null, "e": 10964, "s": 10944, "text": "Collections in Java" }, { "code": null, "e": 10996, "s": 10964, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 11020, "s": 10996, "text": "Singleton Class in Java" }, { "code": null, "e": 11040, "s": 11020, "text": "Stack Class in Java" } ]
Template Specialization in C++
12 Jun, 2022 Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type. What if we want a different code for a particular data type? Consider a big project that needs a function sort() for arrays of many different data types. Let Quick Sort be used for all datatypes except char. In case of char, total possible values are 256 and counting sort may be a better option. Is it possible to use different code only when sort() is called for char data type? It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming. Generic programming is an approach where generic data types are used as parameters in algorithms so that they work for variety of suitable data types.Templates are sometimes called parameterized classes or functions. C++ // Eg: Let us recall the concept of function overloading #include<iostream>using namespace std; void show(int,int);void show(double,double);void show(char,char); main(){ show(2,5); show(2.6,7.6); return 0;} void show(int a,int b){ cout<<"a="<<a<<endl; cout<<"b="<<b<<endl;} void show(double a,double b){ cout<<"a="<<a<<endl; cout<<"b="<<b<<endl;} a=2 b=5 a=2.6 b=7.6 But a careful observation of overloaded functions as in our program will show us the disadvantage of overloaded function. That is, each overloaded function definition does identical tasks. But the only change/difference with the overloaded function is that, they are handling arguments of different data types to do identical tasks. This is a disadvantage because, the data types of function arguments are different, we are writing separate code for function definition for performing the same task.This is one kind of disadvantage and this disadvantage is overcome by a new concept called “FUNCTION TEMPLATE”. CPP // A generic sort functiontemplate <class T>void sort(T arr[], int size){ // code to implement Quick Sort} // Template Specialization: A function// specialized for char data typetemplate <>void sort<char>(char arr[], int size){ // code to implement counting sort} Another example could be a class Set that represents a set of elements and supports operations like union, intersection, etc. When the type of elements is char, we may want to use a simple boolean array of size 256 to make a set. For other data types, we have to use some other complex technique. Function templates allow the programmer to write a generic function which is independent of data type.Using function templates we can reduces the size of the code and makes the maintenance code easy. Syntax: template <class T> <return-type> <function-name> ( <parameters of type T> ) { //function body } Where template ------ keyword class T ------ template type parameter enclosed within a pair of angle brackets(< >) called generic dt. C++ // Example: #include<iostream>using namespace std; template<class T>void show(T a,T b){ cout<<"a="<<a<<endl; cout<<"b="<<b<<endl;} main(){ show(2,5); show(2.6,7.6); return 0;} a=2 b=5 a=2.6 b=7.6 C++ // Create a function template that prints the maximum of two values. #include<iostream>using namespace std; template<class T>void getMax(T a,T b){ T result; result=(a>b)?a:b; cout<<endl<<"Maximum:"<<result;} main(){ getMax(2,5); getMax(2.6,7.6); getMax('A','D'); return 0;} Maximum:5 Maximum:7.6 Maximum:D C++ // Example: #include<iostream>using namespace std; template<class T>T getMax(T a,T b){ T result; result=(a>b)?a:b; return result;} main(){ int a=getMax(2,5); double d=getMax(2.6,7.6); cout<<endl<<a; cout<<endl<<d; return 0;} 5 7.6 C++ // create a function template that prints the swap of two numbers. #include<iostream>using namespace std; template<class T>void swapp(T &a,T &b){ T temp; temp=a; a=b; b=temp;} main(){ int a=10,b=20; double x=20.3,y=55.3; cout<<endl<<"Before Swap"<<endl; cout<<endl<<"A="<<a<<"\t"<<"B="<<b; cout<<endl<<"X="<<x<<"\t"<<"B="<<y; swapp(a,b); swapp(x,y); cout<<endl<<endl<<"After Swap"<<endl; cout<<endl<<"A="<<a<<"\t"<<"B="<<b; cout<<endl<<"X="<<x<<"\t"<<"B="<<y; return 0;} Before Swap A=10 B=20 X=20.3 B=55.3 After Swap A=20 B=10 X=55.3 B=20.3 Note: Apart from built-in data types like int, double, char etc, the template parameter ‘T’ can also be replaced by user defined data type. An Example Program for function template specialization For example, consider the following simple code where we have general template fun() for all data types except int. For int, there is a specialized version of fun(). CPP #include <iostream>using namespace std; template <class T>void fun(T a){ cout << "The main template fun(): " << a << endl;} template<>void fun(int a){ cout << "Specialized Template for int type: " << a << endl;} int main(){ fun<char>('a'); fun<int>(10); fun<float>(10.14);} The main template fun(): a Specialized Template for int type: 10 The main template fun(): 10.14 An Example Program for class template specialization In the following program, a specialized version of class Test is written for int data type. CPP #include <iostream>using namespace std; template <class T>class Test{ // Data members of testpublic: Test() { // Initialization of data members cout << "General template object \n"; } // Other methods of Test}; template <>class Test <int>{public: Test() { // Initialization of data members cout << "Specialized template object\n"; }}; int main(){ Test<int> a; Test<char> b; Test<float> c; return 0;} Specialized template object General template object General template object How does template specialization work? When we write any template based function or class, compiler creates a copy of that function/class whenever compiler sees that being used for a new data type or new set of data types(in case of multiple template arguments). If a specialized version is present, compiler first checks with the specialized version and then the main template. Compiler first checks with the most specialized version by matching the passed parameter with the data type(s) specified in a specialized version. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ashwinanil aditiyadav20102001 cpp-template C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jun, 2022" }, { "code": null, "e": 810, "s": 52, "text": "Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type. What if we want a different code for a particular data type? Consider a big project that needs a function sort() for arrays of many different data types. Let Quick Sort be used for all datatypes except char. In case of char, total possible values are 256 and counting sort may be a better option. Is it possible to use different code only when sort() is called for char data type? It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. " }, { "code": null, "e": 1144, "s": 810, "text": "Template allows us to define generic classes and generic functions and thus provide support for generic programming. Generic programming is an approach where generic data types are used as parameters in algorithms so that they work for variety of suitable data types.Templates are sometimes called parameterized classes or functions." }, { "code": null, "e": 1148, "s": 1144, "text": "C++" }, { "code": "// Eg: Let us recall the concept of function overloading #include<iostream>using namespace std; void show(int,int);void show(double,double);void show(char,char); main(){ show(2,5); show(2.6,7.6); return 0;} void show(int a,int b){ cout<<\"a=\"<<a<<endl; cout<<\"b=\"<<b<<endl;} void show(double a,double b){ cout<<\"a=\"<<a<<endl; cout<<\"b=\"<<b<<endl;}", "e": 1516, "s": 1148, "text": null }, { "code": null, "e": 1536, "s": 1516, "text": "a=2\nb=5\na=2.6\nb=7.6" }, { "code": null, "e": 2149, "s": 1536, "text": "But a careful observation of overloaded functions as in our program will show us the disadvantage of overloaded function. That is, each overloaded function definition does identical tasks. But the only change/difference with the overloaded function is that, they are handling arguments of different data types to do identical tasks. This is a disadvantage because, the data types of function arguments are different, we are writing separate code for function definition for performing the same task.This is one kind of disadvantage and this disadvantage is overcome by a new concept called “FUNCTION TEMPLATE”. " }, { "code": null, "e": 2153, "s": 2149, "text": "CPP" }, { "code": "// A generic sort functiontemplate <class T>void sort(T arr[], int size){ // code to implement Quick Sort} // Template Specialization: A function// specialized for char data typetemplate <>void sort<char>(char arr[], int size){ // code to implement counting sort}", "e": 2423, "s": 2153, "text": null }, { "code": null, "e": 2720, "s": 2423, "text": "Another example could be a class Set that represents a set of elements and supports operations like union, intersection, etc. When the type of elements is char, we may want to use a simple boolean array of size 256 to make a set. For other data types, we have to use some other complex technique." }, { "code": null, "e": 2921, "s": 2720, "text": "Function templates allow the programmer to write a generic function which is independent of data type.Using function templates we can reduces the size of the code and makes the maintenance code easy. " }, { "code": null, "e": 2929, "s": 2921, "text": "Syntax:" }, { "code": null, "e": 3189, "s": 2929, "text": "template <class T>\n<return-type> <function-name> ( <parameters of type T> )\n{\n //function body\n}\nWhere\ntemplate ------ keyword\nclass T ------ template type parameter enclosed within a pair of angle brackets(< >) called generic dt." }, { "code": null, "e": 3193, "s": 3189, "text": "C++" }, { "code": "// Example: #include<iostream>using namespace std; template<class T>void show(T a,T b){ cout<<\"a=\"<<a<<endl; cout<<\"b=\"<<b<<endl;} main(){ show(2,5); show(2.6,7.6); return 0;}", "e": 3384, "s": 3193, "text": null }, { "code": null, "e": 3404, "s": 3384, "text": "a=2\nb=5\na=2.6\nb=7.6" }, { "code": null, "e": 3408, "s": 3404, "text": "C++" }, { "code": "// Create a function template that prints the maximum of two values. #include<iostream>using namespace std; template<class T>void getMax(T a,T b){ T result; result=(a>b)?a:b; cout<<endl<<\"Maximum:\"<<result;} main(){ getMax(2,5); getMax(2.6,7.6); getMax('A','D'); return 0;}", "e": 3703, "s": 3408, "text": null }, { "code": null, "e": 3735, "s": 3703, "text": "Maximum:5\nMaximum:7.6\nMaximum:D" }, { "code": null, "e": 3741, "s": 3737, "text": "C++" }, { "code": "// Example: #include<iostream>using namespace std; template<class T>T getMax(T a,T b){ T result; result=(a>b)?a:b; return result;} main(){ int a=getMax(2,5); double d=getMax(2.6,7.6); cout<<endl<<a; cout<<endl<<d; return 0;}", "e": 3982, "s": 3741, "text": null }, { "code": null, "e": 3988, "s": 3982, "text": "5\n7.6" }, { "code": null, "e": 3992, "s": 3988, "text": "C++" }, { "code": "// create a function template that prints the swap of two numbers. #include<iostream>using namespace std; template<class T>void swapp(T &a,T &b){ T temp; temp=a; a=b; b=temp;} main(){ int a=10,b=20; double x=20.3,y=55.3; cout<<endl<<\"Before Swap\"<<endl; cout<<endl<<\"A=\"<<a<<\"\\t\"<<\"B=\"<<b; cout<<endl<<\"X=\"<<x<<\"\\t\"<<\"B=\"<<y; swapp(a,b); swapp(x,y); cout<<endl<<endl<<\"After Swap\"<<endl; cout<<endl<<\"A=\"<<a<<\"\\t\"<<\"B=\"<<b; cout<<endl<<\"X=\"<<x<<\"\\t\"<<\"B=\"<<y; return 0;}", "e": 4502, "s": 3992, "text": null }, { "code": null, "e": 4588, "s": 4502, "text": "Before Swap\n\nA=10 B=20\nX=20.3 B=55.3\n\nAfter Swap\n\nA=20 B=10\nX=55.3 B=20.3" }, { "code": null, "e": 4729, "s": 4588, "text": "Note: Apart from built-in data types like int, double, char etc, the template parameter ‘T’ can also be replaced by user defined data type." }, { "code": null, "e": 4953, "s": 4729, "text": "An Example Program for function template specialization For example, consider the following simple code where we have general template fun() for all data types except int. For int, there is a specialized version of fun(). " }, { "code": null, "e": 4957, "s": 4953, "text": "CPP" }, { "code": "#include <iostream>using namespace std; template <class T>void fun(T a){ cout << \"The main template fun(): \" << a << endl;} template<>void fun(int a){ cout << \"Specialized Template for int type: \" << a << endl;} int main(){ fun<char>('a'); fun<int>(10); fun<float>(10.14);}", "e": 5260, "s": 4957, "text": null }, { "code": null, "e": 5356, "s": 5260, "text": "The main template fun(): a\nSpecialized Template for int type: 10\nThe main template fun(): 10.14" }, { "code": null, "e": 5503, "s": 5356, "text": "An Example Program for class template specialization In the following program, a specialized version of class Test is written for int data type. " }, { "code": null, "e": 5507, "s": 5503, "text": "CPP" }, { "code": "#include <iostream>using namespace std; template <class T>class Test{ // Data members of testpublic: Test() { // Initialization of data members cout << \"General template object \\n\"; } // Other methods of Test}; template <>class Test <int>{public: Test() { // Initialization of data members cout << \"Specialized template object\\n\"; }}; int main(){ Test<int> a; Test<char> b; Test<float> c; return 0;}", "e": 5958, "s": 5507, "text": null }, { "code": null, "e": 6036, "s": 5958, "text": "Specialized template object\nGeneral template object \nGeneral template object " }, { "code": null, "e": 6687, "s": 6036, "text": "How does template specialization work? When we write any template based function or class, compiler creates a copy of that function/class whenever compiler sees that being used for a new data type or new set of data types(in case of multiple template arguments). If a specialized version is present, compiler first checks with the specialized version and then the main template. Compiler first checks with the most specialized version by matching the passed parameter with the data type(s) specified in a specialized version. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 6698, "s": 6687, "text": "ashwinanil" }, { "code": null, "e": 6717, "s": 6698, "text": "aditiyadav20102001" }, { "code": null, "e": 6730, "s": 6717, "text": "cpp-template" }, { "code": null, "e": 6741, "s": 6730, "text": "C Language" }, { "code": null, "e": 6745, "s": 6741, "text": "C++" }, { "code": null, "e": 6749, "s": 6745, "text": "CPP" }, { "code": null, "e": 6847, "s": 6749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6864, "s": 6847, "text": "Substring in C++" }, { "code": null, "e": 6886, "s": 6864, "text": "Function Pointer in C" }, { "code": null, "e": 6932, "s": 6886, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 6977, "s": 6932, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 7002, "s": 6977, "text": "std::string class in C++" }, { "code": null, "e": 7045, "s": 7002, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 7091, "s": 7045, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 7134, "s": 7091, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7168, "s": 7134, "text": "vector erase() and clear() in C++" } ]
Reducing Execution time in Python using List Comprehensions
10 Jul, 2020 Prerequisites: Comprehensions in Python Most of the competitive programmers who code in Python often face difficulty in executing the programs within the given time limit. List Comprehensions help us in reducing the execution time of a program where you are required to create a list based on any mathematical expression. We will consider an example to prove the above statement. Example : To form a list of all even numbers upto 10**7, we can do it in the following ways Method 1: %%timeit -n 100 even =[ ]for i in range(10**7): if i % 2 == 0: even.append(i) Output: Method 2: %%timeit -n 100 even =[i for i in range(10**7) if i % 2 == 0] Output: We can see the difference in the run-times of the above 2 programs, this difference increases as we increase the range, also when the math expression is a bit complex. This time difference matters a lot when these type of lists are part of a very large program. Note:The %%timeit tool is used which is available in Jupyter Notebook, it repeats the execution of the same cell multiple times specified by us, and returns the average/mean time taken for the execution of the given program. Below are the Python 3 code snippets to check the execution times for the above programs, import time # Using for loopstart = time.time()a =[ ] for i in range(10**7): if i % 2 == 0: a.append(i) print("Execution time = ", time.time()-start) # Using list comprehensionstart = time.time() a =[i for i in range(10**7) if i % 2 == 0]print("Execution time = ", time.time()-start) Output: Execution time = 1.558159589767456 Execution time = 0.9690220355987549 python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jul, 2020" }, { "code": null, "e": 94, "s": 54, "text": "Prerequisites: Comprehensions in Python" }, { "code": null, "e": 434, "s": 94, "text": "Most of the competitive programmers who code in Python often face difficulty in executing the programs within the given time limit. List Comprehensions help us in reducing the execution time of a program where you are required to create a list based on any mathematical expression. We will consider an example to prove the above statement." }, { "code": null, "e": 526, "s": 434, "text": "Example : To form a list of all even numbers upto 10**7, we can do it in the following ways" }, { "code": null, "e": 536, "s": 526, "text": "Method 1:" }, { "code": "%%timeit -n 100 even =[ ]for i in range(10**7): if i % 2 == 0: even.append(i)", "e": 625, "s": 536, "text": null }, { "code": null, "e": 633, "s": 625, "text": "Output:" }, { "code": null, "e": 643, "s": 633, "text": "Method 2:" }, { "code": "%%timeit -n 100 even =[i for i in range(10**7) if i % 2 == 0]", "e": 706, "s": 643, "text": null }, { "code": null, "e": 714, "s": 706, "text": "Output:" }, { "code": null, "e": 976, "s": 714, "text": "We can see the difference in the run-times of the above 2 programs, this difference increases as we increase the range, also when the math expression is a bit complex. This time difference matters a lot when these type of lists are part of a very large program." }, { "code": null, "e": 1201, "s": 976, "text": "Note:The %%timeit tool is used which is available in Jupyter Notebook, it repeats the execution of the same cell multiple times specified by us, and returns the average/mean time taken for the execution of the given program." }, { "code": null, "e": 1291, "s": 1201, "text": "Below are the Python 3 code snippets to check the execution times for the above programs," }, { "code": "import time # Using for loopstart = time.time()a =[ ] for i in range(10**7): if i % 2 == 0: a.append(i) print(\"Execution time = \", time.time()-start) # Using list comprehensionstart = time.time() a =[i for i in range(10**7) if i % 2 == 0]print(\"Execution time = \", time.time()-start)", "e": 1602, "s": 1291, "text": null }, { "code": null, "e": 1610, "s": 1602, "text": "Output:" }, { "code": null, "e": 1683, "s": 1610, "text": "Execution time = 1.558159589767456\nExecution time = 0.9690220355987549" }, { "code": null, "e": 1695, "s": 1683, "text": "python-list" }, { "code": null, "e": 1702, "s": 1695, "text": "Python" }, { "code": null, "e": 1714, "s": 1702, "text": "python-list" }, { "code": null, "e": 1812, "s": 1714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1844, "s": 1812, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1871, "s": 1844, "text": "Python Classes and Objects" }, { "code": null, "e": 1892, "s": 1871, "text": "Python OOPs Concepts" }, { "code": null, "e": 1915, "s": 1892, "text": "Introduction To PYTHON" }, { "code": null, "e": 1971, "s": 1915, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2002, "s": 1971, "text": "Python | os.path.join() method" }, { "code": null, "e": 2044, "s": 2002, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2086, "s": 2044, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2125, "s": 2086, "text": "Python | Get unique values from a list" } ]
Check input character is alphabet, digit or special character
19 Apr, 2021 All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it’s Alphabet, Number or Special character.ASCII value ranges- For capital alphabets 65 – 90 For small alphabets 97 – 122 For digits 48 – 57 Examples : Input : 8 Output : Digit Input : E Output : Alphabet C++ Java Python3 C# PHP Javascript // CPP program to find type of input character#include <iostream>using namespace std; void charCheck(char input_char){ // CHECKING FOR ALPHABET if ((input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) cout << " Alphabet "; // CHECKING FOR DIGITS else if (input_char >= 48 && input_char <= 57) cout << " Digit "; // OTHERWISE SPECIAL CHARACTER else cout << " Special Character ";} // Driver Codeint main(){ char input_char = '$'; charCheck(input_char); return 0;} // Java program to find type of input characterimport java.io.*; class GFG { static void charCheck(char input_char) { // CHECKING FOR ALPHABET if ((input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) System.out.println(" Alphabet "); // CHECKING FOR DIGITS else if (input_char >= 48 && input_char <= 57) System.out.println(" Digit "); // OTHERWISE SPECIAL CHARACTER else System.out.println(" Special Character "); } // Driver Code public static void main(String[] args) { char input_char = '$'; charCheck(input_char); }} // This code is contributed by vt_m. # python program to find type of# input character def charCheck(input_char): # CHECKING FOR ALPHABET if ((int(ord(input_char)) >= 65 and int(ord(input_char)) <= 90) or (int(ord(input_char)) >= 97 and int(ord(input_char)) <= 122)): print( " Alphabet ") # CHECKING FOR DIGITS elif (int(ord(input_char)) >= 48 and int(ord(input_char)) <= 57): print(" Digit ") # OTHERWISE SPECIAL CHARACTER else: print(" Special Character ") # Driver Codeinput_char = '$'charCheck(input_char) # This code is contributed by Sam007. // C# program to find type of// input characterusing System; class GFG { // Function to check type // of input character static void charCheck(char input_char) { // Checking for Alphabet if ((input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) Console.WriteLine(" Alphabet "); // Checking for Digits else if (input_char >= 48 && input_char <= 57) Console.WriteLine(" Digit "); // Otherwise Special Character else Console.WriteLine("Special Character"); } // Driver Code public static void Main() { char input_char = '$'; charCheck(input_char); }} // This code is contributed by vt_m. <?php// PHP program to find type// of input character function charCheck($input_char){ // CHECKING FOR ALPHABET if (($input_char >= 65 && $input_char <= 90) || ($input_char >= 97 && $input_char <= 122)) echo " Alphabet "; // CHECKING FOR DIGITS else if ($input_char >= 48 && $input_char <= 57) echo " Digit "; // OTHERWISE SPECIAL CHARACTER else echo " Special Character ";} // Driver Code$input_char = '$';charCheck($input_char); // This code is contributed by Sam007?> <script> // JavaScript program to find type of input character function charCheck(input) { var input_char = input.charCodeAt(0); // CHECKING FOR ALPHABET if ( (input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122) ) document.write(" Alphabet "); // CHECKING FOR DIGITS else if (input_char >= 48 && input_char <= 57) document.write(" Digit "); // OTHERWISE SPECIAL CHARACTER else document.write(" Special Character "); } // Driver Code var input_char = "$"; charCheck(input_char); // This code is contributed by rdtank. </script> Output : Special Character vt_m Sam007 SopanShrivastava Pawansinghkushwah rdtank C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Templates in C++ with Examples Operator Overloading in C++ Inheritance in C++ Queue in C++ Standard Template Library (STL) Python Dictionary Reverse a string in Java Interfaces in Java Inheritance in C++ Operator Overloading in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2021" }, { "code": null, "e": 243, "s": 52, "text": "All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it’s Alphabet, Number or Special character.ASCII value ranges- " }, { "code": null, "e": 273, "s": 243, "text": "For capital alphabets 65 – 90" }, { "code": null, "e": 302, "s": 273, "text": "For small alphabets 97 – 122" }, { "code": null, "e": 321, "s": 302, "text": "For digits 48 – 57" }, { "code": null, "e": 334, "s": 321, "text": "Examples : " }, { "code": null, "e": 388, "s": 334, "text": "Input : 8\nOutput : Digit\n\nInput : E\nOutput : Alphabet" }, { "code": null, "e": 396, "s": 392, "text": "C++" }, { "code": null, "e": 401, "s": 396, "text": "Java" }, { "code": null, "e": 409, "s": 401, "text": "Python3" }, { "code": null, "e": 412, "s": 409, "text": "C#" }, { "code": null, "e": 416, "s": 412, "text": "PHP" }, { "code": null, "e": 427, "s": 416, "text": "Javascript" }, { "code": "// CPP program to find type of input character#include <iostream>using namespace std; void charCheck(char input_char){ // CHECKING FOR ALPHABET if ((input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) cout << \" Alphabet \"; // CHECKING FOR DIGITS else if (input_char >= 48 && input_char <= 57) cout << \" Digit \"; // OTHERWISE SPECIAL CHARACTER else cout << \" Special Character \";} // Driver Codeint main(){ char input_char = '$'; charCheck(input_char); return 0;}", "e": 977, "s": 427, "text": null }, { "code": "// Java program to find type of input characterimport java.io.*; class GFG { static void charCheck(char input_char) { // CHECKING FOR ALPHABET if ((input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) System.out.println(\" Alphabet \"); // CHECKING FOR DIGITS else if (input_char >= 48 && input_char <= 57) System.out.println(\" Digit \"); // OTHERWISE SPECIAL CHARACTER else System.out.println(\" Special Character \"); } // Driver Code public static void main(String[] args) { char input_char = '$'; charCheck(input_char); }} // This code is contributed by vt_m.", "e": 1690, "s": 977, "text": null }, { "code": "# python program to find type of# input character def charCheck(input_char): # CHECKING FOR ALPHABET if ((int(ord(input_char)) >= 65 and int(ord(input_char)) <= 90) or (int(ord(input_char)) >= 97 and int(ord(input_char)) <= 122)): print( \" Alphabet \") # CHECKING FOR DIGITS elif (int(ord(input_char)) >= 48 and int(ord(input_char)) <= 57): print(\" Digit \") # OTHERWISE SPECIAL CHARACTER else: print(\" Special Character \") # Driver Codeinput_char = '$'charCheck(input_char) # This code is contributed by Sam007.", "e": 2283, "s": 1690, "text": null }, { "code": "// C# program to find type of// input characterusing System; class GFG { // Function to check type // of input character static void charCheck(char input_char) { // Checking for Alphabet if ((input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122)) Console.WriteLine(\" Alphabet \"); // Checking for Digits else if (input_char >= 48 && input_char <= 57) Console.WriteLine(\" Digit \"); // Otherwise Special Character else Console.WriteLine(\"Special Character\"); } // Driver Code public static void Main() { char input_char = '$'; charCheck(input_char); }} // This code is contributed by vt_m.", "e": 3028, "s": 2283, "text": null }, { "code": "<?php// PHP program to find type// of input character function charCheck($input_char){ // CHECKING FOR ALPHABET if (($input_char >= 65 && $input_char <= 90) || ($input_char >= 97 && $input_char <= 122)) echo \" Alphabet \"; // CHECKING FOR DIGITS else if ($input_char >= 48 && $input_char <= 57) echo \" Digit \"; // OTHERWISE SPECIAL CHARACTER else echo \" Special Character \";} // Driver Code$input_char = '$';charCheck($input_char); // This code is contributed by Sam007?>", "e": 3589, "s": 3028, "text": null }, { "code": "<script> // JavaScript program to find type of input character function charCheck(input) { var input_char = input.charCodeAt(0); // CHECKING FOR ALPHABET if ( (input_char >= 65 && input_char <= 90) || (input_char >= 97 && input_char <= 122) ) document.write(\" Alphabet \"); // CHECKING FOR DIGITS else if (input_char >= 48 && input_char <= 57) document.write(\" Digit \"); // OTHERWISE SPECIAL CHARACTER else document.write(\" Special Character \"); } // Driver Code var input_char = \"$\"; charCheck(input_char); // This code is contributed by rdtank. </script>", "e": 4319, "s": 3589, "text": null }, { "code": null, "e": 4330, "s": 4319, "text": "Output : " }, { "code": null, "e": 4350, "s": 4330, "text": " Special Character " }, { "code": null, "e": 4357, "s": 4352, "text": "vt_m" }, { "code": null, "e": 4364, "s": 4357, "text": "Sam007" }, { "code": null, "e": 4381, "s": 4364, "text": "SopanShrivastava" }, { "code": null, "e": 4399, "s": 4381, "text": "Pawansinghkushwah" }, { "code": null, "e": 4406, "s": 4399, "text": "rdtank" }, { "code": null, "e": 4410, "s": 4406, "text": "C++" }, { "code": null, "e": 4429, "s": 4410, "text": "School Programming" }, { "code": null, "e": 4433, "s": 4429, "text": "CPP" }, { "code": null, "e": 4531, "s": 4433, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4558, "s": 4531, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 4589, "s": 4558, "text": "Templates in C++ with Examples" }, { "code": null, "e": 4617, "s": 4589, "text": "Operator Overloading in C++" }, { "code": null, "e": 4636, "s": 4617, "text": "Inheritance in C++" }, { "code": null, "e": 4681, "s": 4636, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 4699, "s": 4681, "text": "Python Dictionary" }, { "code": null, "e": 4724, "s": 4699, "text": "Reverse a string in Java" }, { "code": null, "e": 4743, "s": 4724, "text": "Interfaces in Java" }, { "code": null, "e": 4762, "s": 4743, "text": "Inheritance in C++" } ]
Currency getInstance() Method in Java with Examples
09 Jul, 2021 The getInstance() Method of Currency class in Java is used to retrieve the instance of this currency for a given currency code.Syntax: CURRENCY.getInstance(String currency_code) Parameters: This method accepts one parameter currency_code which is the currency of a particular currency.Return Value: This method returns the instance of the currency for a currency code.Exceptions: The method throws Runtime Error if an invalid code is called.Below program illustrates the working of getInstance() method:Program 1: Java // Java Code to illustrate getInstance() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance("INR"); // Getting the currency code System.out.println("Currency Code of India is: " + curr_ency.toString()); }} Currency Code of India is: INR Program 2: Java // Java Code to illustrate toString() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance("USD"); // Getting the currency code System.out.println("Currency Code of USA is: " + curr_ency.toString()); }} Currency Code of USA is: USD Program 3: For an invalid Currency Code. Java // Java Code to illustrate getInstance() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { try { // Creating a currency with the code Currency curr_ency = Currency.getInstance("USDA"); // Getting the currency code String currency_code = curr_ency.toString(); System.out.println("Invalid Currency Code: " + currency_code); } catch (Exception e) { System.out.println(e); } }} java.lang.IllegalArgumentException singghakshay Java - util package Java-Currency Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2021" }, { "code": null, "e": 165, "s": 28, "text": "The getInstance() Method of Currency class in Java is used to retrieve the instance of this currency for a given currency code.Syntax: " }, { "code": null, "e": 208, "s": 165, "text": "CURRENCY.getInstance(String currency_code)" }, { "code": null, "e": 545, "s": 208, "text": "Parameters: This method accepts one parameter currency_code which is the currency of a particular currency.Return Value: This method returns the instance of the currency for a currency code.Exceptions: The method throws Runtime Error if an invalid code is called.Below program illustrates the working of getInstance() method:Program 1: " }, { "code": null, "e": 550, "s": 545, "text": "Java" }, { "code": "// Java Code to illustrate getInstance() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance(\"INR\"); // Getting the currency code System.out.println(\"Currency Code of India is: \" + curr_ency.toString()); }}", "e": 957, "s": 550, "text": null }, { "code": null, "e": 988, "s": 957, "text": "Currency Code of India is: INR" }, { "code": null, "e": 1002, "s": 990, "text": "Program 2: " }, { "code": null, "e": 1007, "s": 1002, "text": "Java" }, { "code": "// Java Code to illustrate toString() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { // Creating a currency with the code Currency curr_ency = Currency.getInstance(\"USD\"); // Getting the currency code System.out.println(\"Currency Code of USA is: \" + curr_ency.toString()); }}", "e": 1409, "s": 1007, "text": null }, { "code": null, "e": 1438, "s": 1409, "text": "Currency Code of USA is: USD" }, { "code": null, "e": 1482, "s": 1440, "text": "Program 3: For an invalid Currency Code. " }, { "code": null, "e": 1487, "s": 1482, "text": "Java" }, { "code": "// Java Code to illustrate getInstance() method import java.util.*; public class Currency_Demo { public static void main(String[] args) { try { // Creating a currency with the code Currency curr_ency = Currency.getInstance(\"USDA\"); // Getting the currency code String currency_code = curr_ency.toString(); System.out.println(\"Invalid Currency Code: \" + currency_code); } catch (Exception e) { System.out.println(e); } }}", "e": 2073, "s": 1487, "text": null }, { "code": null, "e": 2108, "s": 2073, "text": "java.lang.IllegalArgumentException" }, { "code": null, "e": 2123, "s": 2110, "text": "singghakshay" }, { "code": null, "e": 2143, "s": 2123, "text": "Java - util package" }, { "code": null, "e": 2157, "s": 2143, "text": "Java-Currency" }, { "code": null, "e": 2172, "s": 2157, "text": "Java-Functions" }, { "code": null, "e": 2177, "s": 2172, "text": "Java" }, { "code": null, "e": 2182, "s": 2177, "text": "Java" }, { "code": null, "e": 2280, "s": 2182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2295, "s": 2280, "text": "Stream In Java" }, { "code": null, "e": 2316, "s": 2295, "text": "Introduction to Java" }, { "code": null, "e": 2337, "s": 2316, "text": "Constructors in Java" }, { "code": null, "e": 2356, "s": 2337, "text": "Exceptions in Java" }, { "code": null, "e": 2373, "s": 2356, "text": "Generics in Java" }, { "code": null, "e": 2403, "s": 2373, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2429, "s": 2403, "text": "Java Programming Examples" }, { "code": null, "e": 2445, "s": 2429, "text": "Strings in Java" }, { "code": null, "e": 2482, "s": 2445, "text": "Differences between JDK, JRE and JVM" } ]
Generating API Keys For Using Any Google APIs
15 Mar, 2022 Like most software giants, Google provides its enthusiastic developers community with its APIs, SDKs and Services. These APIs from Google are hosted on their cloud platform, popularly known as Google Cloud Platform (GCP). Software such as Google Maps, YouTube, Gmail, etc., use the same APIs and now are available for the public for implementation at a very minimal cost depending upon the usage. One can use these APIs in their projects and application to integrate similar features. Through this article, we want to share with you how one can get access to those APIs. Most importantly, as these services are paid, every registered developer is provided with an API key to access the API features, which are indeed unique. So, one needs to have an API key before beginning to develop features. To your comfort, we have brought you the following steps to generate an API key. Step 1: To generate an API key for using a specific Google API, you must have an account associated with the Google Cloud Platform (GCP) with billing enabled. You can refer to this article to set up one and create a project. Step 2: Once the project is created, go to your project dashboard. You will see the APIs window below. Click on Go to APIs overview. Step 3: Now you will see Traffic, Errors and Median Latency windows. On the left, you will have a drop-down menu. Click on Library. Step 4: In the API Library page, we have access to a number of APIs and SDKs offered by Google and one can select an interested API. Step 5: For demonstrating, we clicked on the Compute Engine API. We now get an overview, documentation, and support for that API. To use this API, just click Enable option and follow the steps if posed. Step 6: Once the API is enabled, go to Credentials. You will find details about your API key. Step 7: Use this key in your application to use the specific Google API. Note (for Indian billing accounts): “On December 4, RBI had directed all banks including RRBs, NBFCs, and payment gateways that the processing of recurring transactions (domestic or cross-border) using cards or Prepaid Payment Instruments (PPIs) or Unified Payments Interface (UPI) under arrangements/practices not compliant with AFA would not be continued beyond March 31, 2021.” Source: The Hindu Because of this, the process of setting up billing accounts or settlements by Google will fail from April 1, 2021, as payments made are automatic monthly. To avoid this, you must ensure to opt for automatic payments with your nationalized banks. rkbhola5 Google Cloud Platform TechTips Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Mar, 2022" }, { "code": null, "e": 513, "s": 28, "text": "Like most software giants, Google provides its enthusiastic developers community with its APIs, SDKs and Services. These APIs from Google are hosted on their cloud platform, popularly known as Google Cloud Platform (GCP). Software such as Google Maps, YouTube, Gmail, etc., use the same APIs and now are available for the public for implementation at a very minimal cost depending upon the usage. One can use these APIs in their projects and application to integrate similar features." }, { "code": null, "e": 905, "s": 513, "text": "Through this article, we want to share with you how one can get access to those APIs. Most importantly, as these services are paid, every registered developer is provided with an API key to access the API features, which are indeed unique. So, one needs to have an API key before beginning to develop features. To your comfort, we have brought you the following steps to generate an API key." }, { "code": null, "e": 1130, "s": 905, "text": "Step 1: To generate an API key for using a specific Google API, you must have an account associated with the Google Cloud Platform (GCP) with billing enabled. You can refer to this article to set up one and create a project." }, { "code": null, "e": 1263, "s": 1130, "text": "Step 2: Once the project is created, go to your project dashboard. You will see the APIs window below. Click on Go to APIs overview." }, { "code": null, "e": 1395, "s": 1263, "text": "Step 3: Now you will see Traffic, Errors and Median Latency windows. On the left, you will have a drop-down menu. Click on Library." }, { "code": null, "e": 1528, "s": 1395, "text": "Step 4: In the API Library page, we have access to a number of APIs and SDKs offered by Google and one can select an interested API." }, { "code": null, "e": 1731, "s": 1528, "text": "Step 5: For demonstrating, we clicked on the Compute Engine API. We now get an overview, documentation, and support for that API. To use this API, just click Enable option and follow the steps if posed." }, { "code": null, "e": 1825, "s": 1731, "text": "Step 6: Once the API is enabled, go to Credentials. You will find details about your API key." }, { "code": null, "e": 1898, "s": 1825, "text": "Step 7: Use this key in your application to use the specific Google API." }, { "code": null, "e": 2297, "s": 1898, "text": "Note (for Indian billing accounts): “On December 4, RBI had directed all banks including RRBs, NBFCs, and payment gateways that the processing of recurring transactions (domestic or cross-border) using cards or Prepaid Payment Instruments (PPIs) or Unified Payments Interface (UPI) under arrangements/practices not compliant with AFA would not be continued beyond March 31, 2021.” Source: The Hindu" }, { "code": null, "e": 2543, "s": 2297, "text": "Because of this, the process of setting up billing accounts or settlements by Google will fail from April 1, 2021, as payments made are automatic monthly. To avoid this, you must ensure to opt for automatic payments with your nationalized banks." }, { "code": null, "e": 2552, "s": 2543, "text": "rkbhola5" }, { "code": null, "e": 2574, "s": 2552, "text": "Google Cloud Platform" }, { "code": null, "e": 2583, "s": 2574, "text": "TechTips" }, { "code": null, "e": 2600, "s": 2583, "text": "Web Technologies" } ]
Java Program to Generate Calendar of Any Year Without calendar.get() Function
19 Aug, 2021 Java program for generating the calendar of any desired year and month let us first go through an illustration before landing upon logic and procedural part. Illustration: Say the user wants to get the calendar of April 2011. Then, he is required to enter the year along with the month as integers and the output would return the desired month’s calendar for the respective year in a proper format. Procedure: Step 1: Take the year and the month as integer inputs from the user Step 2: Create 2 arrays as follows, one for storing days and the other for storing the months, as per proper order. String day[] = { "SUN","MON","TUE","WED","THU","FRI","SAT" } ; String month[] = { "JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER" } ; Step 3: Initialize a counter variable and three variables, each for the day, month, and year as 1, and a separate array for storing the different combinations of days on which months can be found. Eg. 31,30,29 int ar[] = { 31,29,31,30,31,30,31,31,30,31,30,31 } ; Step 4: Check the leap year condition and re-initialize values for the above array. if(y%4==0&&y%100!=0||y%100==0) ar[1]=29; // if the year is a leap year then store 29 for the month of february else ar[1]=28; // else 28 Step 5: Increment year count as month count reaches 12 and increment month count as day count reaches a value greater than that present in the array for the respective index Step 6: Print the result. Implementation: Example Java // Java Program to Generate Desired Calendar// Without calendar.get() function or// Inputting the Year and the Month // Importing required classesimport java.io.*;import java.util.Scanner; // Main classpublic class GFG { // Main driver method public static void main(String a[]) { // Reading input by creating object of Scanner class Scanner sc = new Scanner(System.in); // Display message only System.out.print("Enter the year : "); // Reading integer input value int yy = sc.nextInt(); // Display message only System.out.print("Enter month : "); // Reading integer input value int mm = sc.nextInt(); int d = 1; int m = 1; int y = 1; int dy = 1; // Storing data and months as input String day[] = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" }; String month[] = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" }; // Custom array as input int ar[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Till condition holds true while (true) { if (d == 1 && m == mm && y == yy) { break; } if (y % 4 == 0 && y % 100 != 0 || y % 100 == 0) { ar[1] = 29; } else { ar[1] = 28; } dy++; d++; if (d > ar[m - 1]) { m++; d = 1; } if (m > 12) { m = 1; y++; } if (dy == 7) { dy = 0; } } int c = dy; if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) { ar[1] = 29; } else { ar[1] = 28; } // Print the desired month of input year System.out.println("MONTH:" + month[mm - 1]); for (int k = 0; k < 7; k++) { System.out.print(" " + day[k]); } System.out.println(); for (int j = 1; j <= (ar[mm - 1] + dy); j++) { if (j > 6) { dy = dy % 6; } } int spaces = dy; if (spaces < 0) spaces = 6; // Printing the calendar for (int i = 0; i < spaces; i++) System.out.print(" "); for (int i = 1; i <= ar[mm - 1]; i++) { System.out.printf(" %4d ", i); if (((i + spaces) % 7 == 0) || (i == ar[mm - 1])) System.out.println(); } }} Output: simranarora5sos clintra Java-Date-Time Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Aug, 2021" }, { "code": null, "e": 212, "s": 54, "text": "Java program for generating the calendar of any desired year and month let us first go through an illustration before landing upon logic and procedural part." }, { "code": null, "e": 226, "s": 212, "text": "Illustration:" }, { "code": null, "e": 453, "s": 226, "text": "Say the user wants to get the calendar of April 2011. Then, he is required to enter the year along with the month as integers and the output would return the desired month’s calendar for the respective year in a proper format." }, { "code": null, "e": 464, "s": 453, "text": "Procedure:" }, { "code": null, "e": 532, "s": 464, "text": "Step 1: Take the year and the month as integer inputs from the user" }, { "code": null, "e": 648, "s": 532, "text": "Step 2: Create 2 arrays as follows, one for storing days and the other for storing the months, as per proper order." }, { "code": null, "e": 849, "s": 648, "text": "String day[] = { \"SUN\",\"MON\",\"TUE\",\"WED\",\"THU\",\"FRI\",\"SAT\" } ; \nString month[] = { \"JANUARY\",\"FEBRUARY\",\"MARCH\",\"APRIL\",\"MAY\",\"JUNE\",\"JULY\",\"AUGUST\",\"SEPTEMBER\",\"OCTOBER\",\"NOVEMBER\",\"DECEMBER\" } ; " }, { "code": null, "e": 1059, "s": 849, "text": "Step 3: Initialize a counter variable and three variables, each for the day, month, and year as 1, and a separate array for storing the different combinations of days on which months can be found. Eg. 31,30,29" }, { "code": null, "e": 1112, "s": 1059, "text": "int ar[] = { 31,29,31,30,31,30,31,31,30,31,30,31 } ;" }, { "code": null, "e": 1196, "s": 1112, "text": "Step 4: Check the leap year condition and re-initialize values for the above array." }, { "code": null, "e": 1380, "s": 1196, "text": "if(y%4==0&&y%100!=0||y%100==0)\nar[1]=29; // if the year is a leap year then store 29 for the month of february\nelse \nar[1]=28; // else 28 " }, { "code": null, "e": 1554, "s": 1380, "text": "Step 5: Increment year count as month count reaches 12 and increment month count as day count reaches a value greater than that present in the array for the respective index" }, { "code": null, "e": 1580, "s": 1554, "text": "Step 6: Print the result." }, { "code": null, "e": 1596, "s": 1580, "text": "Implementation:" }, { "code": null, "e": 1604, "s": 1596, "text": "Example" }, { "code": null, "e": 1609, "s": 1604, "text": "Java" }, { "code": "// Java Program to Generate Desired Calendar// Without calendar.get() function or// Inputting the Year and the Month // Importing required classesimport java.io.*;import java.util.Scanner; // Main classpublic class GFG { // Main driver method public static void main(String a[]) { // Reading input by creating object of Scanner class Scanner sc = new Scanner(System.in); // Display message only System.out.print(\"Enter the year : \"); // Reading integer input value int yy = sc.nextInt(); // Display message only System.out.print(\"Enter month : \"); // Reading integer input value int mm = sc.nextInt(); int d = 1; int m = 1; int y = 1; int dy = 1; // Storing data and months as input String day[] = { \"SUN\", \"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\" }; String month[] = { \"JANUARY\", \"FEBRUARY\", \"MARCH\", \"APRIL\", \"MAY\", \"JUNE\", \"JULY\", \"AUGUST\", \"SEPTEMBER\", \"OCTOBER\", \"NOVEMBER\", \"DECEMBER\" }; // Custom array as input int ar[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Till condition holds true while (true) { if (d == 1 && m == mm && y == yy) { break; } if (y % 4 == 0 && y % 100 != 0 || y % 100 == 0) { ar[1] = 29; } else { ar[1] = 28; } dy++; d++; if (d > ar[m - 1]) { m++; d = 1; } if (m > 12) { m = 1; y++; } if (dy == 7) { dy = 0; } } int c = dy; if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) { ar[1] = 29; } else { ar[1] = 28; } // Print the desired month of input year System.out.println(\"MONTH:\" + month[mm - 1]); for (int k = 0; k < 7; k++) { System.out.print(\" \" + day[k]); } System.out.println(); for (int j = 1; j <= (ar[mm - 1] + dy); j++) { if (j > 6) { dy = dy % 6; } } int spaces = dy; if (spaces < 0) spaces = 6; // Printing the calendar for (int i = 0; i < spaces; i++) System.out.print(\" \"); for (int i = 1; i <= ar[mm - 1]; i++) { System.out.printf(\" %4d \", i); if (((i + spaces) % 7 == 0) || (i == ar[mm - 1])) System.out.println(); } }}", "e": 4383, "s": 1609, "text": null }, { "code": null, "e": 4392, "s": 4383, "text": "Output: " }, { "code": null, "e": 4410, "s": 4394, "text": "simranarora5sos" }, { "code": null, "e": 4418, "s": 4410, "text": "clintra" }, { "code": null, "e": 4433, "s": 4418, "text": "Java-Date-Time" }, { "code": null, "e": 4438, "s": 4433, "text": "Java" }, { "code": null, "e": 4452, "s": 4438, "text": "Java Programs" }, { "code": null, "e": 4457, "s": 4452, "text": "Java" } ]
Profile Application using Python Flask and MySQL
26 May, 2022 Project Title: Profile Application using Python Flask and MySQL Type of Application (Category): Web application. Introduction: A framework is a code library that makes a developer’s life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not require particular tools or libraries. Side tabs are used for single page web applications or to display different contents. Pre-requisite: Knowledge of Python, MySQL Workbench and basics of Flask Framework. Python and MySQL Workbench should be installed in the system. Visual studio code or Spyder or any code editor to work on the application. Technologies used in the project: Flask framework, MySQL Workbench. Implementation of the Project: (1) Creating Environment Step-1: Create an environment. Create a project folder and a venv folder within. py -3 -m venv venv Step-2: Activate the environment. venv\Scripts\activate Step-3: Install Flask. pip install Flask (2) MySQL Workbench Step-1: Install MySQL workbench.Link to install : https://dev.mysql.com/downloads/workbench/Know more about it : https://www.mysql.com/products/workbench/ Step-2: Install ‘mysqlbd’ module in your venv. pip install flask-mysqldb Step-3: Open MySQL workbench. Step-4: Write the following code. The above SQL statement will create our database geekprofile with the table accounts. Step-5: Execute the query. (3) Creating Project Step-1: Create an empty folder ‘geeksprofile’. Step-2: Now open your code editor and open this ‘geeksprofile’ folder. Step-3: Create ‘app.py’ folder and write the code given below. # Store this code in 'app.py' filefrom flask import Flask, render_template, request, redirect, url_for, sessionfrom flask_mysqldb import MySQLimport MySQLdb.cursorsimport re app = Flask(__name__) app.secret_key = 'your secret key' app.config['MYSQL_HOST'] = 'localhost'app.config['MYSQL_USER'] = 'root'app.config['MYSQL_PASSWORD'] = 'password'app.config['MYSQL_DB'] = 'geekprofile' mysql = MySQL(app) @app.route('/')@app.route('/login', methods =['GET', 'POST'])def login(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form: username = request.form['username'] password = request.form['password'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = % s AND password = % s', (username, password, )) account = cursor.fetchone() if account: session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] msg = 'Logged in successfully !' return render_template('index.html', msg = msg) else: msg = 'Incorrect username / password !' return render_template('login.html', msg = msg) @app.route('/logout')def logout(): session.pop('loggedin', None) session.pop('id', None) session.pop('username', None) return redirect(url_for('login')) @app.route('/register', methods =['GET', 'POST'])def register(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form and 'address' in request.form and 'city' in request.form and 'country' in request.form and 'postalcode' in request.form and 'organisation' in request.form: username = request.form['username'] password = request.form['password'] email = request.form['email'] organisation = request.form['organisation'] address = request.form['address'] city = request.form['city'] state = request.form['state'] country = request.form['country'] postalcode = request.form['postalcode'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = % s', (username, )) account = cursor.fetchone() if account: msg = 'Account already exists !' elif not re.match(r'[^@]+@[^@]+\.[^@]+', email): msg = 'Invalid email address !' elif not re.match(r'[A-Za-z0-9]+', username): msg = 'name must contain only characters and numbers !' else: cursor.execute('INSERT INTO accounts VALUES (NULL, % s, % s, % s, % s, % s, % s, % s, % s, % s)', (username, password, email, organisation, address, city, state, country, postalcode, )) mysql.connection.commit() msg = 'You have successfully registered !' elif request.method == 'POST': msg = 'Please fill out the form !' return render_template('register.html', msg = msg) @app.route("/index")def index(): if 'loggedin' in session: return render_template("index.html") return redirect(url_for('login')) @app.route("/display")def display(): if 'loggedin' in session: cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE id = % s', (session['id'], )) account = cursor.fetchone() return render_template("display.html", account = account) return redirect(url_for('login')) @app.route("/update", methods =['GET', 'POST'])def update(): msg = '' if 'loggedin' in session: if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form and 'address' in request.form and 'city' in request.form and 'country' in request.form and 'postalcode' in request.form and 'organisation' in request.form: username = request.form['username'] password = request.form['password'] email = request.form['email'] organisation = request.form['organisation'] address = request.form['address'] city = request.form['city'] state = request.form['state'] country = request.form['country'] postalcode = request.form['postalcode'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = % s', (username, )) account = cursor.fetchone() if account: msg = 'Account already exists !' elif not re.match(r'[^@]+@[^@]+\.[^@]+', email): msg = 'Invalid email address !' elif not re.match(r'[A-Za-z0-9]+', username): msg = 'name must contain only characters and numbers !' else: cursor.execute('UPDATE accounts SET username =% s, password =% s, email =% s, organisation =% s, address =% s, city =% s, state =% s, country =% s, postalcode =% s WHERE id =% s', (username, password, email, organisation, address, city, state, country, postalcode, (session['id'], ), )) mysql.connection.commit() msg = 'You have successfully updated !' elif request.method == 'POST': msg = 'Please fill out the form !' return render_template("update.html", msg = msg) return redirect(url_for('login')) if __name__ == "__main__": app.run(host ="localhost", port = int("5000")) Step-4: Create the folder ‘templates’. create the files ‘index.html’, ‘display.html’, ‘update.html’, ‘login.html’, ‘register.html’ inside the ‘templates’ folder. Step-5: Open ‘login.html’ file and write the code given below. In ‘login.html’, we have two fields i.e. username and password. When user enters correct username and password, it will route you to index page otherwise ‘Incorrect username/password’ is displayed. <!--Store this code in 'login.html' file inside the 'templates' folder--><html> <head> <meta charset="UTF-8"> <title> Login </title> <link rel="stylesheet" href="../static/style.css"> </head> <body> <div class="logincontent" align="center"> <div class="logintop"> <h1>Login</h1> </div></br></br></br></br> <div class="loginbottom"> <form action="{{ url_for('login')}}" method="post" autocomplete="off"> <div class="msg">{{ msg }}</div> <input type="text" name="username" placeholder="Enter Your Username" class="textbox" id="username" required></br></br> <input type="password" name="password" placeholder="Enter Your Password" class="textbox" id="password" required></br></br></br> <input type="submit" class="btn" value="Login"> </form></br></br> <p class="worddark">New to this page? <a class="worddark" href="{{ url_for('register')}}">Register here</a></p> </div> </div> </body></html> Step-6: Open ‘register.html’ file and write the code given below. In ‘register.html’, we have nine fields i.e. username, password, email, organisation, address, city, state, country, postal code. When user enters all the information, it stored the data in the database and ‘Registration successful’ is displayed. <!--Store this code in 'register.html' file inside the 'templates' folder--> <html> <head> <meta charset="UTF-8"> <title> register </title> <link rel="stylesheet" href="../static/style.css"> </head> <body> <div class="registercontent" align="center"> <div class="registertop"> <h1>Register</h1> </div></br></br> <div class="registerbottom"> <form action="{{ url_for('register')}}" method="post" autocomplete="off"> <div class="msg">{{ msg }}</div> <input type="text" name="username" placeholder="Enter Your Username" class="textbox" id="username" required></br></br> <input type="password" name="password" placeholder="Enter Your Password" class="textbox" id="password" required></br></br> <input type="email" name="email" placeholder="Enter Your Email ID" class="textbox" id="email" required></br></br> <input type="text" name="organisation" placeholder="Enter Your Organisation" class="textbox" id="organisation" required></br></br> <input type="text" name="address" placeholder="Enter Your Address" class="textbox" id="address" required></br></br> <input type="text" name="city" placeholder="Enter Your City" class="textbox" id="city" required></br></br> <input type="text" name="state" placeholder="Enter Your State" class="textbox" id="state" required></br></br> <input type="text" name="country" placeholder="Enter Your Country" class="textbox" id="country" required></br></br> <input type="text" name="postalcode" placeholder="Enter Your Postal Code" class="textbox" id="postalcode" required></br></br> <input type="submit" class="btn" value="Register"> </form> <p class="worddark">Already have account? <a class="worddark" href="{{ url_for('login')}}">Login here</a></p> </div> </div> </body></html> Step-7: Open ‘index.html’ file and write the code given below. When user logs in successfully, this page is displayed and ‘Logged in successful!’ is displayed. <!--Store this code in 'index.html' file inside the 'templates' folder--><html lang="en"> <head> <title>index</title> <link rel="stylesheet" href="../static/style.css"> </head> <body bgcolor="#e6ffee"> <div class="one"> <div class="two"> <h1>Side Bar</h1> <ul> <li class="active"><a href="{{url_for('index')}}">Index</a></li> <li><a href="{{url_for('display')}}">Display</a></li> <li><a href="{{url_for('update')}}">Update</a></li> <li><a href="{{url_for('logout')}}">Log out</a></li> </ul> </div> <div class="content" align="center"> <div class="topbar"> <h2>Welcome!! You are in Index Page!! </h2> </div></br></br> <div class="contentbar"> <div class="msg">{{ msg }}</div> </div> </div> </div> </body></html> Step-8: Open ‘display.html’ file and write the code given below. Here, the user information stored in database are displayed. <!--Store this code in 'display.html' file inside the 'templates' folder--> <html lang="en"> <head> <title>display</title> <link rel="stylesheet" href="../static/style.css"> </head> <body bgcolor="#e6ffee"> <div class="one"> <div class="two"> <h1>Side Bar</h1> <ul> <li><a href="{{url_for('index')}}">Index</a></li> <li class="active"><a href="{{url_for('display')}}">Display</a></li> <li><a href="{{url_for('update')}}">Update</a></li> <li><a href="{{url_for('logout')}}">Log out</a></li> </ul> </div> <div class="content" align="center"> <div class="topbar"> <h2>Welcome!! You are in Display Page!! </h2> </div> </br> <div class="contentbar"> <h1>Your Details</h1> </br> {% block content %} <div class="border"> <table class="worddark"></br></br></br></br> <tr> <td>Username:</td> <td>{{ account['username'] }}</td> </tr> <tr> <td>Passworde:</td> <td>{{ account['password'] }}</td> </tr> <tr> <td>Email ID:</td> <td>{{ account['email'] }}</td> </tr> <tr> <td>Organisation:</td> <td>{{ account['organisation'] }}</td> </tr> <tr> <td>Address:</td> <td>{{ account['address'] }}</td> </tr> <tr> <td>City:</td> <td>{{ account['city'] }}</td> </tr> <tr> <td>State:</td> <td>{{ account['state'] }}</td> </tr> <tr> <td>Country:</td> <td>{{ account['country'] }}</td> </tr> <tr> <td>Postal code:</td> <td>{{ account['postalcode'] }}</td> </tr> </table> </div> {% endblock %} </div> </div> </div> </body></html> Step-9: Open ‘update.html’ file and write the code given below. The user can update his/her data which also updates the database. <!--Store this code in 'update.html' file inside the 'templates' folder--><html lang="en"> <head> <title>update</title> <link rel="stylesheet" href="../static/style.css"> </head> <body bgcolor="#e6ffee"> <div class="one"> <div class="two"> <h1>Side Bar</h1> <ul> <li><a href="{{url_for('index')}}">Index</a></li> <li><a href="{{url_for('display')}}">Display</a></li> <li class="active"><a href="{{url_for('update')}}">Update</a></li> <li><a href="{{url_for('logout')}}">Log out</a></li> </ul> </div> <div class="content" align="center"> <div class="topbar"> <h2>Welcome!! You are in Update Page!! </h2> </div></br></br> <div class="contentbar"> <h1>Fill Your Details to Update</h1></br> <form action="{{ url_for('update') }}" method="post" autocomplete="off"> <div class="msg">{{ msg }}</div> <input type="text" name="username" placeholder="Enter Your Username" class="textbox" id="username" required></br></br> <input type="password" name="password" placeholder="Enter Your Password" class="textbox" id="password" required></br></br> <input type="email" name="email" placeholder="Enter Your Email ID" class="textbox" id="email" required></br></br> <input type="text" name="organisation" placeholder="Enter Your Organisation" class="textbox" id="organisation" required></br></br> <input type="text" name="address" placeholder="Enter Your Address" class="textbox" id="address" required></br></br> <input type="text" name="city" placeholder="Enter Your City" class="textbox" id="city" required></br></br> <input type="text" name="state" placeholder="Enter Your State" class="textbox" id="state" required></br></br> <input type="text" name="country" placeholder="Enter Your Country" class="textbox" id="country" required></br></br> <input type="text" name="postalcode" placeholder="Enter Your Postal Code" class="textbox" id="postalcode" required></br></br> <input type="submit" class="btn" value="Update"> </form> </div> </div> </div> </body></html> Step-10: Create the folder ‘static’. create the file ‘style.css’ inside the ‘static’ folder and paste the given CSS code. /*Store this code in 'style.css' file inside the 'static' folder*/ .logincontent{ margin: 0 auto; height: 500px; width: 400px; background-color: #e6ffee; border-radius: 10px;} .registercontent{ margin: 0 auto; height: 720px; width: 400px; background-color: #e6ffee; border-radius: 10px;} .logintop{ height: 60px; width: 400px; background-color: #009933; color: #ffffff;} .registertop{ height: 60px; width: 400px; background-color: #009933; color: #ffffff;} .textbox{ padding: 10px 40px; background-color: #009933; border-radius: 10px;} ::placeholder { color: #FFFFFF; opacity: 1; font-style: oblique; font-weight: bold;} .btn { padding: 10px 40px; background-color: #009933; color: #FFFFFF; font-style: oblique; font-weight: bold; border-radius: 10px;} .worddark{ color: #009933; font-style: oblique; font-weight: bold;} .wordlight{ color: #FFFFFF; font-style: oblique; font-weight: bold;} *{ margin: 0; padding: 0; box-sizing: border-box; list-style: none; text-decoration: none; font-family: 'Josefin Sans', sans-serif;} .one{ display: flex; position: relative;} .one .two{ width: 225px; height: 100%; background: #009933; padding: 30px 0px; position: fixed;} .one .two h1{ color: #fff; text-transform: uppercase; text-align: center; margin-bottom: 30px; font-style: oblique; font-weight: bold;} .one .two h2{ color: #fff; text-align: center;} .one .two .active{ background: #0a8032;} .one .two ul li{ text-align: center; padding: 15px; border-bottom: 0.1px solid white; border-top: 0.1px solid white;} .one .two ul li a{ color: #ffffff; display: block;} .one .two ul li a .side{ width: 25px; align:center;} .one .content{ width: 100%; margin-left: 200px;} .one .content .topbar{ text-align: center; padding: 20px; background: #00b33c; color: white;} .one .content .contentbar{ margin: auto;} .one .content .contentbar h1{ color: #11a844; text-align: center; font-style: oblique; font-weight: bold;} Step-11: The project structure will look like this. (4) Run the Project Step-1: Run the server. Step-2: Browse the URL ‘localhost:5000’. Step-3: The output web page will be displayed. (5) Testing of the Application Step-1: If you are new user, go to sign up page and fill the details. Step-2: After registration, go to login page. Enter your username and password and sign in. Step-3: If your login is successful, you will be moved to index page and your name will be displayed. Step-4: You can view your profile details in display page and also you can update your details in update page. Output:Login page: Register page: If login is successful, Index Page: Update Page: Before updation, Display page: After updation, Display page: Database – Before update: Database – After update: Flask Projects Python Flask Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() 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": "\n26 May, 2022" }, { "code": null, "e": 92, "s": 28, "text": "Project Title: Profile Application using Python Flask and MySQL" }, { "code": null, "e": 141, "s": 92, "text": "Type of Application (Category): Web application." }, { "code": null, "e": 628, "s": 141, "text": "Introduction: A framework is a code library that makes a developer’s life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not require particular tools or libraries. Side tabs are used for single page web applications or to display different contents." }, { "code": null, "e": 849, "s": 628, "text": "Pre-requisite: Knowledge of Python, MySQL Workbench and basics of Flask Framework. Python and MySQL Workbench should be installed in the system. Visual studio code or Spyder or any code editor to work on the application." }, { "code": null, "e": 917, "s": 849, "text": "Technologies used in the project: Flask framework, MySQL Workbench." }, { "code": null, "e": 948, "s": 917, "text": "Implementation of the Project:" }, { "code": null, "e": 973, "s": 948, "text": "(1) Creating Environment" }, { "code": null, "e": 1054, "s": 973, "text": "Step-1: Create an environment. Create a project folder and a venv folder within." }, { "code": null, "e": 1073, "s": 1054, "text": "py -3 -m venv venv" }, { "code": null, "e": 1107, "s": 1073, "text": "Step-2: Activate the environment." }, { "code": null, "e": 1129, "s": 1107, "text": "venv\\Scripts\\activate" }, { "code": null, "e": 1152, "s": 1129, "text": "Step-3: Install Flask." }, { "code": null, "e": 1170, "s": 1152, "text": "pip install Flask" }, { "code": null, "e": 1190, "s": 1170, "text": "(2) MySQL Workbench" }, { "code": null, "e": 1345, "s": 1190, "text": "Step-1: Install MySQL workbench.Link to install : https://dev.mysql.com/downloads/workbench/Know more about it : https://www.mysql.com/products/workbench/" }, { "code": null, "e": 1392, "s": 1345, "text": "Step-2: Install ‘mysqlbd’ module in your venv." }, { "code": null, "e": 1418, "s": 1392, "text": "pip install flask-mysqldb" }, { "code": null, "e": 1448, "s": 1418, "text": "Step-3: Open MySQL workbench." }, { "code": null, "e": 1568, "s": 1448, "text": "Step-4: Write the following code. The above SQL statement will create our database geekprofile with the table accounts." }, { "code": null, "e": 1595, "s": 1568, "text": "Step-5: Execute the query." }, { "code": null, "e": 1616, "s": 1595, "text": "(3) Creating Project" }, { "code": null, "e": 1663, "s": 1616, "text": "Step-1: Create an empty folder ‘geeksprofile’." }, { "code": null, "e": 1734, "s": 1663, "text": "Step-2: Now open your code editor and open this ‘geeksprofile’ folder." }, { "code": null, "e": 1797, "s": 1734, "text": "Step-3: Create ‘app.py’ folder and write the code given below." }, { "code": "# Store this code in 'app.py' filefrom flask import Flask, render_template, request, redirect, url_for, sessionfrom flask_mysqldb import MySQLimport MySQLdb.cursorsimport re app = Flask(__name__) app.secret_key = 'your secret key' app.config['MYSQL_HOST'] = 'localhost'app.config['MYSQL_USER'] = 'root'app.config['MYSQL_PASSWORD'] = 'password'app.config['MYSQL_DB'] = 'geekprofile' mysql = MySQL(app) @app.route('/')@app.route('/login', methods =['GET', 'POST'])def login(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form: username = request.form['username'] password = request.form['password'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = % s AND password = % s', (username, password, )) account = cursor.fetchone() if account: session['loggedin'] = True session['id'] = account['id'] session['username'] = account['username'] msg = 'Logged in successfully !' return render_template('index.html', msg = msg) else: msg = 'Incorrect username / password !' return render_template('login.html', msg = msg) @app.route('/logout')def logout(): session.pop('loggedin', None) session.pop('id', None) session.pop('username', None) return redirect(url_for('login')) @app.route('/register', methods =['GET', 'POST'])def register(): msg = '' if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form and 'address' in request.form and 'city' in request.form and 'country' in request.form and 'postalcode' in request.form and 'organisation' in request.form: username = request.form['username'] password = request.form['password'] email = request.form['email'] organisation = request.form['organisation'] address = request.form['address'] city = request.form['city'] state = request.form['state'] country = request.form['country'] postalcode = request.form['postalcode'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = % s', (username, )) account = cursor.fetchone() if account: msg = 'Account already exists !' elif not re.match(r'[^@]+@[^@]+\\.[^@]+', email): msg = 'Invalid email address !' elif not re.match(r'[A-Za-z0-9]+', username): msg = 'name must contain only characters and numbers !' else: cursor.execute('INSERT INTO accounts VALUES (NULL, % s, % s, % s, % s, % s, % s, % s, % s, % s)', (username, password, email, organisation, address, city, state, country, postalcode, )) mysql.connection.commit() msg = 'You have successfully registered !' elif request.method == 'POST': msg = 'Please fill out the form !' return render_template('register.html', msg = msg) @app.route(\"/index\")def index(): if 'loggedin' in session: return render_template(\"index.html\") return redirect(url_for('login')) @app.route(\"/display\")def display(): if 'loggedin' in session: cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE id = % s', (session['id'], )) account = cursor.fetchone() return render_template(\"display.html\", account = account) return redirect(url_for('login')) @app.route(\"/update\", methods =['GET', 'POST'])def update(): msg = '' if 'loggedin' in session: if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form and 'address' in request.form and 'city' in request.form and 'country' in request.form and 'postalcode' in request.form and 'organisation' in request.form: username = request.form['username'] password = request.form['password'] email = request.form['email'] organisation = request.form['organisation'] address = request.form['address'] city = request.form['city'] state = request.form['state'] country = request.form['country'] postalcode = request.form['postalcode'] cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = % s', (username, )) account = cursor.fetchone() if account: msg = 'Account already exists !' elif not re.match(r'[^@]+@[^@]+\\.[^@]+', email): msg = 'Invalid email address !' elif not re.match(r'[A-Za-z0-9]+', username): msg = 'name must contain only characters and numbers !' else: cursor.execute('UPDATE accounts SET username =% s, password =% s, email =% s, organisation =% s, address =% s, city =% s, state =% s, country =% s, postalcode =% s WHERE id =% s', (username, password, email, organisation, address, city, state, country, postalcode, (session['id'], ), )) mysql.connection.commit() msg = 'You have successfully updated !' elif request.method == 'POST': msg = 'Please fill out the form !' return render_template(\"update.html\", msg = msg) return redirect(url_for('login')) if __name__ == \"__main__\": app.run(host =\"localhost\", port = int(\"5000\"))", "e": 7345, "s": 1797, "text": null }, { "code": null, "e": 7507, "s": 7345, "text": "Step-4: Create the folder ‘templates’. create the files ‘index.html’, ‘display.html’, ‘update.html’, ‘login.html’, ‘register.html’ inside the ‘templates’ folder." }, { "code": null, "e": 7768, "s": 7507, "text": "Step-5: Open ‘login.html’ file and write the code given below. In ‘login.html’, we have two fields i.e. username and password. When user enters correct username and password, it will route you to index page otherwise ‘Incorrect username/password’ is displayed." }, { "code": "<!--Store this code in 'login.html' file inside the 'templates' folder--><html> <head> <meta charset=\"UTF-8\"> <title> Login </title> <link rel=\"stylesheet\" href=\"../static/style.css\"> </head> <body> <div class=\"logincontent\" align=\"center\"> <div class=\"logintop\"> <h1>Login</h1> </div></br></br></br></br> <div class=\"loginbottom\"> <form action=\"{{ url_for('login')}}\" method=\"post\" autocomplete=\"off\"> <div class=\"msg\">{{ msg }}</div> <input type=\"text\" name=\"username\" placeholder=\"Enter Your Username\" class=\"textbox\" id=\"username\" required></br></br> <input type=\"password\" name=\"password\" placeholder=\"Enter Your Password\" class=\"textbox\" id=\"password\" required></br></br></br> <input type=\"submit\" class=\"btn\" value=\"Login\"> </form></br></br> <p class=\"worddark\">New to this page? <a class=\"worddark\" href=\"{{ url_for('register')}}\">Register here</a></p> </div> </div> </body></html>", "e": 8854, "s": 7768, "text": null }, { "code": null, "e": 9167, "s": 8854, "text": "Step-6: Open ‘register.html’ file and write the code given below. In ‘register.html’, we have nine fields i.e. username, password, email, organisation, address, city, state, country, postal code. When user enters all the information, it stored the data in the database and ‘Registration successful’ is displayed." }, { "code": "<!--Store this code in 'register.html' file inside the 'templates' folder--> <html> <head> <meta charset=\"UTF-8\"> <title> register </title> <link rel=\"stylesheet\" href=\"../static/style.css\"> </head> <body> <div class=\"registercontent\" align=\"center\"> <div class=\"registertop\"> <h1>Register</h1> </div></br></br> <div class=\"registerbottom\"> <form action=\"{{ url_for('register')}}\" method=\"post\" autocomplete=\"off\"> <div class=\"msg\">{{ msg }}</div> <input type=\"text\" name=\"username\" placeholder=\"Enter Your Username\" class=\"textbox\" id=\"username\" required></br></br> <input type=\"password\" name=\"password\" placeholder=\"Enter Your Password\" class=\"textbox\" id=\"password\" required></br></br> <input type=\"email\" name=\"email\" placeholder=\"Enter Your Email ID\" class=\"textbox\" id=\"email\" required></br></br> <input type=\"text\" name=\"organisation\" placeholder=\"Enter Your Organisation\" class=\"textbox\" id=\"organisation\" required></br></br> <input type=\"text\" name=\"address\" placeholder=\"Enter Your Address\" class=\"textbox\" id=\"address\" required></br></br> <input type=\"text\" name=\"city\" placeholder=\"Enter Your City\" class=\"textbox\" id=\"city\" required></br></br> <input type=\"text\" name=\"state\" placeholder=\"Enter Your State\" class=\"textbox\" id=\"state\" required></br></br> <input type=\"text\" name=\"country\" placeholder=\"Enter Your Country\" class=\"textbox\" id=\"country\" required></br></br> <input type=\"text\" name=\"postalcode\" placeholder=\"Enter Your Postal Code\" class=\"textbox\" id=\"postalcode\" required></br></br> <input type=\"submit\" class=\"btn\" value=\"Register\"> </form> <p class=\"worddark\">Already have account? <a class=\"worddark\" href=\"{{ url_for('login')}}\">Login here</a></p> </div> </div> </body></html>", "e": 11148, "s": 9167, "text": null }, { "code": null, "e": 11308, "s": 11148, "text": "Step-7: Open ‘index.html’ file and write the code given below. When user logs in successfully, this page is displayed and ‘Logged in successful!’ is displayed." }, { "code": "<!--Store this code in 'index.html' file inside the 'templates' folder--><html lang=\"en\"> <head> <title>index</title> <link rel=\"stylesheet\" href=\"../static/style.css\"> </head> <body bgcolor=\"#e6ffee\"> <div class=\"one\"> <div class=\"two\"> <h1>Side Bar</h1> <ul> <li class=\"active\"><a href=\"{{url_for('index')}}\">Index</a></li> <li><a href=\"{{url_for('display')}}\">Display</a></li> <li><a href=\"{{url_for('update')}}\">Update</a></li> <li><a href=\"{{url_for('logout')}}\">Log out</a></li> </ul> </div> <div class=\"content\" align=\"center\"> <div class=\"topbar\"> <h2>Welcome!! You are in Index Page!! </h2> </div></br></br> <div class=\"contentbar\"> <div class=\"msg\">{{ msg }}</div> </div> </div> </div> </body></html>", "e": 12370, "s": 11308, "text": null }, { "code": null, "e": 12496, "s": 12370, "text": "Step-8: Open ‘display.html’ file and write the code given below. Here, the user information stored in database are displayed." }, { "code": "<!--Store this code in 'display.html' file inside the 'templates' folder--> <html lang=\"en\"> <head> <title>display</title> <link rel=\"stylesheet\" href=\"../static/style.css\"> </head> <body bgcolor=\"#e6ffee\"> <div class=\"one\"> <div class=\"two\"> <h1>Side Bar</h1> <ul> <li><a href=\"{{url_for('index')}}\">Index</a></li> <li class=\"active\"><a href=\"{{url_for('display')}}\">Display</a></li> <li><a href=\"{{url_for('update')}}\">Update</a></li> <li><a href=\"{{url_for('logout')}}\">Log out</a></li> </ul> </div> <div class=\"content\" align=\"center\"> <div class=\"topbar\"> <h2>Welcome!! You are in Display Page!! </h2> </div> </br> <div class=\"contentbar\"> <h1>Your Details</h1> </br> {% block content %} <div class=\"border\"> <table class=\"worddark\"></br></br></br></br> <tr> <td>Username:</td> <td>{{ account['username'] }}</td> </tr> <tr> <td>Passworde:</td> <td>{{ account['password'] }}</td> </tr> <tr> <td>Email ID:</td> <td>{{ account['email'] }}</td> </tr> <tr> <td>Organisation:</td> <td>{{ account['organisation'] }}</td> </tr> <tr> <td>Address:</td> <td>{{ account['address'] }}</td> </tr> <tr> <td>City:</td> <td>{{ account['city'] }}</td> </tr> <tr> <td>State:</td> <td>{{ account['state'] }}</td> </tr> <tr> <td>Country:</td> <td>{{ account['country'] }}</td> </tr> <tr> <td>Postal code:</td> <td>{{ account['postalcode'] }}</td> </tr> </table> </div> {% endblock %} </div> </div> </div> </body></html>", "e": 15649, "s": 12496, "text": null }, { "code": null, "e": 15779, "s": 15649, "text": "Step-9: Open ‘update.html’ file and write the code given below. The user can update his/her data which also updates the database." }, { "code": "<!--Store this code in 'update.html' file inside the 'templates' folder--><html lang=\"en\"> <head> <title>update</title> <link rel=\"stylesheet\" href=\"../static/style.css\"> </head> <body bgcolor=\"#e6ffee\"> <div class=\"one\"> <div class=\"two\"> <h1>Side Bar</h1> <ul> <li><a href=\"{{url_for('index')}}\">Index</a></li> <li><a href=\"{{url_for('display')}}\">Display</a></li> <li class=\"active\"><a href=\"{{url_for('update')}}\">Update</a></li> <li><a href=\"{{url_for('logout')}}\">Log out</a></li> </ul> </div> <div class=\"content\" align=\"center\"> <div class=\"topbar\"> <h2>Welcome!! You are in Update Page!! </h2> </div></br></br> <div class=\"contentbar\"> <h1>Fill Your Details to Update</h1></br> <form action=\"{{ url_for('update') }}\" method=\"post\" autocomplete=\"off\"> <div class=\"msg\">{{ msg }}</div> <input type=\"text\" name=\"username\" placeholder=\"Enter Your Username\" class=\"textbox\" id=\"username\" required></br></br> <input type=\"password\" name=\"password\" placeholder=\"Enter Your Password\" class=\"textbox\" id=\"password\" required></br></br> <input type=\"email\" name=\"email\" placeholder=\"Enter Your Email ID\" class=\"textbox\" id=\"email\" required></br></br> <input type=\"text\" name=\"organisation\" placeholder=\"Enter Your Organisation\" class=\"textbox\" id=\"organisation\" required></br></br> <input type=\"text\" name=\"address\" placeholder=\"Enter Your Address\" class=\"textbox\" id=\"address\" required></br></br> <input type=\"text\" name=\"city\" placeholder=\"Enter Your City\" class=\"textbox\" id=\"city\" required></br></br> <input type=\"text\" name=\"state\" placeholder=\"Enter Your State\" class=\"textbox\" id=\"state\" required></br></br> <input type=\"text\" name=\"country\" placeholder=\"Enter Your Country\" class=\"textbox\" id=\"country\" required></br></br> <input type=\"text\" name=\"postalcode\" placeholder=\"Enter Your Postal Code\" class=\"textbox\" id=\"postalcode\" required></br></br> <input type=\"submit\" class=\"btn\" value=\"Update\"> </form> </div> </div> </div> </body></html>", "e": 18329, "s": 15779, "text": null }, { "code": null, "e": 18451, "s": 18329, "text": "Step-10: Create the folder ‘static’. create the file ‘style.css’ inside the ‘static’ folder and paste the given CSS code." }, { "code": "/*Store this code in 'style.css' file inside the 'static' folder*/ .logincontent{ margin: 0 auto; height: 500px; width: 400px; background-color: #e6ffee; border-radius: 10px;} .registercontent{ margin: 0 auto; height: 720px; width: 400px; background-color: #e6ffee; border-radius: 10px;} .logintop{ height: 60px; width: 400px; background-color: #009933; color: #ffffff;} .registertop{ height: 60px; width: 400px; background-color: #009933; color: #ffffff;} .textbox{ padding: 10px 40px; background-color: #009933; border-radius: 10px;} ::placeholder { color: #FFFFFF; opacity: 1; font-style: oblique; font-weight: bold;} .btn { padding: 10px 40px; background-color: #009933; color: #FFFFFF; font-style: oblique; font-weight: bold; border-radius: 10px;} .worddark{ color: #009933; font-style: oblique; font-weight: bold;} .wordlight{ color: #FFFFFF; font-style: oblique; font-weight: bold;} *{ margin: 0; padding: 0; box-sizing: border-box; list-style: none; text-decoration: none; font-family: 'Josefin Sans', sans-serif;} .one{ display: flex; position: relative;} .one .two{ width: 225px; height: 100%; background: #009933; padding: 30px 0px; position: fixed;} .one .two h1{ color: #fff; text-transform: uppercase; text-align: center; margin-bottom: 30px; font-style: oblique; font-weight: bold;} .one .two h2{ color: #fff; text-align: center;} .one .two .active{ background: #0a8032;} .one .two ul li{ text-align: center; padding: 15px; border-bottom: 0.1px solid white; border-top: 0.1px solid white;} .one .two ul li a{ color: #ffffff; display: block;} .one .two ul li a .side{ width: 25px; align:center;} .one .content{ width: 100%; margin-left: 200px;} .one .content .topbar{ text-align: center; padding: 20px; background: #00b33c; color: white;} .one .content .contentbar{ margin: auto;} .one .content .contentbar h1{ color: #11a844; text-align: center; font-style: oblique; font-weight: bold;}", "e": 20645, "s": 18451, "text": null }, { "code": null, "e": 20697, "s": 20645, "text": "Step-11: The project structure will look like this." }, { "code": null, "e": 20717, "s": 20697, "text": "(4) Run the Project" }, { "code": null, "e": 20741, "s": 20717, "text": "Step-1: Run the server." }, { "code": null, "e": 20782, "s": 20741, "text": "Step-2: Browse the URL ‘localhost:5000’." }, { "code": null, "e": 20829, "s": 20782, "text": "Step-3: The output web page will be displayed." }, { "code": null, "e": 20860, "s": 20829, "text": "(5) Testing of the Application" }, { "code": null, "e": 20930, "s": 20860, "text": "Step-1: If you are new user, go to sign up page and fill the details." }, { "code": null, "e": 21022, "s": 20930, "text": "Step-2: After registration, go to login page. Enter your username and password and sign in." }, { "code": null, "e": 21124, "s": 21022, "text": "Step-3: If your login is successful, you will be moved to index page and your name will be displayed." }, { "code": null, "e": 21235, "s": 21124, "text": "Step-4: You can view your profile details in display page and also you can update your details in update page." }, { "code": null, "e": 21254, "s": 21235, "text": "Output:Login page:" }, { "code": null, "e": 21269, "s": 21254, "text": "Register page:" }, { "code": null, "e": 21305, "s": 21269, "text": "If login is successful, Index Page:" }, { "code": null, "e": 21318, "s": 21305, "text": "Update Page:" }, { "code": null, "e": 21349, "s": 21318, "text": "Before updation, Display page:" }, { "code": null, "e": 21379, "s": 21349, "text": "After updation, Display page:" }, { "code": null, "e": 21405, "s": 21379, "text": "Database – Before update:" }, { "code": null, "e": 21430, "s": 21405, "text": "Database – After update:" }, { "code": null, "e": 21445, "s": 21430, "text": "Flask Projects" }, { "code": null, "e": 21458, "s": 21445, "text": "Python Flask" }, { "code": null, "e": 21465, "s": 21458, "text": "Python" }, { "code": null, "e": 21482, "s": 21465, "text": "Web Technologies" }, { "code": null, "e": 21580, "s": 21482, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21598, "s": 21580, "text": "Python Dictionary" }, { "code": null, "e": 21640, "s": 21598, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 21662, "s": 21640, "text": "Enumerate() in Python" }, { "code": null, "e": 21697, "s": 21662, "text": "Read a file line by line in Python" }, { "code": null, "e": 21723, "s": 21697, "text": "Python String | replace()" }, { "code": null, "e": 21756, "s": 21723, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 21818, "s": 21756, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 21879, "s": 21818, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 21929, "s": 21879, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
BufferedInputStream read() method in Java with Examples
05 Jun, 2020 read() method of BufferedInputStream class in Java is used to read the next byte of data from the input stream. When this read() method is called on the input stream then this read() method reads one character of the input stream at a time.Syntax:public int read() Overrides:It overrides read() method of FilterInputStream class.Parameters: This method does not accept any parameter.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read() method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream read() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create input stream 'demo.txt' // for reading containing // text "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream("c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read until a single byte is available while (buffInputStr.available() > 0) { // Read the byte and // convert the integer to character char c = (char)buffInputStr.read(); // Print the characters System.out.println("Char : " + c); } }}Input:Output:read(byte[ ] b, int off, int len) method of BufferedInputStream class in Java is used to read bytes from the byte-input stream into the specified byte array which starts at the offset given by user. It is basically used to start reading after preserving the characters in an array.Implementation:In the implementation of this method, read() method is called again and again. While calling this method if an IOException is found then it returns the exception from the call to the read(byte[ ] b, int off, int len) method.If further any IOException is found then it catches the exception and input file is supposed to be ended.The bytes that are read up to that point are stored into byte array b and the number of bytes read before the occurrence of exception is returned.Syntax:public int read(byte[] b, int off, int len) Overrides:It overrides read() method of FilterInputStream class.Parameters: This method accepts three parameters.b – It represents destination buffer.off – It represents offset at which storing bytes would be started.len – It represents the maximum number of bytes to read.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read(byte, int, int) method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream// read(byte int int) method import java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing // text "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream("c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read number of bytes available int rem_byte = buffInputStr.available(); // Byte array is declared byte[] barr = new byte[rem_byte]; // Read byte into barr, // starts at offset 1, // 5 bytes to read buffInputStr.read(barr, 1, 5); // For each byte in barr for (byte b : barr) { if (b == (byte)0) b = (byte)'-'; System.out.print((char)b); } }}Input:Output: read() method of BufferedInputStream class in Java is used to read the next byte of data from the input stream. When this read() method is called on the input stream then this read() method reads one character of the input stream at a time.Syntax:public int read() Overrides:It overrides read() method of FilterInputStream class.Parameters: This method does not accept any parameter.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read() method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream read() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create input stream 'demo.txt' // for reading containing // text "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream("c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read until a single byte is available while (buffInputStr.available() > 0) { // Read the byte and // convert the integer to character char c = (char)buffInputStr.read(); // Print the characters System.out.println("Char : " + c); } }}Input:Output: Syntax: public int read() Overrides:It overrides read() method of FilterInputStream class. Parameters: This method does not accept any parameter. Return value: This method does not return any value. Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs. Below program illustrates read() method in BufferedInputStream class in IO package: Program: Assume the existence of file “c:/demo.txt”. // Java program to illustrate// BufferedInputStream read() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create input stream 'demo.txt' // for reading containing // text "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream("c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read until a single byte is available while (buffInputStr.available() > 0) { // Read the byte and // convert the integer to character char c = (char)buffInputStr.read(); // Print the characters System.out.println("Char : " + c); } }} read(byte[ ] b, int off, int len) method of BufferedInputStream class in Java is used to read bytes from the byte-input stream into the specified byte array which starts at the offset given by user. It is basically used to start reading after preserving the characters in an array.Implementation:In the implementation of this method, read() method is called again and again. While calling this method if an IOException is found then it returns the exception from the call to the read(byte[ ] b, int off, int len) method.If further any IOException is found then it catches the exception and input file is supposed to be ended.The bytes that are read up to that point are stored into byte array b and the number of bytes read before the occurrence of exception is returned.Syntax:public int read(byte[] b, int off, int len) Overrides:It overrides read() method of FilterInputStream class.Parameters: This method accepts three parameters.b – It represents destination buffer.off – It represents offset at which storing bytes would be started.len – It represents the maximum number of bytes to read.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read(byte, int, int) method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream// read(byte int int) method import java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing // text "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream("c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read number of bytes available int rem_byte = buffInputStr.available(); // Byte array is declared byte[] barr = new byte[rem_byte]; // Read byte into barr, // starts at offset 1, // 5 bytes to read buffInputStr.read(barr, 1, 5); // For each byte in barr for (byte b : barr) { if (b == (byte)0) b = (byte)'-'; System.out.print((char)b); } }}Input:Output: Implementation: In the implementation of this method, read() method is called again and again. While calling this method if an IOException is found then it returns the exception from the call to the read(byte[ ] b, int off, int len) method. If further any IOException is found then it catches the exception and input file is supposed to be ended. The bytes that are read up to that point are stored into byte array b and the number of bytes read before the occurrence of exception is returned. Syntax: public int read(byte[] b, int off, int len) Overrides:It overrides read() method of FilterInputStream class. Parameters: This method accepts three parameters. b – It represents destination buffer. off – It represents offset at which storing bytes would be started. len – It represents the maximum number of bytes to read. Return value: This method does not return any value. Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs. Below program illustrates read(byte, int, int) method in BufferedInputStream class in IO package: Program: Assume the existence of file “c:/demo.txt”. // Java program to illustrate// BufferedInputStream// read(byte int int) method import java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing // text "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream("c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read number of bytes available int rem_byte = buffInputStr.available(); // Byte array is declared byte[] barr = new byte[rem_byte]; // Read byte into barr, // starts at offset 1, // 5 bytes to read buffInputStr.read(barr, 1, 5); // For each byte in barr for (byte b : barr) { if (b == (byte)0) b = (byte)'-'; System.out.print((char)b); } }} References:1. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#read()2. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#read(byte%5B%5D, int, int) Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Multidimensional Arrays in Java Collections in Java Stream In Java Set in Java Singleton Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 4072, "s": 28, "text": "read() method of BufferedInputStream class in Java is used to read the next byte of data from the input stream. When this read() method is called on the input stream then this read() method reads one character of the input stream at a time.Syntax:public int read()\nOverrides:It overrides read() method of FilterInputStream class.Parameters: This method does not accept any parameter.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read() method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream read() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create input stream 'demo.txt' // for reading containing // text \"GEEKSFORGEEKS\" FileInputStream inputStream = new FileInputStream(\"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read until a single byte is available while (buffInputStr.available() > 0) { // Read the byte and // convert the integer to character char c = (char)buffInputStr.read(); // Print the characters System.out.println(\"Char : \" + c); } }}Input:Output:read(byte[ ] b, int off, int len) method of BufferedInputStream class in Java is used to read bytes from the byte-input stream into the specified byte array which starts at the offset given by user. It is basically used to start reading after preserving the characters in an array.Implementation:In the implementation of this method, read() method is called again and again. While calling this method if an IOException is found then it returns the exception from the call to the read(byte[ ] b, int off, int len) method.If further any IOException is found then it catches the exception and input file is supposed to be ended.The bytes that are read up to that point are stored into byte array b and the number of bytes read before the occurrence of exception is returned.Syntax:public int read(byte[] b,\n int off,\n int len)\nOverrides:It overrides read() method of FilterInputStream class.Parameters: This method accepts three parameters.b – It represents destination buffer.off – It represents offset at which storing bytes would be started.len – It represents the maximum number of bytes to read.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read(byte, int, int) method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream// read(byte int int) method import java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing // text \"GEEKSFORGEEKS\" FileInputStream inputStream = new FileInputStream(\"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read number of bytes available int rem_byte = buffInputStr.available(); // Byte array is declared byte[] barr = new byte[rem_byte]; // Read byte into barr, // starts at offset 1, // 5 bytes to read buffInputStr.read(barr, 1, 5); // For each byte in barr for (byte b : barr) { if (b == (byte)0) b = (byte)'-'; System.out.print((char)b); } }}Input:Output:" }, { "code": null, "e": 5648, "s": 4072, "text": "read() method of BufferedInputStream class in Java is used to read the next byte of data from the input stream. When this read() method is called on the input stream then this read() method reads one character of the input stream at a time.Syntax:public int read()\nOverrides:It overrides read() method of FilterInputStream class.Parameters: This method does not accept any parameter.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read() method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream read() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create input stream 'demo.txt' // for reading containing // text \"GEEKSFORGEEKS\" FileInputStream inputStream = new FileInputStream(\"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read until a single byte is available while (buffInputStr.available() > 0) { // Read the byte and // convert the integer to character char c = (char)buffInputStr.read(); // Print the characters System.out.println(\"Char : \" + c); } }}Input:Output:" }, { "code": null, "e": 5656, "s": 5648, "text": "Syntax:" }, { "code": null, "e": 5675, "s": 5656, "text": "public int read()\n" }, { "code": null, "e": 5740, "s": 5675, "text": "Overrides:It overrides read() method of FilterInputStream class." }, { "code": null, "e": 5795, "s": 5740, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 5848, "s": 5795, "text": "Return value: This method does not return any value." }, { "code": null, "e": 5981, "s": 5848, "text": "Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs." }, { "code": null, "e": 6065, "s": 5981, "text": "Below program illustrates read() method in BufferedInputStream class in IO package:" }, { "code": null, "e": 6118, "s": 6065, "text": "Program: Assume the existence of file “c:/demo.txt”." }, { "code": "// Java program to illustrate// BufferedInputStream read() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create input stream 'demo.txt' // for reading containing // text \"GEEKSFORGEEKS\" FileInputStream inputStream = new FileInputStream(\"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read until a single byte is available while (buffInputStr.available() > 0) { // Read the byte and // convert the integer to character char c = (char)buffInputStr.read(); // Print the characters System.out.println(\"Char : \" + c); } }}", "e": 6979, "s": 6118, "text": null }, { "code": null, "e": 9448, "s": 6979, "text": "read(byte[ ] b, int off, int len) method of BufferedInputStream class in Java is used to read bytes from the byte-input stream into the specified byte array which starts at the offset given by user. It is basically used to start reading after preserving the characters in an array.Implementation:In the implementation of this method, read() method is called again and again. While calling this method if an IOException is found then it returns the exception from the call to the read(byte[ ] b, int off, int len) method.If further any IOException is found then it catches the exception and input file is supposed to be ended.The bytes that are read up to that point are stored into byte array b and the number of bytes read before the occurrence of exception is returned.Syntax:public int read(byte[] b,\n int off,\n int len)\nOverrides:It overrides read() method of FilterInputStream class.Parameters: This method accepts three parameters.b – It represents destination buffer.off – It represents offset at which storing bytes would be started.len – It represents the maximum number of bytes to read.Return value: This method does not return any value.Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs.Below program illustrates read(byte, int, int) method in BufferedInputStream class in IO package:Program: Assume the existence of file “c:/demo.txt”.// Java program to illustrate// BufferedInputStream// read(byte int int) method import java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing // text \"GEEKSFORGEEKS\" FileInputStream inputStream = new FileInputStream(\"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read number of bytes available int rem_byte = buffInputStr.available(); // Byte array is declared byte[] barr = new byte[rem_byte]; // Read byte into barr, // starts at offset 1, // 5 bytes to read buffInputStr.read(barr, 1, 5); // For each byte in barr for (byte b : barr) { if (b == (byte)0) b = (byte)'-'; System.out.print((char)b); } }}Input:Output:" }, { "code": null, "e": 9464, "s": 9448, "text": "Implementation:" }, { "code": null, "e": 9689, "s": 9464, "text": "In the implementation of this method, read() method is called again and again. While calling this method if an IOException is found then it returns the exception from the call to the read(byte[ ] b, int off, int len) method." }, { "code": null, "e": 9795, "s": 9689, "text": "If further any IOException is found then it catches the exception and input file is supposed to be ended." }, { "code": null, "e": 9942, "s": 9795, "text": "The bytes that are read up to that point are stored into byte array b and the number of bytes read before the occurrence of exception is returned." }, { "code": null, "e": 9950, "s": 9942, "text": "Syntax:" }, { "code": null, "e": 10027, "s": 9950, "text": "public int read(byte[] b,\n int off,\n int len)\n" }, { "code": null, "e": 10092, "s": 10027, "text": "Overrides:It overrides read() method of FilterInputStream class." }, { "code": null, "e": 10142, "s": 10092, "text": "Parameters: This method accepts three parameters." }, { "code": null, "e": 10180, "s": 10142, "text": "b – It represents destination buffer." }, { "code": null, "e": 10248, "s": 10180, "text": "off – It represents offset at which storing bytes would be started." }, { "code": null, "e": 10305, "s": 10248, "text": "len – It represents the maximum number of bytes to read." }, { "code": null, "e": 10358, "s": 10305, "text": "Return value: This method does not return any value." }, { "code": null, "e": 10491, "s": 10358, "text": "Exception: This method throws IOException if the input stream has been closed by invoking its close() method or an I/O error occurs." }, { "code": null, "e": 10589, "s": 10491, "text": "Below program illustrates read(byte, int, int) method in BufferedInputStream class in IO package:" }, { "code": null, "e": 10642, "s": 10589, "text": "Program: Assume the existence of file “c:/demo.txt”." }, { "code": "// Java program to illustrate// BufferedInputStream// read(byte int int) method import java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing // text \"GEEKSFORGEEKS\" FileInputStream inputStream = new FileInputStream(\"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read number of bytes available int rem_byte = buffInputStr.available(); // Byte array is declared byte[] barr = new byte[rem_byte]; // Read byte into barr, // starts at offset 1, // 5 bytes to read buffInputStr.read(barr, 1, 5); // For each byte in barr for (byte b : barr) { if (b == (byte)0) b = (byte)'-'; System.out.print((char)b); } }}", "e": 11638, "s": 10642, "text": null }, { "code": null, "e": 11840, "s": 11638, "text": "References:1. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#read()2. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#read(byte%5B%5D, int, int)" }, { "code": null, "e": 11855, "s": 11840, "text": "Java-Functions" }, { "code": null, "e": 11871, "s": 11855, "text": "Java-IO package" }, { "code": null, "e": 11876, "s": 11871, "text": "Java" }, { "code": null, "e": 11881, "s": 11876, "text": "Java" }, { "code": null, "e": 11979, "s": 11881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12030, "s": 11979, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 12061, "s": 12030, "text": "How to iterate any Map in Java" }, { "code": null, "e": 12080, "s": 12061, "text": "Interfaces in Java" }, { "code": null, "e": 12110, "s": 12080, "text": "HashMap in Java with Examples" }, { "code": null, "e": 12128, "s": 12110, "text": "ArrayList in Java" }, { "code": null, "e": 12160, "s": 12128, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 12180, "s": 12160, "text": "Collections in Java" }, { "code": null, "e": 12195, "s": 12180, "text": "Stream In Java" }, { "code": null, "e": 12207, "s": 12195, "text": "Set in Java" } ]
Java Program to Convert Octal to Binary
25 Aug, 2021 Given an Octal number as input, the task is to convert that number into its Binary equivalent number. Example: Input: Octal Number = 513 Output: Binary equivalent value is: 101001011 Explanation : Binary equivalent value of 5: 101 Binary equivalent value of 1: 001 Binary equivalent value of 3: 011 Octal Number System: The Octal number system is a positional numeral system with a radix, or base, of 8 and uses eight distinct digits 0 to 7. Binary Number System: A Binary number is a number expressed in the base-2 binary numeral system, which uses only two symbols: which are 0 and 1. Octal to Binary Conversion Table: Method 1: Naive Approach In this approach, the input of Octal number will be taken as a string. Further, the complete string will be iterated character by character and for each character(ie., octal digit), its equivalent binary value according to the above octal to binary conversion table will be evaluated. The result of each iteration will be added in the resultant string and the combination of all values will give the required binary number. Below is the implementation of this approach. Java // Java program to convert// Octal number to Binary class OctalToBinary { // function to convert octal number // to its binary equivalent value static String converter(String octalValue) { // integer variable to iterate // the input octal string int i = 0; // string to store the result String binaryValue = ""; // iterating the complete length // of octal string and assigning // the equivalent binary value // for each octal digit while (i < octalValue.length()) { // storing character according // to the number of iteration char c = octalValue.charAt((int)i); // switch case to check all // possible 8 conditions switch (c) { case '0': binaryValue += "000"; break; case '1': binaryValue += "001"; break; case '2': binaryValue += "010"; break; case '3': binaryValue += "011"; break; case '4': binaryValue += "100"; break; case '5': binaryValue += "101"; break; case '6': binaryValue += "110"; break; case '7': binaryValue += "111"; break; default: System.out.println( "\nInvalid Octal Digit " + octalValue.charAt((int)i)); break; } i++; } // returning the final result return binaryValue; } // Driver code public static void main(String args[]) { System.out.println("Octal to Binary Conversion\n"); // octal number which is to be converted String octalNumber = "315"; System.out.println("Octal number: " + octalNumber); // calling the converter method and // storing the result in a string variable String result = converter(octalNumber); System.out.println("Binary equivalent value is: " + result); }} Octal to Binary Conversion Octal number: 315 Binary equivalent value is: 011001101 Method 2: Mathematical Approach This method involves complete mathematical calculations to obtain the desired result. The input of the Octal number will be taken as an integer. Further, it is first converted into its decimal equivalent value and then from a decimal number to its binary equivalent using mathematical operations. Below is the implementation of this approach. Java // Java program to convert// Octal number to Binarypublic class OctalToBinary { // function to convert octal number // to its binary equivalent value public static int converter(int octalValue) { // declaring all variable // to store the intermediate results int i = 0; int decimalValue = 0; int binaryValue = 0; // converting octal number // into its decimal equivalent while (octalValue != 0) { decimalValue += (octalValue % 10) * Math.pow(8, i); ++i; octalValue /= 10; } i = 1; // converting generated decimal number // to its binary equivalent while (decimalValue != 0) { binaryValue += (decimalValue % 2) * i; decimalValue /= 2; i *= 10; } // returning the final result return binaryValue; } // Driver code public static void main(String[] args) { System.out.println("Octal to Binary Conversion\n"); // octal number which is to be converted int octalNumber = 315; System.out.println("Octal number: " + octalNumber); // calling the converter method and // storing the result in a string variable int result = converter(octalNumber); // printing the binary equivalent value System.out.println("Binary equivalent value is: " + result); }} Octal to Binary Conversion Octal number: 315 Binary equivalent value is: 11001101 Method 3: Using inbuilt java methods Integer.parseInt() is an in-built function in Java to parse a string into a number system specified by the radix value(2nd argument of the method). In this approach, the input of the Octal number will be taken as a string. The octal string will be parsed into an integer value of octal number system. Further, the octal number will be converted into its binary equivalent using another inbuilt method Integer.toBinaryString(). The resultant value will also be of string datatype. Below is the implementation. Java // Java program to convert// Octal number to Binaryclass OctalToBinary { // function to convert octal number // to its binary equivalent value public static String converter(String octalValue) { // parsing the string value // by following octal number system int octal = Integer.parseInt(octalValue, 8); // converting octal number to binary // and storing as a string String binaryValue = Integer.toBinaryString(octal); // returning the resultant string return binaryValue; } // Driver code public static void main(String args[]) { System.out.println("Octal to Binary Conversion\n"); // octal number which is to be converted String octalNumber = "315"; System.out.println("Octal number: " + octalNumber); // calling the converter method and // storing the result in a string variable String result = converter(octalNumber); // printing the binary equivalent value System.out.println("Binary equivalent value is: " + result); }} Octal to Binary Conversion Octal number: 315 Binary equivalent value is: 11001101 arorakashish0911 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Aug, 2021" }, { "code": null, "e": 154, "s": 52, "text": "Given an Octal number as input, the task is to convert that number into its Binary equivalent number." }, { "code": null, "e": 163, "s": 154, "text": "Example:" }, { "code": null, "e": 354, "s": 163, "text": "Input: Octal Number = 513\nOutput: Binary equivalent value is: 101001011\n\nExplanation : \nBinary equivalent value of 5: 101\nBinary equivalent value of 1: 001\n\nBinary equivalent value of 3: 011" }, { "code": null, "e": 376, "s": 354, "text": "Octal Number System: " }, { "code": null, "e": 498, "s": 376, "text": "The Octal number system is a positional numeral system with a radix, or base, of 8 and uses eight distinct digits 0 to 7." }, { "code": null, "e": 520, "s": 498, "text": "Binary Number System:" }, { "code": null, "e": 643, "s": 520, "text": "A Binary number is a number expressed in the base-2 binary numeral system, which uses only two symbols: which are 0 and 1." }, { "code": null, "e": 677, "s": 643, "text": "Octal to Binary Conversion Table:" }, { "code": null, "e": 702, "s": 677, "text": "Method 1: Naive Approach" }, { "code": null, "e": 1173, "s": 702, "text": "In this approach, the input of Octal number will be taken as a string. Further, the complete string will be iterated character by character and for each character(ie., octal digit), its equivalent binary value according to the above octal to binary conversion table will be evaluated. The result of each iteration will be added in the resultant string and the combination of all values will give the required binary number. Below is the implementation of this approach. " }, { "code": null, "e": 1178, "s": 1173, "text": "Java" }, { "code": "// Java program to convert// Octal number to Binary class OctalToBinary { // function to convert octal number // to its binary equivalent value static String converter(String octalValue) { // integer variable to iterate // the input octal string int i = 0; // string to store the result String binaryValue = \"\"; // iterating the complete length // of octal string and assigning // the equivalent binary value // for each octal digit while (i < octalValue.length()) { // storing character according // to the number of iteration char c = octalValue.charAt((int)i); // switch case to check all // possible 8 conditions switch (c) { case '0': binaryValue += \"000\"; break; case '1': binaryValue += \"001\"; break; case '2': binaryValue += \"010\"; break; case '3': binaryValue += \"011\"; break; case '4': binaryValue += \"100\"; break; case '5': binaryValue += \"101\"; break; case '6': binaryValue += \"110\"; break; case '7': binaryValue += \"111\"; break; default: System.out.println( \"\\nInvalid Octal Digit \" + octalValue.charAt((int)i)); break; } i++; } // returning the final result return binaryValue; } // Driver code public static void main(String args[]) { System.out.println(\"Octal to Binary Conversion\\n\"); // octal number which is to be converted String octalNumber = \"315\"; System.out.println(\"Octal number: \" + octalNumber); // calling the converter method and // storing the result in a string variable String result = converter(octalNumber); System.out.println(\"Binary equivalent value is: \" + result); }}", "e": 3391, "s": 1178, "text": null }, { "code": null, "e": 3475, "s": 3391, "text": "Octal to Binary Conversion\n\nOctal number: 315\nBinary equivalent value is: 011001101" }, { "code": null, "e": 3508, "s": 3475, "text": "Method 2: Mathematical Approach " }, { "code": null, "e": 3851, "s": 3508, "text": "This method involves complete mathematical calculations to obtain the desired result. The input of the Octal number will be taken as an integer. Further, it is first converted into its decimal equivalent value and then from a decimal number to its binary equivalent using mathematical operations. Below is the implementation of this approach." }, { "code": null, "e": 3856, "s": 3851, "text": "Java" }, { "code": "// Java program to convert// Octal number to Binarypublic class OctalToBinary { // function to convert octal number // to its binary equivalent value public static int converter(int octalValue) { // declaring all variable // to store the intermediate results int i = 0; int decimalValue = 0; int binaryValue = 0; // converting octal number // into its decimal equivalent while (octalValue != 0) { decimalValue += (octalValue % 10) * Math.pow(8, i); ++i; octalValue /= 10; } i = 1; // converting generated decimal number // to its binary equivalent while (decimalValue != 0) { binaryValue += (decimalValue % 2) * i; decimalValue /= 2; i *= 10; } // returning the final result return binaryValue; } // Driver code public static void main(String[] args) { System.out.println(\"Octal to Binary Conversion\\n\"); // octal number which is to be converted int octalNumber = 315; System.out.println(\"Octal number: \" + octalNumber); // calling the converter method and // storing the result in a string variable int result = converter(octalNumber); // printing the binary equivalent value System.out.println(\"Binary equivalent value is: \" + result); }}", "e": 5317, "s": 3856, "text": null }, { "code": null, "e": 5400, "s": 5317, "text": "Octal to Binary Conversion\n\nOctal number: 315\nBinary equivalent value is: 11001101" }, { "code": null, "e": 5437, "s": 5400, "text": "Method 3: Using inbuilt java methods" }, { "code": null, "e": 5946, "s": 5437, "text": "Integer.parseInt() is an in-built function in Java to parse a string into a number system specified by the radix value(2nd argument of the method). In this approach, the input of the Octal number will be taken as a string. The octal string will be parsed into an integer value of octal number system. Further, the octal number will be converted into its binary equivalent using another inbuilt method Integer.toBinaryString(). The resultant value will also be of string datatype. Below is the implementation." }, { "code": null, "e": 5951, "s": 5946, "text": "Java" }, { "code": "// Java program to convert// Octal number to Binaryclass OctalToBinary { // function to convert octal number // to its binary equivalent value public static String converter(String octalValue) { // parsing the string value // by following octal number system int octal = Integer.parseInt(octalValue, 8); // converting octal number to binary // and storing as a string String binaryValue = Integer.toBinaryString(octal); // returning the resultant string return binaryValue; } // Driver code public static void main(String args[]) { System.out.println(\"Octal to Binary Conversion\\n\"); // octal number which is to be converted String octalNumber = \"315\"; System.out.println(\"Octal number: \" + octalNumber); // calling the converter method and // storing the result in a string variable String result = converter(octalNumber); // printing the binary equivalent value System.out.println(\"Binary equivalent value is: \" + result); }}", "e": 7060, "s": 5951, "text": null }, { "code": null, "e": 7143, "s": 7060, "text": "Octal to Binary Conversion\n\nOctal number: 315\nBinary equivalent value is: 11001101" }, { "code": null, "e": 7160, "s": 7143, "text": "arorakashish0911" }, { "code": null, "e": 7167, "s": 7160, "text": "Picked" }, { "code": null, "e": 7191, "s": 7167, "text": "Technical Scripter 2020" }, { "code": null, "e": 7196, "s": 7191, "text": "Java" }, { "code": null, "e": 7210, "s": 7196, "text": "Java Programs" }, { "code": null, "e": 7229, "s": 7210, "text": "Technical Scripter" }, { "code": null, "e": 7234, "s": 7229, "text": "Java" }, { "code": null, "e": 7332, "s": 7234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7347, "s": 7332, "text": "Stream In Java" }, { "code": null, "e": 7368, "s": 7347, "text": "Introduction to Java" }, { "code": null, "e": 7389, "s": 7368, "text": "Constructors in Java" }, { "code": null, "e": 7408, "s": 7389, "text": "Exceptions in Java" }, { "code": null, "e": 7425, "s": 7408, "text": "Generics in Java" }, { "code": null, "e": 7451, "s": 7425, "text": "Java Programming Examples" }, { "code": null, "e": 7485, "s": 7451, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 7532, "s": 7485, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 7570, "s": 7532, "text": "Factory method design pattern in Java" } ]
How to make a Animated Table using HTML and CSS ?
26 May, 2021 Table is an arrangement of data in rows and columns, or possibly in a more complex structure. Tables are widely used in communication, research, and data analysis. In this article, we are going to create a Table with animation over its columns. We are going to implement it using HTML and CSS. Approach: Step by step implementation: Step 1: Create Structure of Table using HTML: We will create a table structure using a table tag in HTML. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- Set title of web page --> <title>GFG Animated Table</title></head> <body> <!-- Creating the structure of table --> <table> <tr> <!-- Creating heading of table --> <th>Employee Name</th> <th>Job Type</th> <th>Working Hour</th> <th>Salary</th> </tr> <tr> <!-- Add 1st data to table --> <td>Peter</td> <td>Intern</td> <td>8 Hour</td> <td>10000 Rs</td> </tr> <tr> <!-- Add 2nd data to table --> <td>Liza</td> <td>Employee</td> <td>10 Hour</td> <td>30000 Rs</td> </tr> <tr> <!-- Add 3rd data to table --> <td>John</td> <td>Employee</td> <td>10 Hour</td> <td>35000 Rs</td> </tr> </table></body> </html> Step 2: Decorating Table using CSS: Now, we will apply CSS over the table which we have created earlier. /* Set the content of table usingcss properties */table { width: 700px; margin: auto; text-align: center; table-layout: fixed;} /* Applying css properties to table components */table,td,tr { padding: 12px; color: wheat; background: indigo; border: 1px solid black; border-collapse: collapse; font-size: 20px; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;} /* Apply css properties to th */th { color: white; border: 1px solid black; border-collapse: collapse; background: cadetblue;} /* Apply hover effect to td */td:hover { background: orangered;} Complete Code: Complete HTML code is given as an example for your help. Comments are added in the code for better understanding. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- Set title of web page --> <title>GFG Animated Table</title> <style> /* Set the content of table using css properties */ table { width: 700px; margin: auto; text-align: center; table-layout: fixed; } /* Applying css properties to table components */ table, td, tr { padding: 12px; color: wheat; background: indigo; border: 1px solid black; border-collapse: collapse; font-size: 20px; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; } /* Apply css properties to th */ th { color: white; border: 1px solid black; border-collapse: collapse; background: cadetblue; } /* Apply hover effect to td */ td:hover { background: orangered; } </style></head> <body> <!-- Creating the structure of table --> <table> <tr> <!-- Creating heading of table --> <th>Employee Name</th> <th>Job Type</th> <th>Working Hour</th> <th>Salary</th> </tr> <tr> <!-- Add 1st data to table --> <td>Peter</td> <td>Intern</td> <td>8 Hour</td> <td>10000 Rs</td> </tr> <tr> <!-- Add 2nd data to table --> <td>Liza</td> <td>Employee</td> <td>10 Hour</td> <td>30000 Rs</td> </tr> <tr> <!-- Add 3rd data to table --> <td>John</td> <td>Employee</td> <td>10 Hour</td> <td>35000 Rs</td> </tr> </table></body> </html> Output: Animated table CSS-Properties CSS-Questions HTML-Questions HTML-Tags CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 May, 2021" }, { "code": null, "e": 218, "s": 53, "text": " Table is an arrangement of data in rows and columns, or possibly in a more complex structure. Tables are widely used in communication, research, and data analysis." }, { "code": null, "e": 350, "s": 218, "text": " In this article, we are going to create a Table with animation over its columns. We are going to implement it using HTML and CSS. " }, { "code": null, "e": 389, "s": 350, "text": "Approach: Step by step implementation:" }, { "code": null, "e": 496, "s": 389, "text": "Step 1: Create Structure of Table using HTML: We will create a table structure using a table tag in HTML. " }, { "code": null, "e": 503, "s": 498, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- Set title of web page --> <title>GFG Animated Table</title></head> <body> <!-- Creating the structure of table --> <table> <tr> <!-- Creating heading of table --> <th>Employee Name</th> <th>Job Type</th> <th>Working Hour</th> <th>Salary</th> </tr> <tr> <!-- Add 1st data to table --> <td>Peter</td> <td>Intern</td> <td>8 Hour</td> <td>10000 Rs</td> </tr> <tr> <!-- Add 2nd data to table --> <td>Liza</td> <td>Employee</td> <td>10 Hour</td> <td>30000 Rs</td> </tr> <tr> <!-- Add 3rd data to table --> <td>John</td> <td>Employee</td> <td>10 Hour</td> <td>35000 Rs</td> </tr> </table></body> </html>", "e": 1621, "s": 503, "text": null }, { "code": null, "e": 1726, "s": 1621, "text": "Step 2: Decorating Table using CSS: Now, we will apply CSS over the table which we have created earlier." }, { "code": "/* Set the content of table usingcss properties */table { width: 700px; margin: auto; text-align: center; table-layout: fixed;} /* Applying css properties to table components */table,td,tr { padding: 12px; color: wheat; background: indigo; border: 1px solid black; border-collapse: collapse; font-size: 20px; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;} /* Apply css properties to th */th { color: white; border: 1px solid black; border-collapse: collapse; background: cadetblue;} /* Apply hover effect to td */td:hover { background: orangered;}", "e": 2430, "s": 1726, "text": null }, { "code": null, "e": 2559, "s": 2430, "text": "Complete Code: Complete HTML code is given as an example for your help. Comments are added in the code for better understanding." }, { "code": null, "e": 2564, "s": 2559, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- Set title of web page --> <title>GFG Animated Table</title> <style> /* Set the content of table using css properties */ table { width: 700px; margin: auto; text-align: center; table-layout: fixed; } /* Applying css properties to table components */ table, td, tr { padding: 12px; color: wheat; background: indigo; border: 1px solid black; border-collapse: collapse; font-size: 20px; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; } /* Apply css properties to th */ th { color: white; border: 1px solid black; border-collapse: collapse; background: cadetblue; } /* Apply hover effect to td */ td:hover { background: orangered; } </style></head> <body> <!-- Creating the structure of table --> <table> <tr> <!-- Creating heading of table --> <th>Employee Name</th> <th>Job Type</th> <th>Working Hour</th> <th>Salary</th> </tr> <tr> <!-- Add 1st data to table --> <td>Peter</td> <td>Intern</td> <td>8 Hour</td> <td>10000 Rs</td> </tr> <tr> <!-- Add 2nd data to table --> <td>Liza</td> <td>Employee</td> <td>10 Hour</td> <td>30000 Rs</td> </tr> <tr> <!-- Add 3rd data to table --> <td>John</td> <td>Employee</td> <td>10 Hour</td> <td>35000 Rs</td> </tr> </table></body> </html>", "e": 4720, "s": 2564, "text": null }, { "code": null, "e": 4728, "s": 4720, "text": "Output:" }, { "code": null, "e": 4743, "s": 4728, "text": "Animated table" }, { "code": null, "e": 4758, "s": 4743, "text": "CSS-Properties" }, { "code": null, "e": 4772, "s": 4758, "text": "CSS-Questions" }, { "code": null, "e": 4787, "s": 4772, "text": "HTML-Questions" }, { "code": null, "e": 4797, "s": 4787, "text": "HTML-Tags" }, { "code": null, "e": 4801, "s": 4797, "text": "CSS" }, { "code": null, "e": 4806, "s": 4801, "text": "HTML" }, { "code": null, "e": 4823, "s": 4806, "text": "Web Technologies" }, { "code": null, "e": 4828, "s": 4823, "text": "HTML" } ]
What does the cascading portion of CSS means ?
08 Oct, 2021 CSS simplifies the task of maintaining a web document by separating its style information, which includes font size, font color, line width, and background color. This separation allows you to apply the same style rules to multiple web pages. CSS allows you to apply a style multiple times on a single web page. The style in a CSS file is defined according to the rules of CSS recommendation that suggests how a web page should be presented. A CSS file contains the style code for the structure, which includes a heading, listing, paragraph, and links. Now talking about Cascading in CSS means the styling rules. This is the part where CSS can become unnecessarily complicated, even if the ability to use the cascading is occasionally useful. So, let’s start this by asking a question, “What if you have two CSS classes that have conflicting properties?” Which one “wins” and is applied? Let’s look a the below example. Example: HTML <!DOCTYPE html><html lang="en"> <head> <style> h1 { font-size: 40px; text-align: center; color: red; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>The second style gets applied because it is applied after the first.</p> </body> </html> Output: We have two color properties with the same h1 tag. So which one gets applied? Here comes the role of C in CSS, Since they’re equal, the one that comes last wins. So in this case, the h1 would be green. So remember the rule: when everything is equal, the last one gets applied. What does C in CSS stand for? CASCADING. So cascading means, if we list a style earlier in the document and we say it’s one way, and then later in the document, we can say it’s a different way, the thing that’s later in the document wins. Styles of higher precedence will override the rules of lower precedence. CSS-Properties CSS-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 581, "s": 28, "text": "CSS simplifies the task of maintaining a web document by separating its style information, which includes font size, font color, line width, and background color. This separation allows you to apply the same style rules to multiple web pages. CSS allows you to apply a style multiple times on a single web page. The style in a CSS file is defined according to the rules of CSS recommendation that suggests how a web page should be presented. A CSS file contains the style code for the structure, which includes a heading, listing, paragraph, and links." }, { "code": null, "e": 771, "s": 581, "text": "Now talking about Cascading in CSS means the styling rules. This is the part where CSS can become unnecessarily complicated, even if the ability to use the cascading is occasionally useful." }, { "code": null, "e": 948, "s": 771, "text": "So, let’s start this by asking a question, “What if you have two CSS classes that have conflicting properties?” Which one “wins” and is applied? Let’s look a the below example." }, { "code": null, "e": 957, "s": 948, "text": "Example:" }, { "code": null, "e": 962, "s": 957, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> h1 { font-size: 40px; text-align: center; color: red; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>The second style gets applied because it is applied after the first.</p> </body> </html>", "e": 1319, "s": 962, "text": null }, { "code": null, "e": 1329, "s": 1321, "text": "Output:" }, { "code": null, "e": 1606, "s": 1329, "text": "We have two color properties with the same h1 tag. So which one gets applied? Here comes the role of C in CSS, Since they’re equal, the one that comes last wins. So in this case, the h1 would be green. So remember the rule: when everything is equal, the last one gets applied." }, { "code": null, "e": 1918, "s": 1606, "text": "What does C in CSS stand for? CASCADING. So cascading means, if we list a style earlier in the document and we say it’s one way, and then later in the document, we can say it’s a different way, the thing that’s later in the document wins. Styles of higher precedence will override the rules of lower precedence." }, { "code": null, "e": 1933, "s": 1918, "text": "CSS-Properties" }, { "code": null, "e": 1947, "s": 1933, "text": "CSS-Questions" }, { "code": null, "e": 1954, "s": 1947, "text": "Picked" }, { "code": null, "e": 1958, "s": 1954, "text": "CSS" }, { "code": null, "e": 1963, "s": 1958, "text": "HTML" }, { "code": null, "e": 1980, "s": 1963, "text": "Web Technologies" }, { "code": null, "e": 1985, "s": 1980, "text": "HTML" } ]
MySQL | ISNULL( ) Function
19 Nov, 2019 The MySQL ISNULL() function is used for checking whether an expression is NULL or not. This function returns 1 if the expression passed is NULL, else it returns 0. The ISNULL() function accepts the expression as a parameter and returns an integer a value 0 or 1 depending on the parameter passed. Syntax: ISNULL(expression) Parameters Used: expression – It is used to specify the expression. Return Value:The MySQL ISNULL() function returns 1 if the expression passed is a NULL expression, else it returns 0. Supported Versions of MySQL: MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 MySQL 4.0 MySQL 3.23 Example-1: Implementing ISNULL() function. SELECT ISNULL(NULL); Output: 1 Example-2: Implementing ISNULL() function on a string. SELECT ISNULL("gfg"); Output: 0 Example-3: Implementing ISNULL() function on an integer value. SELECT ISNULL(123); Output: 0 mysql SQLmysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Nov, 2019" }, { "code": null, "e": 217, "s": 53, "text": "The MySQL ISNULL() function is used for checking whether an expression is NULL or not. This function returns 1 if the expression passed is NULL, else it returns 0." }, { "code": null, "e": 350, "s": 217, "text": "The ISNULL() function accepts the expression as a parameter and returns an integer a value 0 or 1 depending on the parameter passed." }, { "code": null, "e": 358, "s": 350, "text": "Syntax:" }, { "code": null, "e": 377, "s": 358, "text": "ISNULL(expression)" }, { "code": null, "e": 394, "s": 377, "text": "Parameters Used:" }, { "code": null, "e": 445, "s": 394, "text": "expression – It is used to specify the expression." }, { "code": null, "e": 562, "s": 445, "text": "Return Value:The MySQL ISNULL() function returns 1 if the expression passed is a NULL expression, else it returns 0." }, { "code": null, "e": 591, "s": 562, "text": "Supported Versions of MySQL:" }, { "code": null, "e": 601, "s": 591, "text": "MySQL 5.7" }, { "code": null, "e": 611, "s": 601, "text": "MySQL 5.6" }, { "code": null, "e": 621, "s": 611, "text": "MySQL 5.5" }, { "code": null, "e": 631, "s": 621, "text": "MySQL 5.1" }, { "code": null, "e": 641, "s": 631, "text": "MySQL 5.0" }, { "code": null, "e": 651, "s": 641, "text": "MySQL 4.1" }, { "code": null, "e": 661, "s": 651, "text": "MySQL 4.0" }, { "code": null, "e": 672, "s": 661, "text": "MySQL 3.23" }, { "code": null, "e": 715, "s": 672, "text": "Example-1: Implementing ISNULL() function." }, { "code": null, "e": 737, "s": 715, "text": "SELECT ISNULL(NULL); " }, { "code": null, "e": 745, "s": 737, "text": "Output:" }, { "code": null, "e": 748, "s": 745, "text": "1 " }, { "code": null, "e": 803, "s": 748, "text": "Example-2: Implementing ISNULL() function on a string." }, { "code": null, "e": 826, "s": 803, "text": "SELECT ISNULL(\"gfg\"); " }, { "code": null, "e": 834, "s": 826, "text": "Output:" }, { "code": null, "e": 837, "s": 834, "text": "0 " }, { "code": null, "e": 900, "s": 837, "text": "Example-3: Implementing ISNULL() function on an integer value." }, { "code": null, "e": 921, "s": 900, "text": "SELECT ISNULL(123); " }, { "code": null, "e": 929, "s": 921, "text": "Output:" }, { "code": null, "e": 932, "s": 929, "text": "0 " }, { "code": null, "e": 938, "s": 932, "text": "mysql" }, { "code": null, "e": 947, "s": 938, "text": "SQLmysql" }, { "code": null, "e": 951, "s": 947, "text": "SQL" }, { "code": null, "e": 955, "s": 951, "text": "SQL" } ]
Data Structures in Pandas
18 Oct, 2021 Pandas is an open-source library that uses for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. It offers a tool for cleaning and processes your data. It is the most popular Python library that is used for data analysis. In this article, We are going to learn about Pandas Data structure. It supports two data structures: Series Dataframe Pandas is a one-dimensional labeled array and capable of holding data of any type (integer, string, float, python objects, etc.) Syntax: pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False) Parameters: data: array- Contains data stored in Series. index: array-like or Index (1d) dtype: str, numpy.dtype, or ExtensionDtype, optional name: str, optional copy: bool, default False Example 1: Series holding the char data type. Python3 import pandas as pd # a simple char listlist = ['g', 'e', 'e', 'k', 's'] # create series form a char listres = pd.Series(list)print(res) Output: Example 2: Series holding the Int data type. Python3 import pandas as pd # a simple int listlist = [1,2,3,4,5] # create series form a int listres = pd.Series(list)print(res) Output: Example 3: Series holding the dictionary. Python3 import pandas as pd dic = { 'Id': 1013, 'Name': 'MOhe', 'State': 'Maniput','Age': 24} res = pd.Series(dic)print(res) Output: Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns like a spreadsheet or SQL table, or a dict of Series objects. . Pandas DataFrame consists of three principal components, the data, rows, and columns. In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and from a list of dictionary etc. Dataframe can be created in different ways here are some ways by which we create a dataframe: Example 1: DataFrame can be created using a single list or a list of lists. Python3 # import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)display(df) Output: Example 2: Creating DataFrame from dict of ndarray/lists. To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length. Python3 # Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Create DataFramedf = pd.DataFrame(data) # Print the output.display(df) Output: Selection of column: In Order to select a column in Pandas DataFrame, we can either access the columns by calling them by their columns name. Python3 # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select two columnsprint(df[['Name', 'Qualification']]) Output: Example 1: Selecting rows. pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition provided. Syntax: df.loc[df[‘cname’] ‘condition’] Parameters: df: represents data frame cname: represents column name condition: represents condition on which rows has to be selected Python3 # Importing pandas as pdfrom pandas import DataFrame # Creating a data frameData = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'], 'ID': [12, 43, 54, 32], 'Place': ['Delhi', 'Kochi', 'Pune', 'Patna'] } df = DataFrame(Data, columns = ['Name', 'ID', 'Place']) # Print original data frameprint("Original data frame:\n")display(df) # Selecting the product of Electronic Typeselect_prod = df.loc[df['Name'] == 'Mohe'] print("\n") # Print selected rows based on the conditionprint("Selecting rows:\n")display (select_prod) Output: Example 2: Selecting column. Python3 # Importing pandas as pdfrom pandas import DataFrame # Creating a data frameData = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'], 'ID': [12, 43, 54, 32], 'Place': ['Delhi', 'Kochi', 'Pune', 'Patna'] } df = DataFrame(Data, columns = ['Name', 'ID', 'Place']) # Print original data frameprint("Original data frame:")display(df) print("Selected column: ")display(df[['Name', 'ID']] ) Output: sagartomar9927 varshagumber28 Python pandas-datatypes Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Oct, 2021" }, { "code": null, "e": 461, "s": 52, "text": "Pandas is an open-source library that uses for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. It offers a tool for cleaning and processes your data. It is the most popular Python library that is used for data analysis. In this article, We are going to learn about Pandas Data structure." }, { "code": null, "e": 494, "s": 461, "text": "It supports two data structures:" }, { "code": null, "e": 501, "s": 494, "text": "Series" }, { "code": null, "e": 511, "s": 501, "text": "Dataframe" }, { "code": null, "e": 640, "s": 511, "text": "Pandas is a one-dimensional labeled array and capable of holding data of any type (integer, string, float, python objects, etc.)" }, { "code": null, "e": 736, "s": 640, "text": "Syntax: pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)" }, { "code": null, "e": 748, "s": 736, "text": "Parameters:" }, { "code": null, "e": 793, "s": 748, "text": "data: array- Contains data stored in Series." }, { "code": null, "e": 825, "s": 793, "text": "index: array-like or Index (1d)" }, { "code": null, "e": 878, "s": 825, "text": "dtype: str, numpy.dtype, or ExtensionDtype, optional" }, { "code": null, "e": 898, "s": 878, "text": "name: str, optional" }, { "code": null, "e": 924, "s": 898, "text": "copy: bool, default False" }, { "code": null, "e": 970, "s": 924, "text": "Example 1: Series holding the char data type." }, { "code": null, "e": 978, "s": 970, "text": "Python3" }, { "code": "import pandas as pd # a simple char listlist = ['g', 'e', 'e', 'k', 's'] # create series form a char listres = pd.Series(list)print(res)", "e": 1118, "s": 978, "text": null }, { "code": null, "e": 1129, "s": 1121, "text": "Output:" }, { "code": null, "e": 1178, "s": 1133, "text": "Example 2: Series holding the Int data type." }, { "code": null, "e": 1186, "s": 1178, "text": "Python3" }, { "code": "import pandas as pd # a simple int listlist = [1,2,3,4,5] # create series form a int listres = pd.Series(list)print(res)", "e": 1310, "s": 1186, "text": null }, { "code": null, "e": 1321, "s": 1313, "text": "Output:" }, { "code": null, "e": 1367, "s": 1325, "text": "Example 3: Series holding the dictionary." }, { "code": null, "e": 1375, "s": 1367, "text": "Python3" }, { "code": "import pandas as pd dic = { 'Id': 1013, 'Name': 'MOhe', 'State': 'Maniput','Age': 24} res = pd.Series(dic)print(res)", "e": 1498, "s": 1375, "text": null }, { "code": null, "e": 1509, "s": 1501, "text": "Output:" }, { "code": null, "e": 1915, "s": 1513, "text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns like a spreadsheet or SQL table, or a dict of Series objects. . Pandas DataFrame consists of three principal components, the data, rows, and columns." }, { "code": null, "e": 2260, "s": 1915, "text": "In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and from a list of dictionary etc. Dataframe can be created in different ways here are some ways by which we create a dataframe:" }, { "code": null, "e": 2336, "s": 2260, "text": "Example 1: DataFrame can be created using a single list or a list of lists." }, { "code": null, "e": 2344, "s": 2336, "text": "Python3" }, { "code": "# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)display(df)", "e": 2552, "s": 2344, "text": null }, { "code": null, "e": 2563, "s": 2555, "text": "Output:" }, { "code": null, "e": 2626, "s": 2567, "text": "Example 2: Creating DataFrame from dict of ndarray/lists. " }, { "code": null, "e": 2886, "s": 2626, "text": " To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length." }, { "code": null, "e": 2894, "s": 2886, "text": "Python3" }, { "code": "# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Create DataFramedf = pd.DataFrame(data) # Print the output.display(df)", "e": 3192, "s": 2894, "text": null }, { "code": null, "e": 3203, "s": 3195, "text": "Output:" }, { "code": null, "e": 3347, "s": 3205, "text": "Selection of column: In Order to select a column in Pandas DataFrame, we can either access the columns by calling them by their columns name." }, { "code": null, "e": 3355, "s": 3347, "text": "Python3" }, { "code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select two columnsprint(df[['Name', 'Qualification']])", "e": 3768, "s": 3355, "text": null }, { "code": null, "e": 3776, "s": 3768, "text": "Output:" }, { "code": null, "e": 3803, "s": 3776, "text": "Example 1: Selecting rows." }, { "code": null, "e": 3913, "s": 3803, "text": "pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition provided." }, { "code": null, "e": 3953, "s": 3913, "text": "Syntax: df.loc[df[‘cname’] ‘condition’]" }, { "code": null, "e": 3965, "s": 3953, "text": "Parameters:" }, { "code": null, "e": 3991, "s": 3965, "text": "df: represents data frame" }, { "code": null, "e": 4021, "s": 3991, "text": "cname: represents column name" }, { "code": null, "e": 4086, "s": 4021, "text": "condition: represents condition on which rows has to be selected" }, { "code": null, "e": 4094, "s": 4086, "text": "Python3" }, { "code": "# Importing pandas as pdfrom pandas import DataFrame # Creating a data frameData = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'], 'ID': [12, 43, 54, 32], 'Place': ['Delhi', 'Kochi', 'Pune', 'Patna'] } df = DataFrame(Data, columns = ['Name', 'ID', 'Place']) # Print original data frameprint(\"Original data frame:\\n\")display(df) # Selecting the product of Electronic Typeselect_prod = df.loc[df['Name'] == 'Mohe'] print(\"\\n\") # Print selected rows based on the conditionprint(\"Selecting rows:\\n\")display (select_prod)", "e": 4639, "s": 4094, "text": null }, { "code": null, "e": 4647, "s": 4639, "text": "Output:" }, { "code": null, "e": 4676, "s": 4647, "text": "Example 2: Selecting column." }, { "code": null, "e": 4684, "s": 4676, "text": "Python3" }, { "code": "# Importing pandas as pdfrom pandas import DataFrame # Creating a data frameData = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'], 'ID': [12, 43, 54, 32], 'Place': ['Delhi', 'Kochi', 'Pune', 'Patna'] } df = DataFrame(Data, columns = ['Name', 'ID', 'Place']) # Print original data frameprint(\"Original data frame:\")display(df) print(\"Selected column: \")display(df[['Name', 'ID']] )", "e": 5089, "s": 4684, "text": null }, { "code": null, "e": 5100, "s": 5092, "text": "Output:" }, { "code": null, "e": 5119, "s": 5104, "text": "sagartomar9927" }, { "code": null, "e": 5134, "s": 5119, "text": "varshagumber28" }, { "code": null, "e": 5158, "s": 5134, "text": "Python pandas-datatypes" }, { "code": null, "e": 5172, "s": 5158, "text": "Python-pandas" }, { "code": null, "e": 5179, "s": 5172, "text": "Python" }, { "code": null, "e": 5277, "s": 5179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5309, "s": 5277, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5336, "s": 5309, "text": "Python Classes and Objects" }, { "code": null, "e": 5357, "s": 5336, "text": "Python OOPs Concepts" }, { "code": null, "e": 5380, "s": 5357, "text": "Introduction To PYTHON" }, { "code": null, "e": 5411, "s": 5380, "text": "Python | os.path.join() method" }, { "code": null, "e": 5467, "s": 5411, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5509, "s": 5467, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5551, "s": 5509, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5590, "s": 5551, "text": "Python | Get unique values from a list" } ]
Program to print all the non-reachable nodes | Using BFS
06 May, 2022 Given an undirected graph and a set of vertices, we have to print all the non-reachable nodes from the given head node using a breadth-first search. For example: Consider below undirected graph with two disconnected components: In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 are reachable. We mark all the reachable nodes as visited. All those nodes which are not marked as visited i.e, node 3 and 4 are non-reachable nodes. Examples: Input: 5 0 1 0 2 1 2 3 4 Output: 3 4 Input: 8 0 1 0 2 1 2 3 4 4 5 6 7 Output: 3 4 5 6 7 Approach: We can either use BFS or DFS for this purpose. Set 1 of this article implements the DFS approach. In this article, BFS approach is used. We do BFS from a given source. Since the given graph is undirected, all the vertices that belong to the disconnected component are non-reachable nodes. We use the visited array for this purpose, the array which is used to keep track of non-visited vertices in BFS. BFS is a traversing algorithm which starts traversing from a selected node (source or starting node) and traverses the graph layer-wise thus exploring the neighbour nodes (nodes which are directly connected to source node). Then, move towards the next-level neighbour nodes. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count non-reachable nodes// from a given source using BFS. #include <bits/stdc++.h>using namespace std; // Function to add an edge to graphvoid add_edge(vector<int> adj[], int v, int w){ // Add w to v’s list. adj[v].push_back(w); // Add v to w's list. adj[w].push_back(v);} // BFS traversal of the vertices// reachable from starting nodevoid BFS(vector<int> adj[], int s, int v){ // Mark all the vertices // as not visited bool visited[v] = { false }; // Create a queue for BFS queue<int> q; // Mark the current node as // visited and enqueue it q.push(s); visited[s] = true; while (!q.empty()) { // Dequeue a vertex from // queue int p = q.front(); q.pop(); // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it for (auto it = adj[p].begin(); it != adj[p].end(); it++) { if (!visited[*it]) { visited[*it] = true; q.push(*it); } } } for (int i = 0; i < v; i++) { if (!visited[i]) { cout << i << " "; } } cout << "\n";} // Drivers codeint main(){ // Create a graph given in // the above diagram vector<int> adj[8]; add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 4, 5); add_edge(adj, 6, 7); BFS(adj, 0, 8); return 0;} // Java program to count non-reachable nodes// from a given source using BFS.import java.util.*; class GFG{ // Function to add an edge to graphstatic void add_edge(Vector<Integer> adj[], int v, int w){ // Add w to v’s list. adj[v].add(w); // Add v to w's list. adj[w].add(v);} // BFS traversal of the vertices// reachable from starting nodestatic void BFS(Vector<Integer> adj[], int s, int v){ // Mark all the vertices // as not visited boolean []visited = new boolean[v]; // Create a queue for BFS Queue<Integer> q = new LinkedList<>(); // Mark the current node as // visited and enqueue it q.add(s); visited[s] = true; while (!q.isEmpty()) { // Dequeue a vertex from // queue int p = q.peek(); q.remove(); // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it for (int it : adj[p]) { if (!visited[it]) { visited[it] = true; q.add(it); } } } for (int i = 0; i < v; i++) { if (!visited[i]) { System.out.print(i+ " "); } } System.out.print("\n");} // Drivers codepublic static void main(String[] args){ // Create a graph given in // the above diagram Vector<Integer> []adj = new Vector[8]; for (int i = 0; i < 8; i++) adj[i] = new Vector<Integer>(); add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 4, 5); add_edge(adj, 6, 7); BFS(adj, 0, 8); }} // This code is contributed by sapnasingh4991 # Python3 program to count non-reachable# nodes from a given source using BFS # Function to add an edge to graphdef add_edge(adj, v, w): # Add w to v’s list adj[v].append(w) # Add v to w's list adj[w].append(v) # BFS traversal of the vertices# reachable from starting nodedef BFS(adj, s, v): # Mark all the vertices # as not visited visited = [False for i in range(v)] # Create a queue for BFS q = [] # Mark the current node as # visited and enqueue it q.append(s) visited[s] = True while (len(q) != 0): # Dequeue a vertex from # queue p = q[0] q.pop(0) # Get all adjacent vertices # of the dequeued vertex p. # If a adjacent has not been # visited, then mark it # visited and enqueue it for it in adj[p]: if (not visited[it]): visited[it] = True q.append(it) for i in range(v): if (not visited[i]): print(i, end = ' ') print() # Driver codeif __name__=='__main__': # Create a graph given in # the above diagram adj = [[] for i in range(8)] add_edge(adj, 0, 1) add_edge(adj, 0, 2) add_edge(adj, 1, 2) add_edge(adj, 3, 4) add_edge(adj, 4, 5) add_edge(adj, 6, 7) BFS(adj, 0, 8) # This code is contributed by rutvik_56 // C# program to count non-reachable nodes// from a given source using BFS.using System;using System.Collections.Generic; class GFG{ // Function to add an edge to graphstatic void add_edge(List<int> []adj, int v, int w){ // Add w to v’s list. adj[v].Add(w); // Add v to w's list. adj[w].Add(v);} // BFS traversal of the vertices// reachable from starting nodestatic void BFS(List<int> []adj, int s, int v){ // Mark all the vertices // as not visited bool []visited = new bool[v]; // Create a queue for BFS List<int> q = new List<int>(); // Mark the current node as // visited and enqueue it q.Add(s); visited[s] = true; while (q.Count != 0) { // Dequeue a vertex from // queue int p = q[0]; q.RemoveAt(0); // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it foreach (int it in adj[p]) { if (!visited[it]) { visited[it] = true; q.Add(it); } } } for (int i = 0; i < v; i++) { if (!visited[i]) { Console.Write(i + " "); } } Console.Write("\n");} // Driver's codepublic static void Main(String[] args){ // Create a graph given in // the above diagram List<int> []adj = new List<int>[8]; for (int i = 0; i < 8; i++) adj[i] = new List<int>(); add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 4, 5); add_edge(adj, 6, 7); BFS(adj, 0, 8);}} // This code is contributed by 29AjayKumar <script> // JavaScript program to count non-reachable// nodes from a given source using BFS // Function to add an edge to graphfunction add_edge(adj, v, w){ // Add w to v’s list adj[v].push(w) // Add v to w's list adj[w].push(v)} // BFS traversal of the vertices// reachable from starting nodefunction BFS(adj, s, v){ // Mark all the vertices // as not visited let visited = new Array(v).fill(false) // Create a queue for BFS let q = [] // Mark the current node as // visited and enqueue it q.push(s) visited[s] = true while (q.length != 0){ // Dequeue a vertex from // queue let p = q.shift() // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it for(let it of adj[p]){ if (!visited[it]){ visited[it] = true q.push(it) } } } for(let i=0;i<v;i++){ if (!visited[i]){ document.write(i,' ') } } document.write("</br>")} // Driver code // Create a graph given in// the above diagramlet adj = new Array(8)for(let i=0;i<8;i++){ adj[i] = new Array()} add_edge(adj, 0, 1)add_edge(adj, 0, 2)add_edge(adj, 1, 2)add_edge(adj, 3, 4)add_edge(adj, 4, 5)add_edge(adj, 6, 7) BFS(adj, 0, 8) // This code is contributed by Shinjanpatra </script> 3 4 5 6 7 sapnasingh4991 29AjayKumar rutvik_56 shinjanpatra BFS Data Structures Graph Data Structures Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 May, 2022" }, { "code": null, "e": 201, "s": 52, "text": "Given an undirected graph and a set of vertices, we have to print all the non-reachable nodes from the given head node using a breadth-first search." }, { "code": null, "e": 216, "s": 201, "text": "For example: " }, { "code": null, "e": 284, "s": 216, "text": "Consider below undirected graph with two disconnected components: " }, { "code": null, "e": 509, "s": 284, "text": "In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 are reachable. We mark all the reachable nodes as visited. All those nodes which are not marked as visited i.e, node 3 and 4 are non-reachable nodes. " }, { "code": null, "e": 520, "s": 509, "text": "Examples: " }, { "code": null, "e": 679, "s": 520, "text": "Input: 5\n 0 1\n 0 2\n 1 2\n 3 4\nOutput: 3 4\n\nInput: 8\n 0 1\n 0 2\n 1 2\n 3 4\n 4 5\n 6 7\nOutput: 3 4 5 6 7" }, { "code": null, "e": 690, "s": 679, "text": "Approach: " }, { "code": null, "e": 827, "s": 690, "text": "We can either use BFS or DFS for this purpose. Set 1 of this article implements the DFS approach. In this article, BFS approach is used." }, { "code": null, "e": 1093, "s": 827, "text": "We do BFS from a given source. Since the given graph is undirected, all the vertices that belong to the disconnected component are non-reachable nodes. We use the visited array for this purpose, the array which is used to keep track of non-visited vertices in BFS. " }, { "code": null, "e": 1370, "s": 1093, "text": "BFS is a traversing algorithm which starts traversing from a selected node (source or starting node) and traverses the graph layer-wise thus exploring the neighbour nodes (nodes which are directly connected to source node). Then, move towards the next-level neighbour nodes. " }, { "code": null, "e": 1423, "s": 1370, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1427, "s": 1423, "text": "C++" }, { "code": null, "e": 1432, "s": 1427, "text": "Java" }, { "code": null, "e": 1440, "s": 1432, "text": "Python3" }, { "code": null, "e": 1443, "s": 1440, "text": "C#" }, { "code": null, "e": 1454, "s": 1443, "text": "Javascript" }, { "code": "// C++ program to count non-reachable nodes// from a given source using BFS. #include <bits/stdc++.h>using namespace std; // Function to add an edge to graphvoid add_edge(vector<int> adj[], int v, int w){ // Add w to v’s list. adj[v].push_back(w); // Add v to w's list. adj[w].push_back(v);} // BFS traversal of the vertices// reachable from starting nodevoid BFS(vector<int> adj[], int s, int v){ // Mark all the vertices // as not visited bool visited[v] = { false }; // Create a queue for BFS queue<int> q; // Mark the current node as // visited and enqueue it q.push(s); visited[s] = true; while (!q.empty()) { // Dequeue a vertex from // queue int p = q.front(); q.pop(); // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it for (auto it = adj[p].begin(); it != adj[p].end(); it++) { if (!visited[*it]) { visited[*it] = true; q.push(*it); } } } for (int i = 0; i < v; i++) { if (!visited[i]) { cout << i << \" \"; } } cout << \"\\n\";} // Drivers codeint main(){ // Create a graph given in // the above diagram vector<int> adj[8]; add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 4, 5); add_edge(adj, 6, 7); BFS(adj, 0, 8); return 0;}", "e": 3005, "s": 1454, "text": null }, { "code": "// Java program to count non-reachable nodes// from a given source using BFS.import java.util.*; class GFG{ // Function to add an edge to graphstatic void add_edge(Vector<Integer> adj[], int v, int w){ // Add w to v’s list. adj[v].add(w); // Add v to w's list. adj[w].add(v);} // BFS traversal of the vertices// reachable from starting nodestatic void BFS(Vector<Integer> adj[], int s, int v){ // Mark all the vertices // as not visited boolean []visited = new boolean[v]; // Create a queue for BFS Queue<Integer> q = new LinkedList<>(); // Mark the current node as // visited and enqueue it q.add(s); visited[s] = true; while (!q.isEmpty()) { // Dequeue a vertex from // queue int p = q.peek(); q.remove(); // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it for (int it : adj[p]) { if (!visited[it]) { visited[it] = true; q.add(it); } } } for (int i = 0; i < v; i++) { if (!visited[i]) { System.out.print(i+ \" \"); } } System.out.print(\"\\n\");} // Drivers codepublic static void main(String[] args){ // Create a graph given in // the above diagram Vector<Integer> []adj = new Vector[8]; for (int i = 0; i < 8; i++) adj[i] = new Vector<Integer>(); add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 4, 5); add_edge(adj, 6, 7); BFS(adj, 0, 8); }} // This code is contributed by sapnasingh4991", "e": 4716, "s": 3005, "text": null }, { "code": "# Python3 program to count non-reachable# nodes from a given source using BFS # Function to add an edge to graphdef add_edge(adj, v, w): # Add w to v’s list adj[v].append(w) # Add v to w's list adj[w].append(v) # BFS traversal of the vertices# reachable from starting nodedef BFS(adj, s, v): # Mark all the vertices # as not visited visited = [False for i in range(v)] # Create a queue for BFS q = [] # Mark the current node as # visited and enqueue it q.append(s) visited[s] = True while (len(q) != 0): # Dequeue a vertex from # queue p = q[0] q.pop(0) # Get all adjacent vertices # of the dequeued vertex p. # If a adjacent has not been # visited, then mark it # visited and enqueue it for it in adj[p]: if (not visited[it]): visited[it] = True q.append(it) for i in range(v): if (not visited[i]): print(i, end = ' ') print() # Driver codeif __name__=='__main__': # Create a graph given in # the above diagram adj = [[] for i in range(8)] add_edge(adj, 0, 1) add_edge(adj, 0, 2) add_edge(adj, 1, 2) add_edge(adj, 3, 4) add_edge(adj, 4, 5) add_edge(adj, 6, 7) BFS(adj, 0, 8) # This code is contributed by rutvik_56", "e": 6098, "s": 4716, "text": null }, { "code": "// C# program to count non-reachable nodes// from a given source using BFS.using System;using System.Collections.Generic; class GFG{ // Function to add an edge to graphstatic void add_edge(List<int> []adj, int v, int w){ // Add w to v’s list. adj[v].Add(w); // Add v to w's list. adj[w].Add(v);} // BFS traversal of the vertices// reachable from starting nodestatic void BFS(List<int> []adj, int s, int v){ // Mark all the vertices // as not visited bool []visited = new bool[v]; // Create a queue for BFS List<int> q = new List<int>(); // Mark the current node as // visited and enqueue it q.Add(s); visited[s] = true; while (q.Count != 0) { // Dequeue a vertex from // queue int p = q[0]; q.RemoveAt(0); // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it foreach (int it in adj[p]) { if (!visited[it]) { visited[it] = true; q.Add(it); } } } for (int i = 0; i < v; i++) { if (!visited[i]) { Console.Write(i + \" \"); } } Console.Write(\"\\n\");} // Driver's codepublic static void Main(String[] args){ // Create a graph given in // the above diagram List<int> []adj = new List<int>[8]; for (int i = 0; i < 8; i++) adj[i] = new List<int>(); add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 4, 5); add_edge(adj, 6, 7); BFS(adj, 0, 8);}} // This code is contributed by 29AjayKumar", "e": 7804, "s": 6098, "text": null }, { "code": "<script> // JavaScript program to count non-reachable// nodes from a given source using BFS // Function to add an edge to graphfunction add_edge(adj, v, w){ // Add w to v’s list adj[v].push(w) // Add v to w's list adj[w].push(v)} // BFS traversal of the vertices// reachable from starting nodefunction BFS(adj, s, v){ // Mark all the vertices // as not visited let visited = new Array(v).fill(false) // Create a queue for BFS let q = [] // Mark the current node as // visited and enqueue it q.push(s) visited[s] = true while (q.length != 0){ // Dequeue a vertex from // queue let p = q.shift() // Get all adjacent vertices // of the dequeued vertex p. // If a adjacent has not been // visited, then mark it // visited and enqueue it for(let it of adj[p]){ if (!visited[it]){ visited[it] = true q.push(it) } } } for(let i=0;i<v;i++){ if (!visited[i]){ document.write(i,' ') } } document.write(\"</br>\")} // Driver code // Create a graph given in// the above diagramlet adj = new Array(8)for(let i=0;i<8;i++){ adj[i] = new Array()} add_edge(adj, 0, 1)add_edge(adj, 0, 2)add_edge(adj, 1, 2)add_edge(adj, 3, 4)add_edge(adj, 4, 5)add_edge(adj, 6, 7) BFS(adj, 0, 8) // This code is contributed by Shinjanpatra </script>", "e": 9267, "s": 7804, "text": null }, { "code": null, "e": 9277, "s": 9267, "text": "3 4 5 6 7" }, { "code": null, "e": 9294, "s": 9279, "text": "sapnasingh4991" }, { "code": null, "e": 9306, "s": 9294, "text": "29AjayKumar" }, { "code": null, "e": 9316, "s": 9306, "text": "rutvik_56" }, { "code": null, "e": 9329, "s": 9316, "text": "shinjanpatra" }, { "code": null, "e": 9333, "s": 9329, "text": "BFS" }, { "code": null, "e": 9349, "s": 9333, "text": "Data Structures" }, { "code": null, "e": 9355, "s": 9349, "text": "Graph" }, { "code": null, "e": 9371, "s": 9355, "text": "Data Structures" }, { "code": null, "e": 9377, "s": 9371, "text": "Graph" }, { "code": null, "e": 9381, "s": 9377, "text": "BFS" } ]
C# | Multidimensional Indexers
21 Dec, 2021 The multi-dimensional indexer is almost similar to multidimensional arrays. For the efficient content-based retrieval of data, multidimensional indexers are used. To create multi-dimensional indexer you have to pass at least two parameters in the argument list of indexer declaration. To access a single element of a multi-dimensional indexer, use integer subscripts. Each subscript indexes a dimension like the first indexes the row dimension, the second indexes the column dimension and so on. Example 1: Using get and set accessor // C# program to illustrate the // Multidimensional Indexersusing System; class GFG { // reference to underlying 2D array int[, ] data = new int[5, 5]; // declaring Multidimensional Indexer public int this[int index1, int index2] { // get accessor get { // it returns the values which // read the indexes return data[index1, index2]; } // set accessor set { // write the values in 'data' // using value keyword data[index1, index2] = value; } }} // Driver Classclass Geeks { // Main Method public static void Main(String []args) { // creating the instance of // Class GFG as "index" GFG index = new GFG(); // assign the values accordingly to // the indexes of the array // 1st row index[0, 0] = 1; index[0, 1] = 2; index[0, 2] = 3; // 2nd row index[1, 0] = 4; index[1, 1] = 5; index[1, 2] = 6; // 3rd row index[2, 0] = 7; index[2, 1] = 8; index[2, 2] = 9; // displaying the values Console.WriteLine("{0}\t{1}\t{2}\n{3}\t{4}\t{5}\n{6}\t{7}\t{8}", index[0, 0], index[0, 1], index[0, 2], index[1, 0], index[1, 1], index[1, 2], index[2, 0], index[2, 1], index[2, 2]); }} 1 2 3 4 5 6 7 8 9 Example 2: Without using the “set” accessor i.e only using Read-Only Property // C# program to illustrate the Multidimensional // Indexer without using set accessor using System; class GFG { // default constructor public GFG() {} // Multidimensional Indexer public int this[int i1, int i2] { // get accessor get { // read only properties return (i1 + i2); } // No set accessor used } // Main Methodpublic static void Main(String []args){ // creating object of class // "GFG" as "index" GFG index = new GFG(); // displaying the values for (int i = 0; i <= 2; i++) { for (int j = 1; j <= 3; j++) { Console.Write(index[i, j] + "\t"); } Console.WriteLine(); }}} 1 2 3 2 3 4 3 4 5 surindertarika1234 CSharp-Indexers & Properties C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Dec, 2021" }, { "code": null, "e": 550, "s": 54, "text": "The multi-dimensional indexer is almost similar to multidimensional arrays. For the efficient content-based retrieval of data, multidimensional indexers are used. To create multi-dimensional indexer you have to pass at least two parameters in the argument list of indexer declaration. To access a single element of a multi-dimensional indexer, use integer subscripts. Each subscript indexes a dimension like the first indexes the row dimension, the second indexes the column dimension and so on." }, { "code": null, "e": 588, "s": 550, "text": "Example 1: Using get and set accessor" }, { "code": "// C# program to illustrate the // Multidimensional Indexersusing System; class GFG { // reference to underlying 2D array int[, ] data = new int[5, 5]; // declaring Multidimensional Indexer public int this[int index1, int index2] { // get accessor get { // it returns the values which // read the indexes return data[index1, index2]; } // set accessor set { // write the values in 'data' // using value keyword data[index1, index2] = value; } }} // Driver Classclass Geeks { // Main Method public static void Main(String []args) { // creating the instance of // Class GFG as \"index\" GFG index = new GFG(); // assign the values accordingly to // the indexes of the array // 1st row index[0, 0] = 1; index[0, 1] = 2; index[0, 2] = 3; // 2nd row index[1, 0] = 4; index[1, 1] = 5; index[1, 2] = 6; // 3rd row index[2, 0] = 7; index[2, 1] = 8; index[2, 2] = 9; // displaying the values Console.WriteLine(\"{0}\\t{1}\\t{2}\\n{3}\\t{4}\\t{5}\\n{6}\\t{7}\\t{8}\", index[0, 0], index[0, 1], index[0, 2], index[1, 0], index[1, 1], index[1, 2], index[2, 0], index[2, 1], index[2, 2]); }}", "e": 2198, "s": 588, "text": null }, { "code": null, "e": 2235, "s": 2198, "text": "1 2 3\n4 5 6\n7 8 9\n" }, { "code": null, "e": 2313, "s": 2235, "text": "Example 2: Without using the “set” accessor i.e only using Read-Only Property" }, { "code": "// C# program to illustrate the Multidimensional // Indexer without using set accessor using System; class GFG { // default constructor public GFG() {} // Multidimensional Indexer public int this[int i1, int i2] { // get accessor get { // read only properties return (i1 + i2); } // No set accessor used } // Main Methodpublic static void Main(String []args){ // creating object of class // \"GFG\" as \"index\" GFG index = new GFG(); // displaying the values for (int i = 0; i <= 2; i++) { for (int j = 1; j <= 3; j++) { Console.Write(index[i, j] + \"\\t\"); } Console.WriteLine(); }}}", "e": 3103, "s": 2313, "text": null }, { "code": null, "e": 3148, "s": 3103, "text": "1 2 3 \n2 3 4 \n3 4 5\n" }, { "code": null, "e": 3167, "s": 3148, "text": "surindertarika1234" }, { "code": null, "e": 3196, "s": 3167, "text": "CSharp-Indexers & Properties" }, { "code": null, "e": 3199, "s": 3196, "text": "C#" } ]
Java Program to Count Number of Vowels in a String
11 Mar, 2022 In java, the string is a sequence of characters and char is a single digit used to store variables. The char uses 2 bytes in java. In java, BufferedReader and InputStreamReader are used to read the input given by the user from the keyboard. Then readLine() is used for reading a line. The java.io package in java provides input and output through data streams, serialization, and the file system. We can count the vowels in a string in two ways: IterativeRecursive Iterative Recursive Examples: Input: GeeksForGeeks Output: Total no of vowels in string are: 5 Input: ChETaN Output: Total no of vowels in string are: 2 Method 1: Iterative Approach: We will traverse through the string’s characters in a for loop starting from index 0 till size-1. And check each character if it is a vowel or not and increment the count variable. Java // Java Program to Count Number of Vowels// in a String in a iterative way import java.io.*; public class vowel { public static void main(String[] args) throws IOException { String str = "GeeksForGeeks"; str = str.toLowerCase(); int count = 0; for (int i = 0; i < str.length(); i++) { // check if char[i] is vowel if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') { // count increments if there is vowel in // char[i] count++; } } // display total count of vowels in string System.out.println( "Total no of vowels in string are: " + count); }} Total no of vowels in string are: 5 Total no of vowels in string are: 5 Method 2: Recursive Approach: Check for the base condition if the length of the string is 1, then simply check for that single character if it is a vowel, then return 1 else return 0. For dividing the whole string into substring to return the answer recursively, we will get the answer for the string starting from first till second last character. And finally return the above answer plus the answer for the check of last character (1 if it is vowel or 0 if it is not) Java // Java Program to Count Number of Vowels// in a String in a recursive way import java.io.*; class GFG { // isVowel() function returns 1 if the // character is a vowel and 0 if it is not static int isVowel(char chars) { if (chars == 'a' || chars == 'e' || chars == 'i' || chars == 'o' || chars == 'u') { return 1; } else { return 0; } } // recursive function to return the number // of characters in a string static int vowelno(String str, int l) { if (l == 1) { return isVowel(str.charAt(l - 1)); } return vowelno(str, l - 1) + isVowel(str.charAt(l - 1)); } public static void main(String[] args) throws IOException { String str = "BufferedOutput"; str = str.toLowerCase(); System.out.println( "Total number of vowels in string are:"); System.out.println(vowelno(str, str.length())); }} Total number of vowels in string are: 6 manobharathi93 Java-String-Programs Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Mar, 2022" }, { "code": null, "e": 450, "s": 53, "text": "In java, the string is a sequence of characters and char is a single digit used to store variables. The char uses 2 bytes in java. In java, BufferedReader and InputStreamReader are used to read the input given by the user from the keyboard. Then readLine() is used for reading a line. The java.io package in java provides input and output through data streams, serialization, and the file system." }, { "code": null, "e": 499, "s": 450, "text": "We can count the vowels in a string in two ways:" }, { "code": null, "e": 518, "s": 499, "text": "IterativeRecursive" }, { "code": null, "e": 528, "s": 518, "text": "Iterative" }, { "code": null, "e": 538, "s": 528, "text": "Recursive" }, { "code": null, "e": 548, "s": 538, "text": "Examples:" }, { "code": null, "e": 672, "s": 548, "text": "Input: GeeksForGeeks\nOutput: Total no of vowels in string are: 5\n\nInput: ChETaN\nOutput: Total no of vowels in string are: 2" }, { "code": null, "e": 693, "s": 672, "text": "Method 1: Iterative " }, { "code": null, "e": 703, "s": 693, "text": "Approach:" }, { "code": null, "e": 801, "s": 703, "text": "We will traverse through the string’s characters in a for loop starting from index 0 till size-1." }, { "code": null, "e": 884, "s": 801, "text": "And check each character if it is a vowel or not and increment the count variable." }, { "code": null, "e": 889, "s": 884, "text": "Java" }, { "code": "// Java Program to Count Number of Vowels// in a String in a iterative way import java.io.*; public class vowel { public static void main(String[] args) throws IOException { String str = \"GeeksForGeeks\"; str = str.toLowerCase(); int count = 0; for (int i = 0; i < str.length(); i++) { // check if char[i] is vowel if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') { // count increments if there is vowel in // char[i] count++; } } // display total count of vowels in string System.out.println( \"Total no of vowels in string are: \" + count); }}", "e": 1706, "s": 889, "text": null }, { "code": null, "e": 1742, "s": 1706, "text": "Total no of vowels in string are: 5" }, { "code": null, "e": 1781, "s": 1745, "text": "Total no of vowels in string are: 5" }, { "code": null, "e": 1803, "s": 1783, "text": "Method 2: Recursive" }, { "code": null, "e": 1815, "s": 1805, "text": "Approach:" }, { "code": null, "e": 1971, "s": 1817, "text": "Check for the base condition if the length of the string is 1, then simply check for that single character if it is a vowel, then return 1 else return 0." }, { "code": null, "e": 2136, "s": 1971, "text": "For dividing the whole string into substring to return the answer recursively, we will get the answer for the string starting from first till second last character." }, { "code": null, "e": 2257, "s": 2136, "text": "And finally return the above answer plus the answer for the check of last character (1 if it is vowel or 0 if it is not)" }, { "code": null, "e": 2264, "s": 2259, "text": "Java" }, { "code": "// Java Program to Count Number of Vowels// in a String in a recursive way import java.io.*; class GFG { // isVowel() function returns 1 if the // character is a vowel and 0 if it is not static int isVowel(char chars) { if (chars == 'a' || chars == 'e' || chars == 'i' || chars == 'o' || chars == 'u') { return 1; } else { return 0; } } // recursive function to return the number // of characters in a string static int vowelno(String str, int l) { if (l == 1) { return isVowel(str.charAt(l - 1)); } return vowelno(str, l - 1) + isVowel(str.charAt(l - 1)); } public static void main(String[] args) throws IOException { String str = \"BufferedOutput\"; str = str.toLowerCase(); System.out.println( \"Total number of vowels in string are:\"); System.out.println(vowelno(str, str.length())); }}", "e": 3248, "s": 2264, "text": null }, { "code": null, "e": 3291, "s": 3251, "text": "Total number of vowels in string are:\n6" }, { "code": null, "e": 3308, "s": 3293, "text": "manobharathi93" }, { "code": null, "e": 3329, "s": 3308, "text": "Java-String-Programs" }, { "code": null, "e": 3336, "s": 3329, "text": "Picked" }, { "code": null, "e": 3360, "s": 3336, "text": "Technical Scripter 2020" }, { "code": null, "e": 3365, "s": 3360, "text": "Java" }, { "code": null, "e": 3379, "s": 3365, "text": "Java Programs" }, { "code": null, "e": 3398, "s": 3379, "text": "Technical Scripter" }, { "code": null, "e": 3403, "s": 3398, "text": "Java" } ]
How to write Multi-Line Strings in PHP ?
21 May, 2021 Multi-Line Strings can be written in PHP using the following ways. Using escape sequences: We can use the \n escape sequences to declare multiple lines in a string.PHP Code:PHPPHP<?php //declaring multiple lines using the new line escape sequence $var="Geeks\nFor\nGeeks"; echo $var;?>Output:Geeks For GeeksUsing concatenation assignment operator: We can use the concatenation assignment operator .= to concatenate two strings and the PHP_EOL to mark the end of the line.PHP Code:PHPPHP<?php $s1="Geeks". PHP_EOL;//PHP_EOL marks end of line so that $s2="For". PHP_EOL;//next string get concatenated as new line $s3="Geeks"; $s1.=$s2.=$s3;//concatenating the string into $s1 echo $s1;//printing final concatenated string?>Output:Geeks For GeeksUsing Heredoc and Nowdoc Syntax: We can use the PHP Heredoc or the PHP Nowdoc syntax to write multiple-line string variables directly. The difference between heredoc and nowdoc is that heredoc uses double-quoted strings. Parsing is done inside a heredoc for escape sequences, etc whereas a nowdoc uses single-quoted strings, and hence parsing is not performed.Note: The delimiter in the heredoc and nowdoc syntaxes must always be at the beginning of a line without any spaces, characters, etc. PHP Code: PHPPHP<?php // code //Heredoc variable $s1=<<<EOD Geeks \tFor GeeksEOD;echo $s1; echo"\n"; //Nowdoc variable $s2=<<<'EOT' Geeks \tFor GeeksEOT;echo $s2?>Output: Geeks For Geeks Geeks \tFor Geeks Using escape sequences: We can use the \n escape sequences to declare multiple lines in a string.PHP Code:PHPPHP<?php //declaring multiple lines using the new line escape sequence $var="Geeks\nFor\nGeeks"; echo $var;?>Output:Geeks For Geeks Using escape sequences: We can use the \n escape sequences to declare multiple lines in a string. PHP Code: PHP <?php //declaring multiple lines using the new line escape sequence $var="Geeks\nFor\nGeeks"; echo $var;?> Output: Geeks For Geeks Using concatenation assignment operator: We can use the concatenation assignment operator .= to concatenate two strings and the PHP_EOL to mark the end of the line.PHP Code:PHPPHP<?php $s1="Geeks". PHP_EOL;//PHP_EOL marks end of line so that $s2="For". PHP_EOL;//next string get concatenated as new line $s3="Geeks"; $s1.=$s2.=$s3;//concatenating the string into $s1 echo $s1;//printing final concatenated string?>Output:Geeks For Geeks Using concatenation assignment operator: We can use the concatenation assignment operator .= to concatenate two strings and the PHP_EOL to mark the end of the line. PHP Code: PHP <?php $s1="Geeks". PHP_EOL;//PHP_EOL marks end of line so that $s2="For". PHP_EOL;//next string get concatenated as new line $s3="Geeks"; $s1.=$s2.=$s3;//concatenating the string into $s1 echo $s1;//printing final concatenated string?> Output: Geeks For Geeks Using Heredoc and Nowdoc Syntax: We can use the PHP Heredoc or the PHP Nowdoc syntax to write multiple-line string variables directly. The difference between heredoc and nowdoc is that heredoc uses double-quoted strings. Parsing is done inside a heredoc for escape sequences, etc whereas a nowdoc uses single-quoted strings, and hence parsing is not performed.Note: The delimiter in the heredoc and nowdoc syntaxes must always be at the beginning of a line without any spaces, characters, etc. PHP Code: PHPPHP<?php // code //Heredoc variable $s1=<<<EOD Geeks \tFor GeeksEOD;echo $s1; echo"\n"; //Nowdoc variable $s2=<<<'EOT' Geeks \tFor GeeksEOT;echo $s2?>Output: Geeks For Geeks Geeks \tFor Geeks Using Heredoc and Nowdoc Syntax: We can use the PHP Heredoc or the PHP Nowdoc syntax to write multiple-line string variables directly. The difference between heredoc and nowdoc is that heredoc uses double-quoted strings. Parsing is done inside a heredoc for escape sequences, etc whereas a nowdoc uses single-quoted strings, and hence parsing is not performed. Note: The delimiter in the heredoc and nowdoc syntaxes must always be at the beginning of a line without any spaces, characters, etc. PHP Code: PHP <?php // code //Heredoc variable $s1=<<<EOD Geeks \tFor GeeksEOD;echo $s1; echo"\n"; //Nowdoc variable $s2=<<<'EOT' Geeks \tFor GeeksEOT;echo $s2?> Output: Geeks For Geeks Geeks \tFor Geeks References: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc, https://www.geeksforgeeks.org/php-strings/ PHP-Questions PHP-string Picked PHP Technical Scripter 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": "\n21 May, 2021" }, { "code": null, "e": 95, "s": 28, "text": "Multi-Line Strings can be written in PHP using the following ways." }, { "code": null, "e": 1524, "s": 95, "text": "Using escape sequences: We can use the \\n escape sequences to declare multiple lines in a string.PHP Code:PHPPHP<?php //declaring multiple lines using the new line escape sequence $var=\"Geeks\\nFor\\nGeeks\"; echo $var;?>Output:Geeks\nFor\nGeeksUsing concatenation assignment operator: We can use the concatenation assignment operator .= to concatenate two strings and the PHP_EOL to mark the end of the line.PHP Code:PHPPHP<?php $s1=\"Geeks\". PHP_EOL;//PHP_EOL marks end of line so that $s2=\"For\". PHP_EOL;//next string get concatenated as new line $s3=\"Geeks\"; $s1.=$s2.=$s3;//concatenating the string into $s1 echo $s1;//printing final concatenated string?>Output:Geeks\nFor\nGeeksUsing Heredoc and Nowdoc Syntax: We can use the PHP Heredoc or the PHP Nowdoc syntax to write multiple-line string variables directly. The difference between heredoc and nowdoc is that heredoc uses double-quoted strings. Parsing is done inside a heredoc for escape sequences, etc whereas a nowdoc uses single-quoted strings, and hence parsing is not performed.Note: The delimiter in the heredoc and nowdoc syntaxes must always be at the beginning of a line without any spaces, characters, etc. PHP Code: PHPPHP<?php // code //Heredoc variable $s1=<<<EOD Geeks \\tFor GeeksEOD;echo $s1; echo\"\\n\"; //Nowdoc variable $s2=<<<'EOT' Geeks \\tFor GeeksEOT;echo $s2?>Output: Geeks\n For\n Geeks\n Geeks\n \\tFor\n Geeks" }, { "code": null, "e": 1776, "s": 1524, "text": "Using escape sequences: We can use the \\n escape sequences to declare multiple lines in a string.PHP Code:PHPPHP<?php //declaring multiple lines using the new line escape sequence $var=\"Geeks\\nFor\\nGeeks\"; echo $var;?>Output:Geeks\nFor\nGeeks" }, { "code": null, "e": 1874, "s": 1776, "text": "Using escape sequences: We can use the \\n escape sequences to declare multiple lines in a string." }, { "code": null, "e": 1884, "s": 1874, "text": "PHP Code:" }, { "code": null, "e": 1888, "s": 1884, "text": "PHP" }, { "code": "<?php //declaring multiple lines using the new line escape sequence $var=\"Geeks\\nFor\\nGeeks\"; echo $var;?>", "e": 2006, "s": 1888, "text": null }, { "code": null, "e": 2014, "s": 2006, "text": "Output:" }, { "code": null, "e": 2030, "s": 2014, "text": "Geeks\nFor\nGeeks" }, { "code": null, "e": 2482, "s": 2030, "text": "Using concatenation assignment operator: We can use the concatenation assignment operator .= to concatenate two strings and the PHP_EOL to mark the end of the line.PHP Code:PHPPHP<?php $s1=\"Geeks\". PHP_EOL;//PHP_EOL marks end of line so that $s2=\"For\". PHP_EOL;//next string get concatenated as new line $s3=\"Geeks\"; $s1.=$s2.=$s3;//concatenating the string into $s1 echo $s1;//printing final concatenated string?>Output:Geeks\nFor\nGeeks" }, { "code": null, "e": 2647, "s": 2482, "text": "Using concatenation assignment operator: We can use the concatenation assignment operator .= to concatenate two strings and the PHP_EOL to mark the end of the line." }, { "code": null, "e": 2657, "s": 2647, "text": "PHP Code:" }, { "code": null, "e": 2661, "s": 2657, "text": "PHP" }, { "code": "<?php $s1=\"Geeks\". PHP_EOL;//PHP_EOL marks end of line so that $s2=\"For\". PHP_EOL;//next string get concatenated as new line $s3=\"Geeks\"; $s1.=$s2.=$s3;//concatenating the string into $s1 echo $s1;//printing final concatenated string?>", "e": 2912, "s": 2661, "text": null }, { "code": null, "e": 2920, "s": 2912, "text": "Output:" }, { "code": null, "e": 2936, "s": 2920, "text": "Geeks\nFor\nGeeks" }, { "code": null, "e": 3663, "s": 2936, "text": "Using Heredoc and Nowdoc Syntax: We can use the PHP Heredoc or the PHP Nowdoc syntax to write multiple-line string variables directly. The difference between heredoc and nowdoc is that heredoc uses double-quoted strings. Parsing is done inside a heredoc for escape sequences, etc whereas a nowdoc uses single-quoted strings, and hence parsing is not performed.Note: The delimiter in the heredoc and nowdoc syntaxes must always be at the beginning of a line without any spaces, characters, etc. PHP Code: PHPPHP<?php // code //Heredoc variable $s1=<<<EOD Geeks \\tFor GeeksEOD;echo $s1; echo\"\\n\"; //Nowdoc variable $s2=<<<'EOT' Geeks \\tFor GeeksEOT;echo $s2?>Output: Geeks\n For\n Geeks\n Geeks\n \\tFor\n Geeks" }, { "code": null, "e": 4024, "s": 3663, "text": "Using Heredoc and Nowdoc Syntax: We can use the PHP Heredoc or the PHP Nowdoc syntax to write multiple-line string variables directly. The difference between heredoc and nowdoc is that heredoc uses double-quoted strings. Parsing is done inside a heredoc for escape sequences, etc whereas a nowdoc uses single-quoted strings, and hence parsing is not performed." }, { "code": null, "e": 4159, "s": 4024, "text": "Note: The delimiter in the heredoc and nowdoc syntaxes must always be at the beginning of a line without any spaces, characters, etc. " }, { "code": null, "e": 4170, "s": 4159, "text": "PHP Code: " }, { "code": null, "e": 4174, "s": 4170, "text": "PHP" }, { "code": "<?php // code //Heredoc variable $s1=<<<EOD Geeks \\tFor GeeksEOD;echo $s1; echo\"\\n\"; //Nowdoc variable $s2=<<<'EOT' Geeks \\tFor GeeksEOT;echo $s2?>", "e": 4336, "s": 4174, "text": null }, { "code": null, "e": 4344, "s": 4336, "text": "Output:" }, { "code": null, "e": 4393, "s": 4344, "text": " Geeks\n For\n Geeks\n Geeks\n \\tFor\n Geeks" }, { "code": null, "e": 4541, "s": 4393, "text": "References: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc, https://www.geeksforgeeks.org/php-strings/" }, { "code": null, "e": 4555, "s": 4541, "text": "PHP-Questions" }, { "code": null, "e": 4566, "s": 4555, "text": "PHP-string" }, { "code": null, "e": 4573, "s": 4566, "text": "Picked" }, { "code": null, "e": 4577, "s": 4573, "text": "PHP" }, { "code": null, "e": 4596, "s": 4577, "text": "Technical Scripter" }, { "code": null, "e": 4613, "s": 4596, "text": "Web Technologies" }, { "code": null, "e": 4617, "s": 4613, "text": "PHP" } ]
Introduction to Brython
19 Aug, 2020 We all know that Python serves excellent as a server side language, it can be also used as a client-side language. We can use Brython on client-side instead of Javascript. Brython stands for Browser’s Python. It is an implementation of Python3 running in the browser. It is believed that Brython’s goal is to replace javascript as a scripting language for browser. Most of all modern browsers support Brython, even smartphones also support Brython. Main features : Brython supports most of the syntax of Python3, including comprehensions, generators, metaclasses, imports, etc. and many modules of the CPython distribution. It includes libraries to interact with DOM elements and events, and with existing Javascript libraries such as jQuery, 3D, Highcharts, Raphael etc. It supports lastest specs of HTML5/CSS3, and can use CSS Frameworks like Bootstrap3, LESS, SASS etc. Installation : You can install Brython locally by running the following pip command in the terminal : pip install brython You can also use Brython without having to install anything, just by including the Brython scripts from a CDN : HTML <script src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js"></script><script src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython_stdlib.js"></script> To use Brython, all there is to do is: Load the script brython.js.Run the function brython() on page load, like <body onload=brython()>.Write Python code inside tags <script type=”text/python”> or linking it. Load the script brython.js. Run the function brython() on page load, like <body onload=brython()>. Write Python code inside tags <script type=”text/python”> or linking it. Example 1 : “Hello World !” using Brython” HTML <!Doctype html><html><head> <meta charset = "utf-8"> <script type = "text/javascript" src = "https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js"> </script></head> <body onload = "brython()"><script type = "text/python">from browser import document document <= "Hello World!"</script></body></html> Output : Example 2 : Create an HTML table using Brython To create a table, we use the HTML tags : TABLE (the table), TR (a table row), TH (a header cell) and TD (a cell). The table is made of rows, each row is made of cells, the first row is generally made of “header cells” describing the value in the matching column HTML <!Doctype html><html> <head> <meta charset = "utf-8"> <script type = "text/javascript" src = "https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js"> </script></head> <body onload="brython()"> <p id='zone'> </p> <script type="text/python"> from browser import document from browser.html import TABLE, TR, TH, TD table = TABLE() # create a row row = TR() # add header cells row <= TH("Country") row <= TH("Capital city") # add the row to the table table <= row # add a row 1 row = TR() row <= TD("United States") + TD("Washington") table <= row # add a row 2 row = TR() row <= TD("India") + TD("Delhi") table <= row # erase initial content document['zone'].clear() # insert table in the element document['zone'] <= table </script></body></html> Output : Example 3 : We can build a table from a list of lists. In this example, we will only show the Python script, the surrounding HTML code will remain the same as in the previous example HTML <script type="text/python"> from browser import document from browser.html import TABLE, TR, TH, TD lines = [ ['Morrissey', 'vocals'], ['Kijibasu', 'guitar'], ['Rajpal', 'the drums'], ['Aayush', 'the bass guitar'] ] t = TABLE() for line in lines: t <= TR(TD(line[0])+TD(line[1])) document['zone'].text = '' document['zone']<= t</script> Future of Brython : Many Python developers are working on it to make it better, but it may be difficult that it can replace Javascript. There is no framework available in Brython. It may take many years for Brython to be used on client-side. There is a lack of resources to learn Brython, so people are choosing Javascript over Brython. But using Brython would be a great advantage for those developer who want to use one language for server side and client side. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Aug, 2020" }, { "code": null, "e": 225, "s": 52, "text": "We all know that Python serves excellent as a server side language, it can be also used as a client-side language. We can use Brython on client-side instead of Javascript. " }, { "code": null, "e": 503, "s": 225, "text": "Brython stands for Browser’s Python. It is an implementation of Python3 running in the browser. It is believed that Brython’s goal is to replace javascript as a scripting language for browser. Most of all modern browsers support Brython, even smartphones also support Brython. " }, { "code": null, "e": 678, "s": 503, "text": "Main features : Brython supports most of the syntax of Python3, including comprehensions, generators, metaclasses, imports, etc. and many modules of the CPython distribution." }, { "code": null, "e": 927, "s": 678, "text": "It includes libraries to interact with DOM elements and events, and with existing Javascript libraries such as jQuery, 3D, Highcharts, Raphael etc. It supports lastest specs of HTML5/CSS3, and can use CSS Frameworks like Bootstrap3, LESS, SASS etc." }, { "code": null, "e": 942, "s": 927, "text": "Installation :" }, { "code": null, "e": 1030, "s": 942, "text": "You can install Brython locally by running the following pip command in the terminal :" }, { "code": null, "e": 1050, "s": 1030, "text": "pip install brython" }, { "code": null, "e": 1162, "s": 1050, "text": "You can also use Brython without having to install anything, just by including the Brython scripts from a CDN :" }, { "code": null, "e": 1167, "s": 1162, "text": "HTML" }, { "code": "<script src=\"https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js\"></script><script src=\"https://cdn.jsdelivr.net/npm/brython@3.8.9/brython_stdlib.js\"></script>", "e": 1333, "s": 1167, "text": null }, { "code": null, "e": 1372, "s": 1333, "text": "To use Brython, all there is to do is:" }, { "code": null, "e": 1542, "s": 1372, "text": "Load the script brython.js.Run the function brython() on page load, like <body onload=brython()>.Write Python code inside tags <script type=”text/python”> or linking it." }, { "code": null, "e": 1570, "s": 1542, "text": "Load the script brython.js." }, { "code": null, "e": 1641, "s": 1570, "text": "Run the function brython() on page load, like <body onload=brython()>." }, { "code": null, "e": 1714, "s": 1641, "text": "Write Python code inside tags <script type=”text/python”> or linking it." }, { "code": null, "e": 1757, "s": 1714, "text": "Example 1 : “Hello World !” using Brython”" }, { "code": null, "e": 1762, "s": 1757, "text": "HTML" }, { "code": "<!Doctype html><html><head> <meta charset = \"utf-8\"> <script type = \"text/javascript\" src = \"https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js\"> </script></head> <body onload = \"brython()\"><script type = \"text/python\">from browser import document document <= \"Hello World!\"</script></body></html>", "e": 2085, "s": 1762, "text": null }, { "code": null, "e": 2094, "s": 2085, "text": "Output :" }, { "code": null, "e": 2141, "s": 2094, "text": "Example 2 : Create an HTML table using Brython" }, { "code": null, "e": 2404, "s": 2141, "text": "To create a table, we use the HTML tags : TABLE (the table), TR (a table row), TH (a header cell) and TD (a cell). The table is made of rows, each row is made of cells, the first row is generally made of “header cells” describing the value in the matching column" }, { "code": null, "e": 2409, "s": 2404, "text": "HTML" }, { "code": "<!Doctype html><html> <head> <meta charset = \"utf-8\"> <script type = \"text/javascript\" src = \"https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js\"> </script></head> <body onload=\"brython()\"> <p id='zone'> </p> <script type=\"text/python\"> from browser import document from browser.html import TABLE, TR, TH, TD table = TABLE() # create a row row = TR() # add header cells row <= TH(\"Country\") row <= TH(\"Capital city\") # add the row to the table table <= row # add a row 1 row = TR() row <= TD(\"United States\") + TD(\"Washington\") table <= row # add a row 2 row = TR() row <= TD(\"India\") + TD(\"Delhi\") table <= row # erase initial content document['zone'].clear() # insert table in the element document['zone'] <= table </script></body></html>", "e": 3287, "s": 2409, "text": null }, { "code": null, "e": 3298, "s": 3287, "text": "Output : " }, { "code": null, "e": 3481, "s": 3298, "text": "Example 3 : We can build a table from a list of lists. In this example, we will only show the Python script, the surrounding HTML code will remain the same as in the previous example" }, { "code": null, "e": 3486, "s": 3481, "text": "HTML" }, { "code": "<script type=\"text/python\"> from browser import document from browser.html import TABLE, TR, TH, TD lines = [ ['Morrissey', 'vocals'], ['Kijibasu', 'guitar'], ['Rajpal', 'the drums'], ['Aayush', 'the bass guitar'] ] t = TABLE() for line in lines: t <= TR(TD(line[0])+TD(line[1])) document['zone'].text = '' document['zone']<= t</script>", "e": 3885, "s": 3486, "text": null }, { "code": null, "e": 3906, "s": 3885, "text": "Future of Brython : " }, { "code": null, "e": 4351, "s": 3906, "text": "Many Python developers are working on it to make it better, but it may be difficult that it can replace Javascript. There is no framework available in Brython. It may take many years for Brython to be used on client-side. There is a lack of resources to learn Brython, so people are choosing Javascript over Brython. But using Brython would be a great advantage for those developer who want to use one language for server side and client side. " }, { "code": null, "e": 4358, "s": 4351, "text": "Python" } ]
Oracle Database Connection in Python
Python can connect to oracle using a python package called cx_Oracle. Oracle is one of the famous and widely used database and python’s data processing features are leverages well using this connectivity. In this article we will see how we can connect to oracle database and query the DB. We can use the below command to install the python package which can be used for establishing the connectivity. pip install cx_Oracle Now using this module we can connect to a oracle database which is accessible through the oracle service name. We create a cursor and execute the SQl query through the cursor for creating a table. All this is handled through a try and except structure to catch any exception or failure in database connectivity. import cx_Oracle # Connecting to DB try: con = cx_Oracle.connect('username/password@servicename') cursor = con.cursor() #Creating a table cursor.execute("create table TableName(COL1 VARCHAR2(200),\COL2 NUMBER(8))") print("Table Created") except cx_Oracle.DatabaseError as e: print("Problem connecting to Oracle", e) # Close the all database operation finally: if cursor: cursor.close() if con: con.close() Running the above code gives us the following result − Table Created
[ { "code": null, "e": 1351, "s": 1062, "text": "Python can connect to oracle using a python package called cx_Oracle. Oracle is one of the famous and widely used database and python’s data processing features are leverages well using this connectivity. In this article we will see how we can connect to oracle database and query the DB." }, { "code": null, "e": 1463, "s": 1351, "text": "We can use the below command to install the python package which can be used for establishing the connectivity." }, { "code": null, "e": 1485, "s": 1463, "text": "pip install cx_Oracle" }, { "code": null, "e": 1797, "s": 1485, "text": "Now using this module we can connect to a oracle database which is accessible through the oracle service name. We create a cursor and execute the SQl query through the cursor for creating a table. All this is handled through a try and except structure to catch any exception or failure in database connectivity." }, { "code": null, "e": 2256, "s": 1797, "text": "import cx_Oracle\n# Connecting to DB\ntry:\n con = cx_Oracle.connect('username/password@servicename')\n cursor = con.cursor()\n \n #Creating a table\n cursor.execute(\"create table TableName(COL1 VARCHAR2(200),\\COL2 NUMBER(8))\")\n print(\"Table Created\")\n \nexcept cx_Oracle.DatabaseError as e:\n print(\"Problem connecting to Oracle\", e)\n # Close the all database operation\n finally:\n if cursor:\n cursor.close()\n if con:\n con.close()" }, { "code": null, "e": 2311, "s": 2256, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2325, "s": 2311, "text": "Table Created" } ]
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it). A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...) The code to be executed, by the function, is placed inside curly brackets: {} Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as local variables. A Function is much the same as a Procedure or a Subroutine, in other programming languages. The code inside the function will execute when "something" invokes (calls) the function: When an event occurs (when a user clicks a button) When it is invoked (called) from JavaScript code Automatically (self invoked) You will learn a lot more about function invocation later in this tutorial. When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller": Calculate the product of two numbers, and return the result: The result in x will be: You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results. Convert Fahrenheit to Celsius: Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result. Accessing a function without () will return the function object instead of the function result. Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations. Instead of using a variable to store the return value of a function: You can use the function directly, as a variable value: You will learn a lot more about functions later in this tutorial. Variables declared within a JavaScript function, become LOCAL to the function. Local variables can only be accessed from within the function. Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed. Execute the function named myFunction. function myFunction() { alert("Hello World!"); } ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 81, "s": 0, "text": "A JavaScript function is a block of code designed to perform a \nparticular task." }, { "code": null, "e": 156, "s": 81, "text": "A JavaScript function is executed when \n\"something\" invokes it (calls it)." }, { "code": null, "e": 265, "s": 156, "text": "A JavaScript function is defined with the function keyword, \nfollowed by a name, followed by parentheses ()." }, { "code": null, "e": 367, "s": 265, "text": "Function names can contain letters, digits, underscores, and dollar signs \n(same rules as variables)." }, { "code": null, "e": 462, "s": 367, "text": "The parentheses may include parameter names separated by commas:\n(parameter1, parameter2, ...)" }, { "code": null, "e": 540, "s": 462, "text": "The code to be executed, by the function, is placed inside curly brackets: {}" }, { "code": null, "e": 626, "s": 540, "text": "Function parameters are listed inside the parentheses () in \nthe function definition." }, { "code": null, "e": 706, "s": 626, "text": "Function arguments are the values \nreceived by the function when it is invoked." }, { "code": null, "e": 785, "s": 706, "text": "Inside the function, the arguments (the parameters) behave as local variables." }, { "code": null, "e": 877, "s": 785, "text": "A Function is much the same as a Procedure or a Subroutine, in other programming languages." }, { "code": null, "e": 967, "s": 877, "text": "The code inside the function will execute when \"something\" invokes (calls) the \nfunction:" }, { "code": null, "e": 1018, "s": 967, "text": "When an event occurs (when a user clicks a button)" }, { "code": null, "e": 1067, "s": 1018, "text": "When it is invoked (called) from JavaScript code" }, { "code": null, "e": 1096, "s": 1067, "text": "Automatically (self invoked)" }, { "code": null, "e": 1173, "s": 1096, "text": "You will learn a lot more about function invocation later in this \ntutorial." }, { "code": null, "e": 1252, "s": 1173, "text": "When JavaScript reaches a return statement, \nthe function will stop executing." }, { "code": null, "e": 1374, "s": 1252, "text": "If the function was invoked from a statement, JavaScript will \n\"return\" to execute the code after the invoking statement." }, { "code": null, "e": 1469, "s": 1374, "text": "Functions often compute a return value. The return value is \n\"returned\" back to \nthe \"caller\":" }, { "code": null, "e": 1530, "s": 1469, "text": "Calculate the product of two numbers, and return the result:" }, { "code": null, "e": 1555, "s": 1530, "text": "The result in x will be:" }, { "code": null, "e": 1620, "s": 1555, "text": "You can reuse code: Define the code once, and use it many times." }, { "code": null, "e": 1714, "s": 1620, "text": "You can use the same code many times with different arguments, to produce different \nresults." }, { "code": null, "e": 1745, "s": 1714, "text": "Convert Fahrenheit to Celsius:" }, { "code": null, "e": 1859, "s": 1745, "text": "Using the example above, toCelsius refers to the function object, and \ntoCelsius() refers to the function result." }, { "code": null, "e": 1956, "s": 1859, "text": "Accessing a function without () will return the function object instead of \nthe function result." }, { "code": null, "e": 2071, "s": 1956, "text": "Functions can be used the same way as you use variables, in all types of formulas, assignments, and \ncalculations." }, { "code": null, "e": 2140, "s": 2071, "text": "Instead of using a variable to store the return value of a function:" }, { "code": null, "e": 2196, "s": 2140, "text": "You can use the function directly, as a variable value:" }, { "code": null, "e": 2262, "s": 2196, "text": "You will learn a lot more about functions later in this tutorial." }, { "code": null, "e": 2343, "s": 2262, "text": "Variables declared within a JavaScript function, become \nLOCAL to \nthe function." }, { "code": null, "e": 2407, "s": 2343, "text": "Local variables can only be accessed \nfrom within the function." }, { "code": null, "e": 2538, "s": 2407, "text": "Since local variables are only recognized inside their functions, variables with the same name can be used in different functions." }, { "code": null, "e": 2634, "s": 2538, "text": "Local variables are created when a function starts, and deleted when the function is completed." }, { "code": null, "e": 2673, "s": 2634, "text": "Execute the function named myFunction." }, { "code": null, "e": 2727, "s": 2673, "text": "function myFunction() {\n alert(\"Hello World!\");\n}\n;\n" }, { "code": null, "e": 2746, "s": 2727, "text": "Start the Exercise" }, { "code": null, "e": 2779, "s": 2746, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2821, "s": 2779, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2928, "s": 2821, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2947, "s": 2928, "text": "help@w3schools.com" } ]
AvatarGAN — Generate Cartoon Images using GAN | by Aakash Jhawar | Towards Data Science
Most of us have created our own customized bitmoji and used them across different social media apps. Those bitmoji are personalized for a particular user. But have you ever wondered how to generate bitmoji that doesn't belong to any human face? Well, let's explore how GANs do the job for us. Generative Adversarial Networks are one of the most interesting ideas in computer science today. GANs can generate images from garbage datasets. GANs were developed by Ian J. Goodfellow in 2014. It consists of two neural networks which compete with each other to become more accurate in their prediction. The generative model finds out the features in the input data and is able to analyze, capture and copy the variations within the dataset and generate new images that look similar to that of the input set in an unsupervised fashion. For instance, GANs can create images that resemble photos of human faces. All these images generated by GAN have a common pattern. Every face's eyes lies in the same coordinates. The background is just a blurred random texture. If there are multiple faces, the shape of the second face is very distorted. Before we get our hands dirty while diving into the training part, let's understand how GANs work. Generative as the name suggests tries to generate fake images that look like real images. It learns the probability of features X. The generator takes noise (random features) as input noise. The discriminator is a binary classifier and tries to discriminate the real images and the images created by the generator. It learns the probability of class Y (real or fake) given features X. The probabilities are the feedback for the generator. Generator learns to make fakes that look real. Discriminator learns to distinguish real from fake. Steps involved in training GANs: Define Generator and Discriminator network architectureTrain the Generator model to generate the fake data that can fool DiscriminatorTrain the Discriminator model to distinguish real vs fake dataContinue the training for several epochs and save the Generator model Define Generator and Discriminator network architecture Train the Generator model to generate the fake data that can fool Discriminator Train the Discriminator model to distinguish real vs fake data Continue the training for several epochs and save the Generator model In essence, we take the random noise, pass it through Generator. The generator generates the fake image. This output image is passed to the Discriminator along with a stream of images from the real image dataset. Both real and fake images are given to the Discriminator which returns the probability of authenticity of the image. Then we compute the cost function from the Discriminator output and update both model’s weights. Noise → Generator → Features → Discriminator → Output → Cost (output) Now that we have gone through the basics of GAN, it's time to do the heavy lifting and train the model. We will train our GAN on Cartoon Set, a collection of random 2 dimension cartoon avatar images. The cartoons vary in 10 artwork categories, 4 colour categories, and 4 proportion categories, so we have a lot of possible combinations. We will use the dataset with 100,000 randomly chosen cartoon images. The next step is to read all the images. Since we have a lot of images to read and process, this task can take a while. So we will read all the images, convert them to JPG format, resize it, normalize it and store the preprocessed image as a binary file. It is more efficient to perform these series of steps only once. This way we can simply read the processed image data and quickly use it. We will create a Numpy array of all the images and save it as a .npy file. We are using Numpy binary instead of Pickle because the file is very large and may cause problems with some versions of Pickle. Now, to hold the images in memory we will use TensorFlow tf.data.Dataset. Dataset object is used to write descriptive and efficient input pipelines. The iteration happens in a streaming fashion, so the full dataset does not need to fit into memory. Both the models are using Keras Sequential class. Generator The generator needs upsampling layers to generate an image from noise i.e., seed. We can use UpSampling2D() and Conv2DTranspose() for upsampling. UpSampling2D is just a simple scaling up of the image matrix by using some upsampling techniques. Mostly we use the nearest neighbour or bilinear upsampling. So no machine is learning here. The benefit of UpSampling2D is it’s cheap. Whereas, Conv2DTranspose layer is a convolution operation and learns several filters similar to the regular Conv2D layer. The transpose layer simply swaps the backward and forward pass, keeping the rest of the operations the same. Conv2DTranspose will also upsample its input but the key difference is that the model should learn what are the best upsampling features for the job. The first layer is a Dense layer whose input is the seed noise. Then we upsample it multiple times until the size is 28x28x1. We will use LeakyReLU activation function through the net for Generator, and for the last layer, we will use tanh. Let’s try to plot the image generated by Generator Neural Network. Discriminator Discriminator network is a simple Convolution Neural Network image classifier. Let’s check out the output of our Discriminator model. Output: tf.Tensor([0.50059265]], shape=(1, 1), dtype=float32) It returns the probability score. We will use the Binary Cross-Entropy loss function. BCE cost function has two parts, one relevant for each class. The value is close to zero when the label and prediction are similar but approaches infinity when the label and the prediction are different. Let’s break down the equation and analyze each part. Discriminator loss quantifies how well the discriminator model can distinguish real and fake images. It compares the discriminator’s prediction on real images to an array of 1s, and the discriminator’s prediction on fake images to an array of 0s. Generator loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the discriminator's decision on the generated images to an array of 1s. Both Generator and Discriminator model uses Adam optimizer and the same learning rate and momentum. Their optimizers are different since we are training two different networks separately. Now that we have defined the major components of the training pipeline, let's move to the training section. The following function is where the magic happens. Notice the use of tf.function annotation. This percompiles the function and improves the performance. The two neural networks must be trained independently in two separate passes. Because of which we have defined two separate loss functions and separate updates for the gradients. During backpropagation for the discriminator model, it is necessary that the discriminator’s gradient is only applied to reduce the discriminator’s loss, and only the weights for this model get updated. The model will not learn if the generative model’s weights are also updated at the same time. The training dataset should be normalized. An equal number of samples for both the class is a must. For the discriminator training set, the input images will be x and y containing the value of 1 for real images and 0 for generated ones. Whereas for the generator training set, x contains the random noise (seed) and y is always 1. Here the aim of the generator is to generate such good images that the discriminator gets fooled and assigns them a probability close to 1. Now since we have everything in place, let's start the training. train(train_dataset, EPOCHS) Check out the model being trained to generate cartoon images. A pat on the back! Our model is finally trained and it's time to save it so that we can use it in the future. generator.save(os.path.join(DATA_PATH, "face_generator.h5")) Now that we know the functioning of GAN, it’s time to check the fascinating applications of it. There is a plethora of usage of GAN regularly published in research. With the help of GANs, we can perform the translation of photos. Phillip Isola in the paper demonstrated the pix2pix approach for many image-to-image translation tasks. For example, using GANs we can convert horse images into zebra, create colour photographs from sketches, colour black and white images, and the list goes on. With the rise of AI, the risk for fraud and cyber threats also increased. A huge amount of confidential information can be leaked by cyber threats. GANs can be used to prevent “adversarial attacks”. These adversarial attacks use a variety of techniques to fool deep learning architectures. GAN can create more such fake examples and we can easily flag them off by training the model on the fake generated examples. SSGAN is used to perform Steganalysis and detect hidden encodings in images that ideally should not be there. GANs can also be used to generate synthetic data for supervision. GANs can be used to perform photograph inpainting or spot filling i.e., to fill the missing area of the photograph that was removed or got destroyed for some reason. The paper Context Encoders: Feature Learning by Inpainting has described the use of Context encoders to perform the photo inpainting. Jiajun Wu has proposed a GAN that can be used to generate three-dimensional objects like a gun, chair, car, sofa, and table. The generator’s goal is to fool the discriminator whereas the discriminator tries to distinguish between real and fake. Both the models learn from the competition with each other. And in the end, fake looks real. The idea of generating data opens a new potential but unfortunately great dangers too. If you’ve hung in this long... thanks! I hope this has been a learning experience for you. If you enjoyed this article, share it with your friends and colleagues. Drop me a note if you find it useful or have any follow-up questions. For the lazy among you who have skipped reading or performing the tutorial yourselves, here’s a link to the source code.
[ { "code": null, "e": 465, "s": 172, "text": "Most of us have created our own customized bitmoji and used them across different social media apps. Those bitmoji are personalized for a particular user. But have you ever wondered how to generate bitmoji that doesn't belong to any human face? Well, let's explore how GANs do the job for us." }, { "code": null, "e": 770, "s": 465, "text": "Generative Adversarial Networks are one of the most interesting ideas in computer science today. GANs can generate images from garbage datasets. GANs were developed by Ian J. Goodfellow in 2014. It consists of two neural networks which compete with each other to become more accurate in their prediction." }, { "code": null, "e": 1076, "s": 770, "text": "The generative model finds out the features in the input data and is able to analyze, capture and copy the variations within the dataset and generate new images that look similar to that of the input set in an unsupervised fashion. For instance, GANs can create images that resemble photos of human faces." }, { "code": null, "e": 1307, "s": 1076, "text": "All these images generated by GAN have a common pattern. Every face's eyes lies in the same coordinates. The background is just a blurred random texture. If there are multiple faces, the shape of the second face is very distorted." }, { "code": null, "e": 1406, "s": 1307, "text": "Before we get our hands dirty while diving into the training part, let's understand how GANs work." }, { "code": null, "e": 1597, "s": 1406, "text": "Generative as the name suggests tries to generate fake images that look like real images. It learns the probability of features X. The generator takes noise (random features) as input noise." }, { "code": null, "e": 1845, "s": 1597, "text": "The discriminator is a binary classifier and tries to discriminate the real images and the images created by the generator. It learns the probability of class Y (real or fake) given features X. The probabilities are the feedback for the generator." }, { "code": null, "e": 1944, "s": 1845, "text": "Generator learns to make fakes that look real. Discriminator learns to distinguish real from fake." }, { "code": null, "e": 1977, "s": 1944, "text": "Steps involved in training GANs:" }, { "code": null, "e": 2243, "s": 1977, "text": "Define Generator and Discriminator network architectureTrain the Generator model to generate the fake data that can fool DiscriminatorTrain the Discriminator model to distinguish real vs fake dataContinue the training for several epochs and save the Generator model" }, { "code": null, "e": 2299, "s": 2243, "text": "Define Generator and Discriminator network architecture" }, { "code": null, "e": 2379, "s": 2299, "text": "Train the Generator model to generate the fake data that can fool Discriminator" }, { "code": null, "e": 2442, "s": 2379, "text": "Train the Discriminator model to distinguish real vs fake data" }, { "code": null, "e": 2512, "s": 2442, "text": "Continue the training for several epochs and save the Generator model" }, { "code": null, "e": 2939, "s": 2512, "text": "In essence, we take the random noise, pass it through Generator. The generator generates the fake image. This output image is passed to the Discriminator along with a stream of images from the real image dataset. Both real and fake images are given to the Discriminator which returns the probability of authenticity of the image. Then we compute the cost function from the Discriminator output and update both model’s weights." }, { "code": null, "e": 3009, "s": 2939, "text": "Noise → Generator → Features → Discriminator → Output → Cost (output)" }, { "code": null, "e": 3113, "s": 3009, "text": "Now that we have gone through the basics of GAN, it's time to do the heavy lifting and train the model." }, { "code": null, "e": 3415, "s": 3113, "text": "We will train our GAN on Cartoon Set, a collection of random 2 dimension cartoon avatar images. The cartoons vary in 10 artwork categories, 4 colour categories, and 4 proportion categories, so we have a lot of possible combinations. We will use the dataset with 100,000 randomly chosen cartoon images." }, { "code": null, "e": 4011, "s": 3415, "text": "The next step is to read all the images. Since we have a lot of images to read and process, this task can take a while. So we will read all the images, convert them to JPG format, resize it, normalize it and store the preprocessed image as a binary file. It is more efficient to perform these series of steps only once. This way we can simply read the processed image data and quickly use it. We will create a Numpy array of all the images and save it as a .npy file. We are using Numpy binary instead of Pickle because the file is very large and may cause problems with some versions of Pickle." }, { "code": null, "e": 4260, "s": 4011, "text": "Now, to hold the images in memory we will use TensorFlow tf.data.Dataset. Dataset object is used to write descriptive and efficient input pipelines. The iteration happens in a streaming fashion, so the full dataset does not need to fit into memory." }, { "code": null, "e": 4310, "s": 4260, "text": "Both the models are using Keras Sequential class." }, { "code": null, "e": 4320, "s": 4310, "text": "Generator" }, { "code": null, "e": 4466, "s": 4320, "text": "The generator needs upsampling layers to generate an image from noise i.e., seed. We can use UpSampling2D() and Conv2DTranspose() for upsampling." }, { "code": null, "e": 5080, "s": 4466, "text": "UpSampling2D is just a simple scaling up of the image matrix by using some upsampling techniques. Mostly we use the nearest neighbour or bilinear upsampling. So no machine is learning here. The benefit of UpSampling2D is it’s cheap. Whereas, Conv2DTranspose layer is a convolution operation and learns several filters similar to the regular Conv2D layer. The transpose layer simply swaps the backward and forward pass, keeping the rest of the operations the same. Conv2DTranspose will also upsample its input but the key difference is that the model should learn what are the best upsampling features for the job." }, { "code": null, "e": 5321, "s": 5080, "text": "The first layer is a Dense layer whose input is the seed noise. Then we upsample it multiple times until the size is 28x28x1. We will use LeakyReLU activation function through the net for Generator, and for the last layer, we will use tanh." }, { "code": null, "e": 5388, "s": 5321, "text": "Let’s try to plot the image generated by Generator Neural Network." }, { "code": null, "e": 5402, "s": 5388, "text": "Discriminator" }, { "code": null, "e": 5481, "s": 5402, "text": "Discriminator network is a simple Convolution Neural Network image classifier." }, { "code": null, "e": 5536, "s": 5481, "text": "Let’s check out the output of our Discriminator model." }, { "code": null, "e": 5598, "s": 5536, "text": "Output: tf.Tensor([0.50059265]], shape=(1, 1), dtype=float32)" }, { "code": null, "e": 5632, "s": 5598, "text": "It returns the probability score." }, { "code": null, "e": 5888, "s": 5632, "text": "We will use the Binary Cross-Entropy loss function. BCE cost function has two parts, one relevant for each class. The value is close to zero when the label and prediction are similar but approaches infinity when the label and the prediction are different." }, { "code": null, "e": 5941, "s": 5888, "text": "Let’s break down the equation and analyze each part." }, { "code": null, "e": 6188, "s": 5941, "text": "Discriminator loss quantifies how well the discriminator model can distinguish real and fake images. It compares the discriminator’s prediction on real images to an array of 1s, and the discriminator’s prediction on fake images to an array of 0s." }, { "code": null, "e": 6471, "s": 6188, "text": "Generator loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Here, we will compare the discriminator's decision on the generated images to an array of 1s." }, { "code": null, "e": 6659, "s": 6471, "text": "Both Generator and Discriminator model uses Adam optimizer and the same learning rate and momentum. Their optimizers are different since we are training two different networks separately." }, { "code": null, "e": 6818, "s": 6659, "text": "Now that we have defined the major components of the training pipeline, let's move to the training section. The following function is where the magic happens." }, { "code": null, "e": 6920, "s": 6818, "text": "Notice the use of tf.function annotation. This percompiles the function and improves the performance." }, { "code": null, "e": 7396, "s": 6920, "text": "The two neural networks must be trained independently in two separate passes. Because of which we have defined two separate loss functions and separate updates for the gradients. During backpropagation for the discriminator model, it is necessary that the discriminator’s gradient is only applied to reduce the discriminator’s loss, and only the weights for this model get updated. The model will not learn if the generative model’s weights are also updated at the same time." }, { "code": null, "e": 7867, "s": 7396, "text": "The training dataset should be normalized. An equal number of samples for both the class is a must. For the discriminator training set, the input images will be x and y containing the value of 1 for real images and 0 for generated ones. Whereas for the generator training set, x contains the random noise (seed) and y is always 1. Here the aim of the generator is to generate such good images that the discriminator gets fooled and assigns them a probability close to 1." }, { "code": null, "e": 7932, "s": 7867, "text": "Now since we have everything in place, let's start the training." }, { "code": null, "e": 7961, "s": 7932, "text": "train(train_dataset, EPOCHS)" }, { "code": null, "e": 8023, "s": 7961, "text": "Check out the model being trained to generate cartoon images." }, { "code": null, "e": 8133, "s": 8023, "text": "A pat on the back! Our model is finally trained and it's time to save it so that we can use it in the future." }, { "code": null, "e": 8194, "s": 8133, "text": "generator.save(os.path.join(DATA_PATH, \"face_generator.h5\"))" }, { "code": null, "e": 8359, "s": 8194, "text": "Now that we know the functioning of GAN, it’s time to check the fascinating applications of it. There is a plethora of usage of GAN regularly published in research." }, { "code": null, "e": 8686, "s": 8359, "text": "With the help of GANs, we can perform the translation of photos. Phillip Isola in the paper demonstrated the pix2pix approach for many image-to-image translation tasks. For example, using GANs we can convert horse images into zebra, create colour photographs from sketches, colour black and white images, and the list goes on." }, { "code": null, "e": 9101, "s": 8686, "text": "With the rise of AI, the risk for fraud and cyber threats also increased. A huge amount of confidential information can be leaked by cyber threats. GANs can be used to prevent “adversarial attacks”. These adversarial attacks use a variety of techniques to fool deep learning architectures. GAN can create more such fake examples and we can easily flag them off by training the model on the fake generated examples." }, { "code": null, "e": 9277, "s": 9101, "text": "SSGAN is used to perform Steganalysis and detect hidden encodings in images that ideally should not be there. GANs can also be used to generate synthetic data for supervision." }, { "code": null, "e": 9577, "s": 9277, "text": "GANs can be used to perform photograph inpainting or spot filling i.e., to fill the missing area of the photograph that was removed or got destroyed for some reason. The paper Context Encoders: Feature Learning by Inpainting has described the use of Context encoders to perform the photo inpainting." }, { "code": null, "e": 9702, "s": 9577, "text": "Jiajun Wu has proposed a GAN that can be used to generate three-dimensional objects like a gun, chair, car, sofa, and table." }, { "code": null, "e": 10002, "s": 9702, "text": "The generator’s goal is to fool the discriminator whereas the discriminator tries to distinguish between real and fake. Both the models learn from the competition with each other. And in the end, fake looks real. The idea of generating data opens a new potential but unfortunately great dangers too." }, { "code": null, "e": 10235, "s": 10002, "text": "If you’ve hung in this long... thanks! I hope this has been a learning experience for you. If you enjoyed this article, share it with your friends and colleagues. Drop me a note if you find it useful or have any follow-up questions." } ]
C Program To Check whether Matrix is Skew Symmetric or not - GeeksforGeeks
29 Nov, 2020 A Skew Symmetric Matrix or Anti-Symmetric Matrix is a square matrix whose transpose is negative to that of the original matrix. If the entry in the ith row and jth column of a matrix is a[i][j], i.e. if A = (a[i][j]) then the skew symmetric condition is -A = -a[j][i].Examples : Input : matrix: 0 5 -4 -5 0 1 4 -1 0 Output: Transpose matrix: 0 -5 4 5 0 -1 -4 1 0 Skew Symmetric matrix Steps: Find the transpose of the input matrix.If the input matrix is equal to the negative of its transpose matrix, then the matrix is Skew Symmetrical. Find the transpose of the input matrix. If the input matrix is equal to the negative of its transpose matrix, then the matrix is Skew Symmetrical. Java C++ C# Python3 // java program to check// whether given matrix// is skew-symmetric or notimport java.io.*; class GFG { static int ROW =3;static int COL =3; // Utility function to create transpose matrix static void transpose(int transpose_matrix[][], int matrix[][]){for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) transpose_matrix[j][i] = matrix[i][j];} // Utility function to check skew - symmetric// matrix condition static boolean check(int transpose_matrix[][], int matrix[][]){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (matrix[i][j] != -transpose_matrix[i][j]) return false; return true;} // Utility function to print a matrix static void printMatrix(int matrix[][]){ for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) System.out.print(matrix[i][j] + " "); System.out.println(); }} // Driver program to test above functionspublic static void main (String[] args) { int matrix[][] = { {0, 5, -4}, {-5, 0, 1}, {4, -1, 0}, }; int transpose_matrix[][] = new int[ROW][COL]; // Function create transpose matrix transpose(transpose_matrix, matrix); System.out.println ("Transpose matrix: "); printMatrix(transpose_matrix); // Check whether matrix is skew-symmetric or not if (check(transpose_matrix, matrix)) System.out.println("Skew Symmetric Matrix"); else System.out.println("Not Skew Symmetric Matrix"); }} // This code is contributed by vt_m. // C program to check whether given matrix// is skew-symmetric or not#include <stdio.h>#include <stdlib.h> #define ROW 3#define COL 3 // Utility function to create transpose matrixvoid transpose(int transpose_matrix[ROW][COL], int matrix[ROW][COL]){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) transpose_matrix[j][i] = matrix[i][j];} // Utility function to check skew - symmetric// matrix conditionbool check(int transpose_matrix[ROW][COL], int matrix[ROW][COL]){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (matrix[i][j] != -transpose_matrix[i][j]) return false; return true;} // Utility function to print a matrixvoid printMatrix(int matrix[ROW][COL]){ for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) printf("%d ", matrix[i][j]); printf("\n"); }} // Driver program to test above functionsint main(){ int matrix[ROW][COL] = { {0, 5, -4}, {-5, 0, 1}, {4, -1, 0}, }; int transpose_matrix[ROW][COL]; // Function create transpose matrix transpose(transpose_matrix, matrix); printf ("Transpose matrix: \n"); printMatrix(transpose_matrix); // Check whether matrix is skew-symmetric or not if (check(transpose_matrix, matrix)) printf("Skew Symmetric Matrix"); else printf("Not Skew Symmetric Matrix"); return 0;} // C# program to check// whether given matrix// is skew-symmetric or notusing System; class GFG{static int ROW =3;static int COL =3; // Utility function to// create transpose matrixstatic void transpose(int [,]transpose_matrix, int [,]matrix){for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) transpose_matrix[j,i] = matrix[i,j];} // Utility function to check// skew - symmetric matrix// conditionstatic bool check(int [,]transpose_matrix, int [,]matrix){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (matrix[i, j] != -transpose_matrix[i, j]) return false; return true;} // Utility function// to print a matrixstatic void printMatrix(int [,]matrix){ for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) Console.Write(matrix[i, j] + " "); Console.WriteLine(); }} // Driver Codepublic static void Main (){ int [,]matrix = {{0, 5, -4}, {-5, 0, 1}, {4, -1, 0},}; int [,]transpose_matrix = new int[ROW, COL]; // Function create transpose matrix transpose(transpose_matrix, matrix); Console.WriteLine("Transpose matrix: "); printMatrix(transpose_matrix); // Check whether matrix is // skew-symmetric or not if (check(transpose_matrix, matrix)) Console.WriteLine("Skew Symmetric Matrix"); else Console.WriteLine("Not Skew Symmetric Matrix"); }} // This code is contributed by anuj_67. # Python 3 program to check# whether given matrix# is skew-symmetric or notROW=3COL=3 # Utility function to# create transpose matrixdef transpose(transpose_matrix,matrix): for i in range (ROW): for j in range(COL): transpose_matrix[j][i] = matrix[i][j] # Utility function to# check skew - symmetric# matrix conditiondef check(transpose_matrix,matrix): for i in range(ROW): for j in range(COL): if (matrix[i][j] != -transpose_matrix[i][j]): return False return True # Utility function to print a matrixdef printMatrix(matrix): for i in range (ROW): for j in range(COL): print(matrix[i][j]," ",end="") print() # Driver program to test above functionsmatrix= [ [0, 5, -4], [-5, 0, 1], [4, -1, 0], ]transpose_matrix=[[0 for i in range(3)] for j in range(3)] # Function create transpose matrixtranspose(transpose_matrix, matrix)print("Transpose matrix:")printMatrix(transpose_matrix) # Check whether matrix is# skew-symmetric or notif (check(transpose_matrix, matrix)): print("Skew Symmetric Matrix")else: print("Not Skew Symmetric Matrix") # This code is contributed# by Azkia Anam. Transpose matrix: 0 -5 4 5 0 -1 -4 1 0 Skew Symmetric Matrix References : WikipediaThis article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m pradiptamukherjee Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Unique paths in a Grid with Obstacles Check for possible path in 2D matrix A Boolean Matrix Question Mathematics | L U Decomposition of a System of Linear Equations Python program to add two Matrices Program to find the Sum of each Row and each Column of a Matrix Flood fill Algorithm - how to implement fill() in paint? Implementation of BFS using adjacency matrix Breadth First Traversal ( BFS ) on a 2D array Efficiently compute sums of diagonals of a matrix
[ { "code": null, "e": 24530, "s": 24502, "text": "\n29 Nov, 2020" }, { "code": null, "e": 24811, "s": 24530, "text": "A Skew Symmetric Matrix or Anti-Symmetric Matrix is a square matrix whose transpose is negative to that of the original matrix. If the entry in the ith row and jth column of a matrix is a[i][j], i.e. if A = (a[i][j]) then the skew symmetric condition is -A = -a[j][i].Examples : " }, { "code": null, "e": 25090, "s": 24811, "text": "Input : matrix: 0 5 -4 \n -5 0 1 \n 4 -1 0 \n\nOutput: \nTranspose matrix: 0 -5 4\n 5 0 -1\n -4 1 0\nSkew Symmetric matrix" }, { "code": null, "e": 25099, "s": 25090, "text": "Steps: " }, { "code": null, "e": 25245, "s": 25099, "text": "Find the transpose of the input matrix.If the input matrix is equal to the negative of its transpose matrix, then the matrix is Skew Symmetrical." }, { "code": null, "e": 25285, "s": 25245, "text": "Find the transpose of the input matrix." }, { "code": null, "e": 25392, "s": 25285, "text": "If the input matrix is equal to the negative of its transpose matrix, then the matrix is Skew Symmetrical." }, { "code": null, "e": 25401, "s": 25396, "text": "Java" }, { "code": null, "e": 25405, "s": 25401, "text": "C++" }, { "code": null, "e": 25408, "s": 25405, "text": "C#" }, { "code": null, "e": 25416, "s": 25408, "text": "Python3" }, { "code": "// java program to check// whether given matrix// is skew-symmetric or notimport java.io.*; class GFG { static int ROW =3;static int COL =3; // Utility function to create transpose matrix static void transpose(int transpose_matrix[][], int matrix[][]){for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) transpose_matrix[j][i] = matrix[i][j];} // Utility function to check skew - symmetric// matrix condition static boolean check(int transpose_matrix[][], int matrix[][]){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (matrix[i][j] != -transpose_matrix[i][j]) return false; return true;} // Utility function to print a matrix static void printMatrix(int matrix[][]){ for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) System.out.print(matrix[i][j] + \" \"); System.out.println(); }} // Driver program to test above functionspublic static void main (String[] args) { int matrix[][] = { {0, 5, -4}, {-5, 0, 1}, {4, -1, 0}, }; int transpose_matrix[][] = new int[ROW][COL]; // Function create transpose matrix transpose(transpose_matrix, matrix); System.out.println (\"Transpose matrix: \"); printMatrix(transpose_matrix); // Check whether matrix is skew-symmetric or not if (check(transpose_matrix, matrix)) System.out.println(\"Skew Symmetric Matrix\"); else System.out.println(\"Not Skew Symmetric Matrix\"); }} // This code is contributed by vt_m.", "e": 27072, "s": 25416, "text": null }, { "code": "// C program to check whether given matrix// is skew-symmetric or not#include <stdio.h>#include <stdlib.h> #define ROW 3#define COL 3 // Utility function to create transpose matrixvoid transpose(int transpose_matrix[ROW][COL], int matrix[ROW][COL]){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) transpose_matrix[j][i] = matrix[i][j];} // Utility function to check skew - symmetric// matrix conditionbool check(int transpose_matrix[ROW][COL], int matrix[ROW][COL]){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (matrix[i][j] != -transpose_matrix[i][j]) return false; return true;} // Utility function to print a matrixvoid printMatrix(int matrix[ROW][COL]){ for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) printf(\"%d \", matrix[i][j]); printf(\"\\n\"); }} // Driver program to test above functionsint main(){ int matrix[ROW][COL] = { {0, 5, -4}, {-5, 0, 1}, {4, -1, 0}, }; int transpose_matrix[ROW][COL]; // Function create transpose matrix transpose(transpose_matrix, matrix); printf (\"Transpose matrix: \\n\"); printMatrix(transpose_matrix); // Check whether matrix is skew-symmetric or not if (check(transpose_matrix, matrix)) printf(\"Skew Symmetric Matrix\"); else printf(\"Not Skew Symmetric Matrix\"); return 0;}", "e": 28611, "s": 27072, "text": null }, { "code": "// C# program to check// whether given matrix// is skew-symmetric or notusing System; class GFG{static int ROW =3;static int COL =3; // Utility function to// create transpose matrixstatic void transpose(int [,]transpose_matrix, int [,]matrix){for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) transpose_matrix[j,i] = matrix[i,j];} // Utility function to check// skew - symmetric matrix// conditionstatic bool check(int [,]transpose_matrix, int [,]matrix){ for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) if (matrix[i, j] != -transpose_matrix[i, j]) return false; return true;} // Utility function// to print a matrixstatic void printMatrix(int [,]matrix){ for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) Console.Write(matrix[i, j] + \" \"); Console.WriteLine(); }} // Driver Codepublic static void Main (){ int [,]matrix = {{0, 5, -4}, {-5, 0, 1}, {4, -1, 0},}; int [,]transpose_matrix = new int[ROW, COL]; // Function create transpose matrix transpose(transpose_matrix, matrix); Console.WriteLine(\"Transpose matrix: \"); printMatrix(transpose_matrix); // Check whether matrix is // skew-symmetric or not if (check(transpose_matrix, matrix)) Console.WriteLine(\"Skew Symmetric Matrix\"); else Console.WriteLine(\"Not Skew Symmetric Matrix\"); }} // This code is contributed by anuj_67.", "e": 30171, "s": 28611, "text": null }, { "code": "# Python 3 program to check# whether given matrix# is skew-symmetric or notROW=3COL=3 # Utility function to# create transpose matrixdef transpose(transpose_matrix,matrix): for i in range (ROW): for j in range(COL): transpose_matrix[j][i] = matrix[i][j] # Utility function to# check skew - symmetric# matrix conditiondef check(transpose_matrix,matrix): for i in range(ROW): for j in range(COL): if (matrix[i][j] != -transpose_matrix[i][j]): return False return True # Utility function to print a matrixdef printMatrix(matrix): for i in range (ROW): for j in range(COL): print(matrix[i][j],\" \",end=\"\") print() # Driver program to test above functionsmatrix= [ [0, 5, -4], [-5, 0, 1], [4, -1, 0], ]transpose_matrix=[[0 for i in range(3)] for j in range(3)] # Function create transpose matrixtranspose(transpose_matrix, matrix)print(\"Transpose matrix:\")printMatrix(transpose_matrix) # Check whether matrix is# skew-symmetric or notif (check(transpose_matrix, matrix)): print(\"Skew Symmetric Matrix\")else: print(\"Not Skew Symmetric Matrix\") # This code is contributed# by Azkia Anam.", "e": 31408, "s": 30171, "text": null }, { "code": null, "e": 31474, "s": 31408, "text": "Transpose matrix: \n0 -5 4 \n5 0 -1 \n-4 1 0 \nSkew Symmetric Matrix\n" }, { "code": null, "e": 31920, "s": 31474, "text": "References : WikipediaThis article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31927, "s": 31922, "text": "vt_m" }, { "code": null, "e": 31945, "s": 31927, "text": "pradiptamukherjee" }, { "code": null, "e": 31952, "s": 31945, "text": "Matrix" }, { "code": null, "e": 31959, "s": 31952, "text": "Matrix" }, { "code": null, "e": 32057, "s": 31959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32066, "s": 32057, "text": "Comments" }, { "code": null, "e": 32079, "s": 32066, "text": "Old Comments" }, { "code": null, "e": 32117, "s": 32079, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 32154, "s": 32117, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 32180, "s": 32154, "text": "A Boolean Matrix Question" }, { "code": null, "e": 32244, "s": 32180, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 32279, "s": 32244, "text": "Python program to add two Matrices" }, { "code": null, "e": 32343, "s": 32279, "text": "Program to find the Sum of each Row and each Column of a Matrix" }, { "code": null, "e": 32400, "s": 32343, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 32445, "s": 32400, "text": "Implementation of BFS using adjacency matrix" }, { "code": null, "e": 32491, "s": 32445, "text": "Breadth First Traversal ( BFS ) on a 2D array" } ]
Count number of even and odd elements in an array in C++
In this tutorial, we will be discussing a program to find the number of even and odd elements in an array. For this we will be provided with an array. Our task is to calculate the number of even and odd elements in the given array. Live Demo #include<iostream> using namespace std; void CountingEvenOdd(int arr[], int arr_size){ int even_count = 0; int odd_count = 0; //looping through the elements for(int i = 0 ; i < arr_size ; i++) { //checking if the number is odd if (arr[i]%2 != 0) odd_count ++ ; else even_count ++ ; } cout << "Number of even elements = " << even_count << "\nNumber of odd elements = " << odd_count ; } int main(){ int arr[] = {2, 3, 4, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); CountingEvenOdd(arr, n); } Number of even elements = 3 Number of odd elements = 2
[ { "code": null, "e": 1169, "s": 1062, "text": "In this tutorial, we will be discussing a program to find the number of even and odd elements in an array." }, { "code": null, "e": 1294, "s": 1169, "text": "For this we will be provided with an array. Our task is to calculate the number of even and odd elements in the given array." }, { "code": null, "e": 1305, "s": 1294, "text": " Live Demo" }, { "code": null, "e": 1865, "s": 1305, "text": "#include<iostream>\nusing namespace std;\nvoid CountingEvenOdd(int arr[], int arr_size){\n int even_count = 0;\n int odd_count = 0;\n //looping through the elements\n for(int i = 0 ; i < arr_size ; i++) {\n //checking if the number is odd\n if (arr[i]%2 != 0)\n odd_count ++ ;\n else\n even_count ++ ;\n }\n cout << \"Number of even elements = \" << even_count\n << \"\\nNumber of odd elements = \" << odd_count ;\n}\nint main(){\n int arr[] = {2, 3, 4, 5, 6};\n int n = sizeof(arr) / sizeof(arr[0]);\n CountingEvenOdd(arr, n);\n}" }, { "code": null, "e": 1920, "s": 1865, "text": "Number of even elements = 3\nNumber of odd elements = 2" } ]
Tryit Editor v3.7
Tryit: HTML euro symbol
[]
How to Convert Bytes to String in Python ? - GeeksforGeeks
11 Dec, 2020 Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. We can convert bytes to string using the below methods: Method #1: Using decode() method This method is used to convert from one encoding scheme, in which the argument string is encoded to the desired encoding scheme. This works opposite to the encode. Python3 # Program for converting bytes # to string using decode() data = b'GeeksForGeeks' # display inputprint('\nInput:')print(data)print(type(data)) # convertingoutput = data.decode() # display outputprint('\nOutput:')print(output)print(type(output)) Output: Input: b'GeeksForGeeks' <class 'bytes'> Output: GeeksForGeeks <class 'str'> Method #2: Using str() function The str() function of Python returns the string version of the object. Python3 # Program for converting bytes to string using decode()data = b'GeeksForGeeks' # display inputprint('\nInput:')print(data)print(type(data)) # convertingoutput = str(data, 'UTF-8') # display outputprint('\nOutput:')print(output)print(type(output)) Output: Input: b'GeeksForGeeks' <class 'bytes'> Output: GeeksForGeeks <class 'str'> Method #3: Using codecs.decode() method This method is used to decode the binary string into normal form. Python3 # Program for converting bytes to string using decode() # import required moduleimport codecs data = b'GeeksForGeeks' # display inputprint('\nInput:')print(data)print(type(data)) # convertingoutput = codecs.decode(data) # display outputprint('\nOutput:')print(output)print(type(output)) Output: Input: b'GeeksForGeeks' <class 'bytes'> Output: GeeksForGeeks <class 'str'> python-basics Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n11 Dec, 2020" }, { "code": null, "e": 24229, "s": 23925, "text": "Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes." }, { "code": null, "e": 24285, "s": 24229, "text": "We can convert bytes to string using the below methods:" }, { "code": null, "e": 24318, "s": 24285, "text": "Method #1: Using decode() method" }, { "code": null, "e": 24482, "s": 24318, "text": "This method is used to convert from one encoding scheme, in which the argument string is encoded to the desired encoding scheme. This works opposite to the encode." }, { "code": null, "e": 24490, "s": 24482, "text": "Python3" }, { "code": "# Program for converting bytes # to string using decode() data = b'GeeksForGeeks' # display inputprint('\\nInput:')print(data)print(type(data)) # convertingoutput = data.decode() # display outputprint('\\nOutput:')print(output)print(type(output))", "e": 24739, "s": 24490, "text": null }, { "code": null, "e": 24747, "s": 24739, "text": "Output:" }, { "code": null, "e": 24824, "s": 24747, "text": "Input:\nb'GeeksForGeeks'\n<class 'bytes'>\n\nOutput:\nGeeksForGeeks\n<class 'str'>" }, { "code": null, "e": 24856, "s": 24824, "text": "Method #2: Using str() function" }, { "code": null, "e": 24927, "s": 24856, "text": "The str() function of Python returns the string version of the object." }, { "code": null, "e": 24935, "s": 24927, "text": "Python3" }, { "code": "# Program for converting bytes to string using decode()data = b'GeeksForGeeks' # display inputprint('\\nInput:')print(data)print(type(data)) # convertingoutput = str(data, 'UTF-8') # display outputprint('\\nOutput:')print(output)print(type(output))", "e": 25185, "s": 24935, "text": null }, { "code": null, "e": 25193, "s": 25185, "text": "Output:" }, { "code": null, "e": 25270, "s": 25193, "text": "Input:\nb'GeeksForGeeks'\n<class 'bytes'>\n\nOutput:\nGeeksForGeeks\n<class 'str'>" }, { "code": null, "e": 25310, "s": 25270, "text": "Method #3: Using codecs.decode() method" }, { "code": null, "e": 25376, "s": 25310, "text": "This method is used to decode the binary string into normal form." }, { "code": null, "e": 25384, "s": 25376, "text": "Python3" }, { "code": "# Program for converting bytes to string using decode() # import required moduleimport codecs data = b'GeeksForGeeks' # display inputprint('\\nInput:')print(data)print(type(data)) # convertingoutput = codecs.decode(data) # display outputprint('\\nOutput:')print(output)print(type(output))", "e": 25676, "s": 25384, "text": null }, { "code": null, "e": 25684, "s": 25676, "text": "Output:" }, { "code": null, "e": 25761, "s": 25684, "text": "Input:\nb'GeeksForGeeks'\n<class 'bytes'>\n\nOutput:\nGeeksForGeeks\n<class 'str'>" }, { "code": null, "e": 25775, "s": 25761, "text": "python-basics" }, { "code": null, "e": 25799, "s": 25775, "text": "Technical Scripter 2020" }, { "code": null, "e": 25806, "s": 25799, "text": "Python" }, { "code": null, "e": 25825, "s": 25806, "text": "Technical Scripter" }, { "code": null, "e": 25923, "s": 25825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25932, "s": 25923, "text": "Comments" }, { "code": null, "e": 25945, "s": 25932, "text": "Old Comments" }, { "code": null, "e": 25977, "s": 25945, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26033, "s": 25977, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26075, "s": 26033, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26117, "s": 26075, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26153, "s": 26117, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26175, "s": 26153, "text": "Defaultdict in Python" }, { "code": null, "e": 26214, "s": 26175, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26241, "s": 26214, "text": "Python Classes and Objects" }, { "code": null, "e": 26272, "s": 26241, "text": "Python | os.path.join() method" } ]
Neural Network Plays Flappy Bird. Currently, I am an IT student in... | by Woojae Kim | Towards Data Science
Currently, I am an IT student in college. This semester, I had a really interesting course which I choose my own topic to study, and create my own project. So I decided to learn and work on something very interesting and unique. While I was exploring various topic, I found a video tutorial about Neural Network, and I was really interested in learning this topic. After watching the tutorial video, I come up with an idea to implement a neural network program that learns how to play Flappy Bird game. Finally, this is my result. When the program runs first time, it does nothing because it has no idea about the game. However, a few hours of training, it learns how to play the game. In this posting, I want to give a basic information about Neural network and how I implemented my program. First of all, I want to talk about what neural network is. In programming, artificial neural network is computational model/algorithm for machine learning that is inspired by structure and functional aspects of biological neural networks. Every neural network has one input layer, one output layer and one or more hidden layers. Each circle represents a neuron and a neuron has a connection to every neuron in the next layer. Each connection has weight value and each neuron has a bias value. For example, below diagram shows what’s happening in the neural network. When neural network calculate the output, it does a lot of math with weight and bias. You can easily expect that if I change one of the weight or bias value, the final output will also be changed. In other words, training neural network means finding and adjusting weight and bias values that gives the best output that we want. Synaptic.js is a great JavaScript neural network library for node.js and browser. If you have node.js installed, you can install synaptic.js with using following command: npm install synaptic --save Now, I want to provide very brief example solving problem using Synaptic.js library. If you take a look at table on the left, it has two input and one output. If the first input is greater than the second input, the output is 1. Otherwise the output is 0. The first five records will be our test data and we will see what is the output for the last two records. Following code shows how I implemented using synaptic.js to solve the problem. var synaptic = require('synaptic');var myNetwork = new synaptic.Architect.Perceptron(2, 3, 1);var learningRate = .2;//trainingfor (var i = 0; i < 20000; i++){ //test data 1 myNetwork.activate([2,1]); myNetwork.propagate(learningRate, [1]); //test data 2 myNetwork.activate([1,5]); myNetwork.propagate(learningRate, [0]); //test data 3 myNetwork.activate([4,2]); myNetwork.propagate(learningRate, [1]); //test data 4 myNetwork.activate([5,2]); myNetwork.propagate(learningRate, [1]); //test data 5 myNetwork.activate([3,5]); myNetwork.propagate(learningRate, [0]);}console.log(myNetwork.activate([2,5])); //[ 0.0000728000640238746 ]console.log(myNetwork.activate([3,1])); //[ 0.9999465030073619 ] var myNetwork = new synaptic.Architect.Perceptron(2, 3, 1); Above code creates neural network with 2 input neurons, 3 hidden neurons and 1 output neuron. myNetwork.activate([2,1]); activate() method returns output from the given input (in above code, 2 and 1). The output value is between 0 to 1 float value. myNetwork.propagate(learningRate, [1]); After call the activate function, we call propagate() function to train the network with learning rate and target output value. This is done by backpropagation. When I implement the flappy bird program, I’ve come up with 5 inputs and 1 output. The inputs are: Bird Position Velocity Distance between next pipe Upper pipe height Lower pipe height Each time the game is rendered, neural network gets the input and activate it. If the output is greater than 0.55, the bird will jumps. However, I cannot use propagate() method because there is no test data and its target value. In this case, we can use genetic algorithm to train our neural network. Assume that I have 8 birds in one generation and each bird has 6 neurons. (In my actual implementation, I have 12 birds in a generation and 18 neurons for each birds). After one generation (12 games), I pick the best 4 birds and apply crossover and mutation. Repeat the same process until we get good results. For crossover function, the bias value will be crossover-ed. Learn.crossOverDataKey(netA.neurons, netB.neurons, 'bias'); Cut the random location of the neuron, and crossover it. Learn.crossOverDataKey = function (a, b, key) { var cutLocation = Math.round(a.length * Math.random()); var tmp; for (var k = cutLocation; k < a.length; k++) { // Swap tmp = a[k][key]; a[k][key] = b[k][key]; b[k][key] = tmp; }} For mutation function, bias and weight value will be mutated. Learn.mutateDataKeys(net.neurons, 'bias', Learn.mutationProb);Learn.mutateDataKeys(net.connections, 'weight', Learn.mutationProb); Connection and neurons are randomly selected and mutated to random value. In my implementation, I have mutation rate 20%. Learn.mutateDataKeys = function (a, key, mutationRate){ for (var k = 0; k < a.length; k++) { // Should mutate? if (Math.random() > mutationRate) { continue; } a[k][key] += a[k][key] * (Math.random() - 0.5) * 3 + (Math.random() - 0.5); }} You can see my full code here. Also, here are links to resources that I used: synaptic.js: https://github.com/cazala/synapticflappybird web version: https://github.com/nebez/floppybirdcode/algorithms that I referenced: https://github.com/ivanseidel/IAMDinosaur
[ { "code": null, "e": 536, "s": 171, "text": "Currently, I am an IT student in college. This semester, I had a really interesting course which I choose my own topic to study, and create my own project. So I decided to learn and work on something very interesting and unique. While I was exploring various topic, I found a video tutorial about Neural Network, and I was really interested in learning this topic." }, { "code": null, "e": 702, "s": 536, "text": "After watching the tutorial video, I come up with an idea to implement a neural network program that learns how to play Flappy Bird game. Finally, this is my result." }, { "code": null, "e": 857, "s": 702, "text": "When the program runs first time, it does nothing because it has no idea about the game. However, a few hours of training, it learns how to play the game." }, { "code": null, "e": 964, "s": 857, "text": "In this posting, I want to give a basic information about Neural network and how I implemented my program." }, { "code": null, "e": 1203, "s": 964, "text": "First of all, I want to talk about what neural network is. In programming, artificial neural network is computational model/algorithm for machine learning that is inspired by structure and functional aspects of biological neural networks." }, { "code": null, "e": 1390, "s": 1203, "text": "Every neural network has one input layer, one output layer and one or more hidden layers. Each circle represents a neuron and a neuron has a connection to every neuron in the next layer." }, { "code": null, "e": 1530, "s": 1390, "text": "Each connection has weight value and each neuron has a bias value. For example, below diagram shows what’s happening in the neural network." }, { "code": null, "e": 1859, "s": 1530, "text": "When neural network calculate the output, it does a lot of math with weight and bias. You can easily expect that if I change one of the weight or bias value, the final output will also be changed. In other words, training neural network means finding and adjusting weight and bias values that gives the best output that we want." }, { "code": null, "e": 2030, "s": 1859, "text": "Synaptic.js is a great JavaScript neural network library for node.js and browser. If you have node.js installed, you can install synaptic.js with using following command:" }, { "code": null, "e": 2058, "s": 2030, "text": "npm install synaptic --save" }, { "code": null, "e": 2143, "s": 2058, "text": "Now, I want to provide very brief example solving problem using Synaptic.js library." }, { "code": null, "e": 2314, "s": 2143, "text": "If you take a look at table on the left, it has two input and one output. If the first input is greater than the second input, the output is 1. Otherwise the output is 0." }, { "code": null, "e": 2420, "s": 2314, "text": "The first five records will be our test data and we will see what is the output for the last two records." }, { "code": null, "e": 2499, "s": 2420, "text": "Following code shows how I implemented using synaptic.js to solve the problem." }, { "code": null, "e": 3240, "s": 2499, "text": "var synaptic = require('synaptic');var myNetwork = new synaptic.Architect.Perceptron(2, 3, 1);var learningRate = .2;//trainingfor (var i = 0; i < 20000; i++){ //test data 1 myNetwork.activate([2,1]); myNetwork.propagate(learningRate, [1]); //test data 2 myNetwork.activate([1,5]); myNetwork.propagate(learningRate, [0]); //test data 3 myNetwork.activate([4,2]); myNetwork.propagate(learningRate, [1]); //test data 4 myNetwork.activate([5,2]); myNetwork.propagate(learningRate, [1]); //test data 5 myNetwork.activate([3,5]); myNetwork.propagate(learningRate, [0]);}console.log(myNetwork.activate([2,5])); //[ 0.0000728000640238746 ]console.log(myNetwork.activate([3,1])); //[ 0.9999465030073619 ]" }, { "code": null, "e": 3300, "s": 3240, "text": "var myNetwork = new synaptic.Architect.Perceptron(2, 3, 1);" }, { "code": null, "e": 3394, "s": 3300, "text": "Above code creates neural network with 2 input neurons, 3 hidden neurons and 1 output neuron." }, { "code": null, "e": 3421, "s": 3394, "text": "myNetwork.activate([2,1]);" }, { "code": null, "e": 3549, "s": 3421, "text": "activate() method returns output from the given input (in above code, 2 and 1). The output value is between 0 to 1 float value." }, { "code": null, "e": 3589, "s": 3549, "text": "myNetwork.propagate(learningRate, [1]);" }, { "code": null, "e": 3750, "s": 3589, "text": "After call the activate function, we call propagate() function to train the network with learning rate and target output value. This is done by backpropagation." }, { "code": null, "e": 3833, "s": 3750, "text": "When I implement the flappy bird program, I’ve come up with 5 inputs and 1 output." }, { "code": null, "e": 3849, "s": 3833, "text": "The inputs are:" }, { "code": null, "e": 3863, "s": 3849, "text": "Bird Position" }, { "code": null, "e": 3872, "s": 3863, "text": "Velocity" }, { "code": null, "e": 3899, "s": 3872, "text": "Distance between next pipe" }, { "code": null, "e": 3917, "s": 3899, "text": "Upper pipe height" }, { "code": null, "e": 3935, "s": 3917, "text": "Lower pipe height" }, { "code": null, "e": 4071, "s": 3935, "text": "Each time the game is rendered, neural network gets the input and activate it. If the output is greater than 0.55, the bird will jumps." }, { "code": null, "e": 4236, "s": 4071, "text": "However, I cannot use propagate() method because there is no test data and its target value. In this case, we can use genetic algorithm to train our neural network." }, { "code": null, "e": 4404, "s": 4236, "text": "Assume that I have 8 birds in one generation and each bird has 6 neurons. (In my actual implementation, I have 12 birds in a generation and 18 neurons for each birds)." }, { "code": null, "e": 4546, "s": 4404, "text": "After one generation (12 games), I pick the best 4 birds and apply crossover and mutation. Repeat the same process until we get good results." }, { "code": null, "e": 4607, "s": 4546, "text": "For crossover function, the bias value will be crossover-ed." }, { "code": null, "e": 4667, "s": 4607, "text": "Learn.crossOverDataKey(netA.neurons, netB.neurons, 'bias');" }, { "code": null, "e": 4724, "s": 4667, "text": "Cut the random location of the neuron, and crossover it." }, { "code": null, "e": 4992, "s": 4724, "text": "Learn.crossOverDataKey = function (a, b, key) { var cutLocation = Math.round(a.length * Math.random()); var tmp; for (var k = cutLocation; k < a.length; k++) { // Swap tmp = a[k][key]; a[k][key] = b[k][key]; b[k][key] = tmp; }}" }, { "code": null, "e": 5054, "s": 4992, "text": "For mutation function, bias and weight value will be mutated." }, { "code": null, "e": 5185, "s": 5054, "text": "Learn.mutateDataKeys(net.neurons, 'bias', Learn.mutationProb);Learn.mutateDataKeys(net.connections, 'weight', Learn.mutationProb);" }, { "code": null, "e": 5307, "s": 5185, "text": "Connection and neurons are randomly selected and mutated to random value. In my implementation, I have mutation rate 20%." }, { "code": null, "e": 5590, "s": 5307, "text": "Learn.mutateDataKeys = function (a, key, mutationRate){ for (var k = 0; k < a.length; k++) { // Should mutate? if (Math.random() > mutationRate) { continue; } a[k][key] += a[k][key] * (Math.random() - 0.5) * 3 + (Math.random() - 0.5); }}" }, { "code": null, "e": 5621, "s": 5590, "text": "You can see my full code here." }, { "code": null, "e": 5668, "s": 5621, "text": "Also, here are links to resources that I used:" } ]
Python | Pandas dataframe.swapaxes() - GeeksforGeeks
23 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.swapaxes() function interchange axes and swap values axes appropriately. The function takes the name of the axes to be interchanged with as parameter. Based on the axes, it accordingly changes the data as well. Syntax: DataFrame.swapaxes(axis1, axis2, copy=True) Parameters :axis1 : name of the first axes { string}axis2 : name of the second axes { string} Returns : y : same as input Example #1: Use swapaxes() function to swap the axes of the dataframe. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[10, 11, 7, 8, 5], "B":[21, 5, 32, 4, 6], "C":[11, 21, 23, 7, 9], "D":[1, 5, 3, 8, 6]}, index =["A1", "A2", "A3", "A4", "A5"]) # Print the dataframedf # interchange the index and columns axisdf.swapaxes("index", "columns") Output : Example #2: Use swapaxes() function to swap the index and column axes with each other. The dataframe has some missing values. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5 + 1j, 3+.2j, 4 + 1j, None], "B":[3, 2, 4, 3, 4], "C":["brook", "daniela", "samantha", "hayden", "nathan"], "D":[None, 3, 6, None, 7]}, index =["A1", "A2", "A3", "A4", "A5"]) # Print the dataframedf # interchange the columns and index axis df.swapaxes("index", "columns") Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists sum() function in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Convert integer to string in Python
[ { "code": null, "e": 24870, "s": 24842, "text": "\n23 Nov, 2018" }, { "code": null, "e": 25084, "s": 24870, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25312, "s": 25084, "text": "Pandas dataframe.swapaxes() function interchange axes and swap values axes appropriately. The function takes the name of the axes to be interchanged with as parameter. Based on the axes, it accordingly changes the data as well." }, { "code": null, "e": 25364, "s": 25312, "text": "Syntax: DataFrame.swapaxes(axis1, axis2, copy=True)" }, { "code": null, "e": 25458, "s": 25364, "text": "Parameters :axis1 : name of the first axes { string}axis2 : name of the second axes { string}" }, { "code": null, "e": 25486, "s": 25458, "text": "Returns : y : same as input" }, { "code": null, "e": 25557, "s": 25486, "text": "Example #1: Use swapaxes() function to swap the axes of the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[10, 11, 7, 8, 5], \"B\":[21, 5, 32, 4, 6], \"C\":[11, 21, 23, 7, 9], \"D\":[1, 5, 3, 8, 6]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Print the dataframedf", "e": 25875, "s": 25557, "text": null }, { "code": "# interchange the index and columns axisdf.swapaxes(\"index\", \"columns\")", "e": 25947, "s": 25875, "text": null }, { "code": null, "e": 26082, "s": 25947, "text": "Output : Example #2: Use swapaxes() function to swap the index and column axes with each other. The dataframe has some missing values." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5 + 1j, 3+.2j, 4 + 1j, None], \"B\":[3, 2, 4, 3, 4], \"C\":[\"brook\", \"daniela\", \"samantha\", \"hayden\", \"nathan\"], \"D\":[None, 3, 6, None, 7]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Print the dataframedf", "e": 26452, "s": 26082, "text": null }, { "code": "# interchange the columns and index axis df.swapaxes(\"index\", \"columns\")", "e": 26526, "s": 26452, "text": null }, { "code": null, "e": 26535, "s": 26526, "text": "Output :" }, { "code": null, "e": 26559, "s": 26535, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26591, "s": 26559, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 26605, "s": 26591, "text": "Python-pandas" }, { "code": null, "e": 26612, "s": 26605, "text": "Python" }, { "code": null, "e": 26710, "s": 26612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26719, "s": 26710, "text": "Comments" }, { "code": null, "e": 26732, "s": 26719, "text": "Old Comments" }, { "code": null, "e": 26750, "s": 26732, "text": "Python Dictionary" }, { "code": null, "e": 26772, "s": 26750, "text": "Enumerate() in Python" }, { "code": null, "e": 26804, "s": 26772, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26846, "s": 26804, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26883, "s": 26846, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26908, "s": 26883, "text": "sum() function in Python" }, { "code": null, "e": 26937, "s": 26908, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26979, "s": 26937, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27035, "s": 26979, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
jQuery toggleClass() with Examples
The toggleClass() method in jQuery is used to toggle between adding or removing one or more classes from selected elements. The syntax is as follows − $(selector).toggleClass(classname,func(index,currentclass),switch) Above, class name specifies one or more class names to add or remove, whereas func is a function that returns one or more class names to add or remove. Let us now see an example to implement the jQuery toggleClass() method − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").toggleClass("demo"); }); }); </script> <style> .demo { background-color: orange; color: white; border: 1px solid blue; } </style> </head> <body> <h2>Exam Info</h2> <p>Examination begins on 24th December. The students are requested to submit project report before 15th December.</p> <button>Toggle</button> </body> </html> This will produce the following output − On clicking Toggle, the appearance of the above text will change − On clicking Toggle again, the appearance gets back to the initial stage −
[ { "code": null, "e": 1186, "s": 1062, "text": "The toggleClass() method in jQuery is used to toggle between adding or removing one or more classes from selected elements." }, { "code": null, "e": 1213, "s": 1186, "text": "The syntax is as follows −" }, { "code": null, "e": 1280, "s": 1213, "text": "$(selector).toggleClass(classname,func(index,currentclass),switch)" }, { "code": null, "e": 1432, "s": 1280, "text": "Above, class name specifies one or more class names to add or remove, whereas func is a function that returns one or more class names to add or remove." }, { "code": null, "e": 1505, "s": 1432, "text": "Let us now see an example to implement the jQuery toggleClass() method −" }, { "code": null, "e": 1516, "s": 1505, "text": " Live Demo" }, { "code": null, "e": 2069, "s": 1516, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n $(\"p\").toggleClass(\"demo\");\n });\n });\n</script>\n<style>\n.demo {\n background-color: orange;\n color: white;\n border: 1px solid blue;\n}\n</style>\n</head>\n<body>\n<h2>Exam Info</h2>\n<p>Examination begins on 24th December. The students are requested to submit project report before 15th December.</p>\n<button>Toggle</button>\n</body>\n</html>" }, { "code": null, "e": 2110, "s": 2069, "text": "This will produce the following output −" }, { "code": null, "e": 2177, "s": 2110, "text": "On clicking Toggle, the appearance of the above text will change −" }, { "code": null, "e": 2251, "s": 2177, "text": "On clicking Toggle again, the appearance gets back to the initial stage −" } ]
Comparing Timestamp in Python – Pandas
To compare timestamps, we can use index operator i.e. the square brackets. At first, import the required library − import pandas as pd Create a DataFrame with 3 columns − dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"], "Date_of_Purchase": [ pd.Timestamp("2021-06-10"), pd.Timestamp("2021-07-11"), pd.Timestamp("2021-06-25"), pd.Timestamp("2021-06-29"), pd.Timestamp("2021-03-20"), ], "Date_of_Service": [ pd.Timestamp("2021-11-10"), pd.Timestamp("2021-12-11"), pd.Timestamp("2021-11-25"), pd.Timestamp("2021-11-29"), pd.Timestamp("2021-08-20"), ] }) Let us now compare some timestamps from both the date columns − timestamp1_diff = abs(dataFrame['Date_of_Purchase'][0]-dataFrame['Date_of_Service'][0]) timestamp2_diff = abs(dataFrame['Date_of_Purchase'][1]-dataFrame['Date_of_Service'][1]) Compare all the timestamps − timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service']) Following is the complete code − import pandas as pd # create a dataframe with 3 columns dataFrame = pd.DataFrame( { "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"], "Date_of_Purchase": [ pd.Timestamp("2021-06-10"), pd.Timestamp("2021-07-11"), pd.Timestamp("2021-06-25"), pd.Timestamp("2021-06-29"), pd.Timestamp("2021-03-20"), ], "Date_of_Service": [ pd.Timestamp("2021-11-10"), pd.Timestamp("2021-12-11"), pd.Timestamp("2021-11-25"), pd.Timestamp("2021-11-29"), pd.Timestamp("2021-08-20"), ] }) print"DataFrame...\n", dataFrame # compare specific timestamps timestamp1_diff = abs(dataFrame['Date_of_Purchase'][0]-dataFrame['Date_of_Service'][0]) timestamp2_diff = abs(dataFrame['Date_of_Purchase'][1]-dataFrame['Date_of_Service'][1]) print"\nDifference between Car 1 Date of Purchase and Service \n",timestamp1_diff print"\nDifference between Car 2 Date of Purchase and Service \n",timestamp2_diff # compare all timestamps by finding difference timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service']) print"\nDifference between two Timestamps: \n",timestamp_diff This will produce the following output − DataFrame... Car Date_of_Purchase Date_of_Service 0 Audi 2021-06-10 2021-11-10 1 Lexus 2021-07-11 2021-12-11 2 Tesla 2021-06-25 2021-11-25 3 Mercedes 2021-06-29 2021-11-29 4 BMW 2021-03-20 2021-08-20 Difference between Car 1 Date of Purchase and Service 153 days 00:00:00 Difference between Car 2 Date of Purchase and Service 153 days 00:00:00 Difference between two Timestamps: 0 153 days 1 153 days 2 153 days 3 153 days 4 153 days dtype: timedelta64[ns]
[ { "code": null, "e": 1177, "s": 1062, "text": "To compare timestamps, we can use index operator i.e. the square brackets. At first, import the required library −" }, { "code": null, "e": 1197, "s": 1177, "text": "import pandas as pd" }, { "code": null, "e": 1233, "s": 1197, "text": "Create a DataFrame with 3 columns −" }, { "code": null, "e": 1780, "s": 1233, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n ],\n \"Date_of_Service\": [\n pd.Timestamp(\"2021-11-10\"),\n pd.Timestamp(\"2021-12-11\"),\n pd.Timestamp(\"2021-11-25\"),\n pd.Timestamp(\"2021-11-29\"),\n pd.Timestamp(\"2021-08-20\"),\n ]\n })\n\n" }, { "code": null, "e": 1844, "s": 1780, "text": "Let us now compare some timestamps from both the date columns −" }, { "code": null, "e": 2020, "s": 1844, "text": "timestamp1_diff = abs(dataFrame['Date_of_Purchase'][0]-dataFrame['Date_of_Service'][0])\ntimestamp2_diff = abs(dataFrame['Date_of_Purchase'][1]-dataFrame['Date_of_Service'][1])" }, { "code": null, "e": 2049, "s": 2020, "text": "Compare all the timestamps −" }, { "code": null, "e": 2130, "s": 2049, "text": "timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])" }, { "code": null, "e": 2163, "s": 2130, "text": "Following is the complete code −" }, { "code": null, "e": 3356, "s": 2163, "text": "import pandas as pd\n\n# create a dataframe with 3 columns\ndataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n ],\n \"Date_of_Service\": [\n pd.Timestamp(\"2021-11-10\"),\n pd.Timestamp(\"2021-12-11\"),\n pd.Timestamp(\"2021-11-25\"),\n pd.Timestamp(\"2021-11-29\"),\n pd.Timestamp(\"2021-08-20\"),\n ]\n })\n\nprint\"DataFrame...\\n\", dataFrame\n\n# compare specific timestamps\ntimestamp1_diff = abs(dataFrame['Date_of_Purchase'][0]-dataFrame['Date_of_Service'][0])\ntimestamp2_diff = abs(dataFrame['Date_of_Purchase'][1]-dataFrame['Date_of_Service'][1])\nprint\"\\nDifference between Car 1 Date of Purchase and Service \\n\",timestamp1_diff\nprint\"\\nDifference between Car 2 Date of Purchase and Service \\n\",timestamp2_diff\n\n# compare all timestamps by finding difference\ntimestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])\nprint\"\\nDifference between two Timestamps: \\n\",timestamp_diff" }, { "code": null, "e": 3397, "s": 3356, "text": "This will produce the following output −" }, { "code": null, "e": 3974, "s": 3397, "text": "DataFrame...\n Car Date_of_Purchase Date_of_Service\n0 Audi 2021-06-10 2021-11-10\n1 Lexus 2021-07-11 2021-12-11\n2 Tesla 2021-06-25 2021-11-25\n3 Mercedes 2021-06-29 2021-11-29\n4 BMW 2021-03-20 2021-08-20\n\nDifference between Car 1 Date of Purchase and Service\n153 days 00:00:00\n\nDifference between Car 2 Date of Purchase and Service\n153 days 00:00:00\n\nDifference between two Timestamps:\n0 153 days\n1 153 days\n2 153 days\n3 153 days\n4 153 days\ndtype: timedelta64[ns]" } ]
Simple Linear Regression in Python | by Tarun Gupta | Towards Data Science
Simple Linear Regression is a statistical method to find relationship between two continuous variables. Out of the two variables present, one is independent variable and the other is dependent variable. Statistical relationship is not accurate in determining relationship between two variables. For example, relationship between height and weight. This relationship is defined by the famous line equation which you would have learned in high school. y = b0 + b1*x where, y is the dependent variable x is the independent variable b0 is the base value of the relationship b1 is the slope of the line explaining the relationship between y & x. For instance, y refers to how does a person’s salary change with the years of experience that he has. So in that case salary would be the dependent variable and experience will be the independent variable and the base value will the salary of a person who has no experience. In our code example, we are going to work on such a dataset. In order to determine what is the best fitting line, let’s have a look at the following curve. Point with red cross are actual or real data points, whereas points with green cross are predicted value of the regression model. The goal here is to make such a regression model that the sum of squared error is minimum. Importing the dataset and performing Data Preprocessing Diving into the dataset of our code today. We have a business problem, where a company wants to establish a relationship between salary of its employees and the experience they have. We are going to investigate that correlation using Simple Linear Regression. Simple Linear Regression will tell us what is the best fitting line for this relationship. Let’s have a look at the dataset. You can download the dataset here. Our data consists of total 30 objects and two attributes, YearsExperience and Salary. The attribute YearsExperience is the independent attribute and the attribute Salary is the dependent attribute. I am going to use Spyder for writing this Machine Learning model. Before diving into Regression part of the model, we need to perform Data Preprocessing on our dataset. I am going to write the code for that directly but if you want to learn more about them, visit the following articles. The conceptual Data Preprocessing article: towardsdatascience.com The Programming Data Preprocessing article: towardsdatascience.com # Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd# Importing the datasetdataset = pd.read_csv('SimpleLinearRegression.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, -1].values# Splitting the dataset into the Training set and Test setfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) After executing this code, we have our training and testing sets split along with arrays and vectors of independent and dependent attributes respectively. They should look like this: Fit the dataset into Simple Linear Regression model In order to fit the data into our regressor model, we need to import a library, call the method for Regression and fit our training data to that regression model. We do this as follows: # Fitting Simple Linear Regression to the Training setfrom sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train) Since, our Machine Learning model already knows the correlation of our training set, we will now predict the values of our testing set and then later compare them with the actual values of the test set. To predict the values of the test set, we need to write the following code: # Predicting the Test set resultsy_pred = regressor.predict(X_test) After execution of code until now, we can manually have a look at the predicted test set values and actual test set values and see the how do they differ. As you can see, the values differ with each other. Some have a very low difference like the 4th entry and some have a slightly higher difference like the 8th entry. Visualising the correlation in the dataset In order to judge the actual correlation amongst the data, we are going to plot two curves. Visualising the Training set results We do this using the following code: # Visualising the Training set resultsplt.scatter(X_train, y_train, color = 'red')plt.plot(X_train, regressor.predict(X_train), color = 'blue')plt.title('Salary vs Experience (Training set)')plt.xlabel('Years of Experience')plt.ylabel('Salary')plt.show() As it can be seen, the line we have here is not that bad, since only a few points lie very far from it, most of the points lie around the line itself. Visualising the Test set results We do this using the following code: # Visualising the Test set resultsplt.scatter(X_test, y_test, color = 'red')plt.plot(X_train, regressor.predict(X_train), color = 'blue')plt.title('Salary vs Experience (Test set)')plt.xlabel('Years of Experience')plt.ylabel('Salary')plt.show() Here, there can be a confusion on why the parameter of regressor.predict() is not changed in plt.plot(X_train, regressor.predict(X_train), color = 'blue') to X_test. This is so because, if we do that, we will get a new line altogether but we want to compare our test set to the line we got from our training set. The curve will look like this: Here, it can be seen that 5 out of 10 data points lie on the line itself. 3 out of 10 are very near to the line and only 2 out of 10 points are a little bit farther. This concludes this post on Simple Linear Regression in Python for Machine Learning Modelling. I am giving away a free eBook on Consistency. Get your free eBook here. If you enjoy reading stories like these, then you should get my posts in your inbox and if want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission at no extra cost to you. tarun-gupta.medium.com Thanks for reading. If you liked this, have a read at some of my other posts here:
[ { "code": null, "e": 519, "s": 171, "text": "Simple Linear Regression is a statistical method to find relationship between two continuous variables. Out of the two variables present, one is independent variable and the other is dependent variable. Statistical relationship is not accurate in determining relationship between two variables. For example, relationship between height and weight." }, { "code": null, "e": 621, "s": 519, "text": "This relationship is defined by the famous line equation which you would have learned in high school." }, { "code": null, "e": 635, "s": 621, "text": "y = b0 + b1*x" }, { "code": null, "e": 642, "s": 635, "text": "where," }, { "code": null, "e": 670, "s": 642, "text": "y is the dependent variable" }, { "code": null, "e": 700, "s": 670, "text": "x is the independent variable" }, { "code": null, "e": 741, "s": 700, "text": "b0 is the base value of the relationship" }, { "code": null, "e": 812, "s": 741, "text": "b1 is the slope of the line explaining the relationship between y & x." }, { "code": null, "e": 1148, "s": 812, "text": "For instance, y refers to how does a person’s salary change with the years of experience that he has. So in that case salary would be the dependent variable and experience will be the independent variable and the base value will the salary of a person who has no experience. In our code example, we are going to work on such a dataset." }, { "code": null, "e": 1243, "s": 1148, "text": "In order to determine what is the best fitting line, let’s have a look at the following curve." }, { "code": null, "e": 1464, "s": 1243, "text": "Point with red cross are actual or real data points, whereas points with green cross are predicted value of the regression model. The goal here is to make such a regression model that the sum of squared error is minimum." }, { "code": null, "e": 1520, "s": 1464, "text": "Importing the dataset and performing Data Preprocessing" }, { "code": null, "e": 1780, "s": 1520, "text": "Diving into the dataset of our code today. We have a business problem, where a company wants to establish a relationship between salary of its employees and the experience they have. We are going to investigate that correlation using Simple Linear Regression." }, { "code": null, "e": 1940, "s": 1780, "text": "Simple Linear Regression will tell us what is the best fitting line for this relationship. Let’s have a look at the dataset. You can download the dataset here." }, { "code": null, "e": 2138, "s": 1940, "text": "Our data consists of total 30 objects and two attributes, YearsExperience and Salary. The attribute YearsExperience is the independent attribute and the attribute Salary is the dependent attribute." }, { "code": null, "e": 2426, "s": 2138, "text": "I am going to use Spyder for writing this Machine Learning model. Before diving into Regression part of the model, we need to perform Data Preprocessing on our dataset. I am going to write the code for that directly but if you want to learn more about them, visit the following articles." }, { "code": null, "e": 2469, "s": 2426, "text": "The conceptual Data Preprocessing article:" }, { "code": null, "e": 2492, "s": 2469, "text": "towardsdatascience.com" }, { "code": null, "e": 2536, "s": 2492, "text": "The Programming Data Preprocessing article:" }, { "code": null, "e": 2559, "s": 2536, "text": "towardsdatascience.com" }, { "code": null, "e": 2990, "s": 2559, "text": "# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd# Importing the datasetdataset = pd.read_csv('SimpleLinearRegression.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, -1].values# Splitting the dataset into the Training set and Test setfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)" }, { "code": null, "e": 3173, "s": 2990, "text": "After executing this code, we have our training and testing sets split along with arrays and vectors of independent and dependent attributes respectively. They should look like this:" }, { "code": null, "e": 3225, "s": 3173, "text": "Fit the dataset into Simple Linear Regression model" }, { "code": null, "e": 3411, "s": 3225, "text": "In order to fit the data into our regressor model, we need to import a library, call the method for Regression and fit our training data to that regression model. We do this as follows:" }, { "code": null, "e": 3576, "s": 3411, "text": "# Fitting Simple Linear Regression to the Training setfrom sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train)" }, { "code": null, "e": 3779, "s": 3576, "text": "Since, our Machine Learning model already knows the correlation of our training set, we will now predict the values of our testing set and then later compare them with the actual values of the test set." }, { "code": null, "e": 3855, "s": 3779, "text": "To predict the values of the test set, we need to write the following code:" }, { "code": null, "e": 3923, "s": 3855, "text": "# Predicting the Test set resultsy_pred = regressor.predict(X_test)" }, { "code": null, "e": 4078, "s": 3923, "text": "After execution of code until now, we can manually have a look at the predicted test set values and actual test set values and see the how do they differ." }, { "code": null, "e": 4243, "s": 4078, "text": "As you can see, the values differ with each other. Some have a very low difference like the 4th entry and some have a slightly higher difference like the 8th entry." }, { "code": null, "e": 4286, "s": 4243, "text": "Visualising the correlation in the dataset" }, { "code": null, "e": 4378, "s": 4286, "text": "In order to judge the actual correlation amongst the data, we are going to plot two curves." }, { "code": null, "e": 4415, "s": 4378, "text": "Visualising the Training set results" }, { "code": null, "e": 4452, "s": 4415, "text": "We do this using the following code:" }, { "code": null, "e": 4707, "s": 4452, "text": "# Visualising the Training set resultsplt.scatter(X_train, y_train, color = 'red')plt.plot(X_train, regressor.predict(X_train), color = 'blue')plt.title('Salary vs Experience (Training set)')plt.xlabel('Years of Experience')plt.ylabel('Salary')plt.show()" }, { "code": null, "e": 4858, "s": 4707, "text": "As it can be seen, the line we have here is not that bad, since only a few points lie very far from it, most of the points lie around the line itself." }, { "code": null, "e": 4891, "s": 4858, "text": "Visualising the Test set results" }, { "code": null, "e": 4928, "s": 4891, "text": "We do this using the following code:" }, { "code": null, "e": 5173, "s": 4928, "text": "# Visualising the Test set resultsplt.scatter(X_test, y_test, color = 'red')plt.plot(X_train, regressor.predict(X_train), color = 'blue')plt.title('Salary vs Experience (Test set)')plt.xlabel('Years of Experience')plt.ylabel('Salary')plt.show()" }, { "code": null, "e": 5517, "s": 5173, "text": "Here, there can be a confusion on why the parameter of regressor.predict() is not changed in plt.plot(X_train, regressor.predict(X_train), color = 'blue') to X_test. This is so because, if we do that, we will get a new line altogether but we want to compare our test set to the line we got from our training set. The curve will look like this:" }, { "code": null, "e": 5683, "s": 5517, "text": "Here, it can be seen that 5 out of 10 data points lie on the line itself. 3 out of 10 are very near to the line and only 2 out of 10 points are a little bit farther." }, { "code": null, "e": 5778, "s": 5683, "text": "This concludes this post on Simple Linear Regression in Python for Machine Learning Modelling." }, { "code": null, "e": 5850, "s": 5778, "text": "I am giving away a free eBook on Consistency. Get your free eBook here." }, { "code": null, "e": 6171, "s": 5850, "text": "If you enjoy reading stories like these, then you should get my posts in your inbox and if want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission at no extra cost to you." }, { "code": null, "e": 6194, "s": 6171, "text": "tarun-gupta.medium.com" } ]
Faulty calculator using Python - GeeksforGeeks
01 Jul, 2021 A faulty calculator is simply a calculator which operates simple tasks, but in some cases (set by the programmer) it gives the wrong output. You all must be wondering why do we need a faulty calculator? This type of calculator is not needed unless you want to prank someone or prove them wrong in case of some maths problem. Approach: First, we take input from the user that what he/she wants to do Then we write the code of Addition, Subtraction, Multiplication, and Division And lastly, we insert those cases that we want wrong results. Implementation: Python print("what type of arithmetic operation you want to do?\n" "type + for addition\n" "type - for subtraction\n" "type / for division\n" "type* for multiplication\n") # taking inputtype_of_calculation = input() print("enter the first number")A = int(input()) print("enter the second number\n")B = int(input()) b = "+"c = "-"d = "*"e = "/" # setting normal and false condition for calculatorif type_of_calculation == b: # for addition if (A == 53 and B == 9) or (A == 90 and B == 52): print(97) else: print(A+B)elif type_of_calculation == c: # for subtraction print(A-B)elif type_of_calculation == d: # for multiplication if A == 45 and B == 3 or A == 4 and B == 67: print(575) else: print(A*B)elif type_of_calculation == e: # for division if A == 5 and B == 63: print(40) else: print(A/B) Output: For normal condition For false condition anikaseth98 school-programming Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24317, "s": 24289, "text": "\n01 Jul, 2021" }, { "code": null, "e": 24642, "s": 24317, "text": "A faulty calculator is simply a calculator which operates simple tasks, but in some cases (set by the programmer) it gives the wrong output. You all must be wondering why do we need a faulty calculator? This type of calculator is not needed unless you want to prank someone or prove them wrong in case of some maths problem." }, { "code": null, "e": 24652, "s": 24642, "text": "Approach:" }, { "code": null, "e": 24716, "s": 24652, "text": "First, we take input from the user that what he/she wants to do" }, { "code": null, "e": 24794, "s": 24716, "text": "Then we write the code of Addition, Subtraction, Multiplication, and Division" }, { "code": null, "e": 24856, "s": 24794, "text": "And lastly, we insert those cases that we want wrong results." }, { "code": null, "e": 24872, "s": 24856, "text": "Implementation:" }, { "code": null, "e": 24879, "s": 24872, "text": "Python" }, { "code": "print(\"what type of arithmetic operation you want to do?\\n\" \"type + for addition\\n\" \"type - for subtraction\\n\" \"type / for division\\n\" \"type* for multiplication\\n\") # taking inputtype_of_calculation = input() print(\"enter the first number\")A = int(input()) print(\"enter the second number\\n\")B = int(input()) b = \"+\"c = \"-\"d = \"*\"e = \"/\" # setting normal and false condition for calculatorif type_of_calculation == b: # for addition if (A == 53 and B == 9) or (A == 90 and B == 52): print(97) else: print(A+B)elif type_of_calculation == c: # for subtraction print(A-B)elif type_of_calculation == d: # for multiplication if A == 45 and B == 3 or A == 4 and B == 67: print(575) else: print(A*B)elif type_of_calculation == e: # for division if A == 5 and B == 63: print(40) else: print(A/B)", "e": 25772, "s": 24879, "text": null }, { "code": null, "e": 25780, "s": 25772, "text": "Output:" }, { "code": null, "e": 25801, "s": 25780, "text": "For normal condition" }, { "code": null, "e": 25821, "s": 25801, "text": "For false condition" }, { "code": null, "e": 25833, "s": 25821, "text": "anikaseth98" }, { "code": null, "e": 25852, "s": 25833, "text": "school-programming" }, { "code": null, "e": 25859, "s": 25852, "text": "Python" }, { "code": null, "e": 25957, "s": 25859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25966, "s": 25957, "text": "Comments" }, { "code": null, "e": 25979, "s": 25966, "text": "Old Comments" }, { "code": null, "e": 26011, "s": 25979, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26067, "s": 26011, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26122, "s": 26067, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26164, "s": 26122, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26206, "s": 26164, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26237, "s": 26206, "text": "Python | os.path.join() method" }, { "code": null, "e": 26276, "s": 26237, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26305, "s": 26276, "text": "Create a directory in Python" }, { "code": null, "e": 26327, "s": 26305, "text": "Defaultdict in Python" } ]
How to read all excel files under a directory as a Pandas DataFrame ? - GeeksforGeeks
21 Apr, 2021 In this article, we will see how to read all Excel files in a folder into single Pandas dataframe. The task can be performed by first finding all excel files in a particular folder using glob() method and then reading the file by using pandas.read_excel() method and then displaying the content. Import necessary python packages like pandas, glob, and os.Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.xlsx’Loop over the list of excel files, read that file using pandas.read_excel().Convert each excel file into a dataframe.Display its location, name, and content. Import necessary python packages like pandas, glob, and os. Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.xlsx’ Loop over the list of excel files, read that file using pandas.read_excel(). Convert each excel file into a dataframe. Display its location, name, and content. Below is the implementation. Python3 # import necessary librariesimport pandas as pdimport osimport glob # use glob to get all the csv files# in the folderpath = os.getcwd()csv_files = glob.glob(os.path.join(path, "*.xlsx")) # loop over the list of csv filesfor f in csv_files: # read the csv file df = pd.read_excel(f) # print the location and filename print('Location:', f) print('File Name:', f.split("\\")[-1]) # print the content print('Content:') display(df) print() Output : Note: The program reads all Excel files in the folder in which the program itself is present. Picked Python-excel Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n21 Apr, 2021" }, { "code": null, "e": 24588, "s": 24292, "text": "In this article, we will see how to read all Excel files in a folder into single Pandas dataframe. The task can be performed by first finding all excel files in a particular folder using glob() method and then reading the file by using pandas.read_excel() method and then displaying the content." }, { "code": null, "e": 24898, "s": 24588, "text": "Import necessary python packages like pandas, glob, and os.Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.xlsx’Loop over the list of excel files, read that file using pandas.read_excel().Convert each excel file into a dataframe.Display its location, name, and content." }, { "code": null, "e": 24958, "s": 24898, "text": "Import necessary python packages like pandas, glob, and os." }, { "code": null, "e": 25052, "s": 24958, "text": "Use glob python package to retrieve files/pathnames matching a specified pattern i.e. ‘.xlsx’" }, { "code": null, "e": 25129, "s": 25052, "text": "Loop over the list of excel files, read that file using pandas.read_excel()." }, { "code": null, "e": 25171, "s": 25129, "text": "Convert each excel file into a dataframe." }, { "code": null, "e": 25212, "s": 25171, "text": "Display its location, name, and content." }, { "code": null, "e": 25241, "s": 25212, "text": "Below is the implementation." }, { "code": null, "e": 25249, "s": 25241, "text": "Python3" }, { "code": "# import necessary librariesimport pandas as pdimport osimport glob # use glob to get all the csv files# in the folderpath = os.getcwd()csv_files = glob.glob(os.path.join(path, \"*.xlsx\")) # loop over the list of csv filesfor f in csv_files: # read the csv file df = pd.read_excel(f) # print the location and filename print('Location:', f) print('File Name:', f.split(\"\\\\\")[-1]) # print the content print('Content:') display(df) print()", "e": 25734, "s": 25249, "text": null }, { "code": null, "e": 25743, "s": 25734, "text": "Output :" }, { "code": null, "e": 25837, "s": 25743, "text": "Note: The program reads all Excel files in the folder in which the program itself is present." }, { "code": null, "e": 25844, "s": 25837, "text": "Picked" }, { "code": null, "e": 25857, "s": 25844, "text": "Python-excel" }, { "code": null, "e": 25871, "s": 25857, "text": "Python-pandas" }, { "code": null, "e": 25878, "s": 25871, "text": "Python" }, { "code": null, "e": 25976, "s": 25878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26008, "s": 25976, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26050, "s": 26008, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26106, "s": 26050, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26148, "s": 26106, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26203, "s": 26148, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26234, "s": 26203, "text": "Python | os.path.join() method" }, { "code": null, "e": 26256, "s": 26234, "text": "Defaultdict in Python" }, { "code": null, "e": 26285, "s": 26256, "text": "Create a directory in Python" }, { "code": null, "e": 26324, "s": 26285, "text": "Python | Get unique values from a list" } ]
Primality Test | Set 3 (Miller–Rabin) - GeeksforGeeks
07 Apr, 2022 Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabilistic method ( like Fermat), but it is generally preferred over Fermat’s method. Algorithm: // It returns false if n is composite and returns true if n // is probably prime. k is an input parameter that determines // accuracy level. Higher value of k indicates more accuracy. bool isPrime(int n, int k) 1) Handle base cases for n < 3 2) If n is even, return false. 3) Find an odd number d such that n-1 can be written as d*2r. Note that since n is odd, (n-1) must be even and r must be greater than 0. 4) Do following k times if (millerTest(n, d) == false) return false 5) Return true. // This function is called for all k trials. It returns // false if n is composite and returns true if n is probably // prime. // d is an odd number such that d*2r = n-1 for some r>=1 bool millerTest(int n, int d) 1) Pick a random number 'a' in range [2, n-2] 2) Compute: x = pow(a, d) % n 3) If x == 1 or x == n-1, return true. // Below loop mainly runs 'r-1' times. 4) Do following while d doesn't become n-1. a) x = (x*x) % n. b) If (x == 1) return false. c) If (x == n-1) return true. Example: Input: n = 13, k = 2. 1) Compute d and r such that d*2r = n-1, d = 3, r = 2. 2) Call millerTest k times. 1st Iteration: 1) Pick a random number 'a' in range [2, n-2] Suppose a = 4 2) Compute: x = pow(a, d) % n x = 43 % 13 = 12 3) Since x = (n-1), return true. IInd Iteration: 1) Pick a random number 'a' in range [2, n-2] Suppose a = 5 2) Compute: x = pow(a, d) % n x = 53 % 13 = 8 3) x neither 1 nor 12. 4) Do following (r-1) = 1 times a) x = (x * x) % 13 = (8 * 8) % 13 = 12 b) Since x = (n-1), return true. Since both iterations return true, we return true. Implementation: Below is the implementation of the above algorithm. C++ Java Python3 C# PHP Javascript // C++ program Miller-Rabin primality test#include <bits/stdc++.h>using namespace std; // Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // This function is called for all k trials. It returns// false if n is composite and returns true if n is// probably prime.// d is an odd number such that d*2<sup>r</sup> = n-1// for some r >= 1bool miillerTest(int d, int n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + rand() % (n - 4); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n-1) return true; // Keep squaring x while one of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n-1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n-1) return true; } // Return composite return false;} // It returns false if n is composite and returns true if n// is probably prime. k is an input parameter that determines// accuracy level. Higher value of k indicates more accuracy.bool isPrime(int n, int k){ // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = 2^d * r + 1 for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Driver programint main(){ int k = 4; // Number of iterations cout << "All primes smaller than 100: \n"; for (int n = 1; n < 100; n++) if (isPrime(n, k)) cout << n << " "; return 0;} // Java program Miller-Rabin primality testimport java.io.*;import java.math.*; class GFG { // Utility function to do modular // exponentiation. It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result //Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // This function is called for all k trials. // It returns false if n is composite and // returns false if n is probably prime. // d is an odd number such that d*2<sup>r</sup> // = n-1 for some r >= 1 static boolean miillerTest(int d, int n) { // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + (int)(Math.random() % (n - 4)); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one of the // following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false; } // It returns false if n is composite // and returns true if n is probably // prime. k is an input parameter that // determines accuracy level. Higher // value of k indicates more accuracy. static boolean isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = 2^d * r + 1 // for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true; } // Driver program public static void main(String args[]) { int k = 4; // Number of iterations System.out.println("All primes smaller " + "than 100: "); for (int n = 1; n < 100; n++) if (isPrime(n, k)) System.out.print(n + " "); }} /* This code is contributed by Nikita Tiwari.*/ # Python3 program Miller-Rabin primality testimport random # Utility function to do# modular exponentiation.# It returns (x^y) % pdef power(x, y, p): # Initialize result res = 1; # Update x if it is more than or # equal to p x = x % p; while (y > 0): # If y is odd, multiply # x with result if (y & 1): res = (res * x) % p; # y must be even now y = y>>1; # y = y/2 x = (x * x) % p; return res; # This function is called# for all k trials. It returns# false if n is composite and# returns false if n is# probably prime. d is an odd# number such that d*2<sup>r</sup> = n-1# for some r >= 1def miillerTest(d, n): # Pick a random number in [2..n-2] # Corner cases make sure that n > 4 a = 2 + random.randint(1, n - 4); # Compute a^d % n x = power(a, d, n); if (x == 1 or x == n - 1): return True; # Keep squaring x while one # of the following doesn't # happen # (i) d does not reach n-1 # (ii) (x^2) % n is not 1 # (iii) (x^2) % n is not n-1 while (d != n - 1): x = (x * x) % n; d *= 2; if (x == 1): return False; if (x == n - 1): return True; # Return composite return False; # It returns false if n is# composite and returns true if n# is probably prime. k is an# input parameter that determines# accuracy level. Higher value of# k indicates more accuracy.def isPrime( n, k): # Corner cases if (n <= 1 or n == 4): return False; if (n <= 3): return True; # Find r such that n = # 2^d * r + 1 for some r >= 1 d = n - 1; while (d % 2 == 0): d //= 2; # Iterate given number of 'k' times for i in range(k): if (miillerTest(d, n) == False): return False; return True; # Driver Code# Number of iterationsk = 4; print("All primes smaller than 100: ");for n in range(1,100): if (isPrime(n, k)): print(n , end=" "); # This code is contributed by mits // C# program Miller-Rabin primality testusing System; class GFG{ // Utility function to do modular // exponentiation. It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // This function is called for all k trials. // It returns false if n is composite and // returns false if n is probably prime. // d is an odd number such that d*2<sup>r</sup> // = n-1 for some r >= 1 static bool miillerTest(int d, int n) { // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 Random r = new Random(); int a = 2 + (int)(r.Next() % (n - 4)); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one of the // following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false; } // It returns false if n is composite // and returns true if n is probably // prime. k is an input parameter that // determines accuracy level. Higher // value of k indicates more accuracy. static bool isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = 2^d * r + 1 // for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (miillerTest(d, n) == false) return false; return true; } // Driver Code static void Main() { int k = 4; // Number of iterations Console.WriteLine("All primes smaller " + "than 100: "); for (int n = 1; n < 100; n++) if (isPrime(n, k)) Console.Write(n + " "); }} // This code is contributed by mits <?php// PHP program Miller-Rabin primality test // Utility function to do// modular exponentiation.// It returns (x^y) % pfunction power($x, $y, $p){ // Initialize result $res = 1; // Update x if it is more than or // equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res*$x) % $p; // y must be even now $y = $y>>1; // $y = $y/2 $x = ($x*$x) % $p; } return $res;} // This function is called// for all k trials. It returns// false if n is composite and// returns false if n is// probably prime. d is an odd// number such that d*2<sup>r</sup> = n-1// for some r >= 1function miillerTest($d, $n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 $a = 2 + rand() % ($n - 4); // Compute a^d % n $x = power($a, $d, $n); if ($x == 1 || $x == $n-1) return true; // Keep squaring x while one // of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while ($d != $n-1) { $x = ($x * $x) % $n; $d *= 2; if ($x == 1) return false; if ($x == $n-1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime. k is an// input parameter that determines// accuracy level. Higher value of// k indicates more accuracy.function isPrime( $n, $k){ // Corner cases if ($n <= 1 || $n == 4) return false; if ($n <= 3) return true; // Find r such that n = // 2^d * r + 1 for some r >= 1 $d = $n - 1; while ($d % 2 == 0) $d /= 2; // Iterate given number of 'k' times for ($i = 0; $i < $k; $i++) if (!miillerTest($d, $n)) return false; return true;} // Driver Code // Number of iterations $k = 4; echo "All primes smaller than 100: \n"; for ($n = 1; $n < 100; $n++) if (isPrime($n, $k)) echo $n , " "; // This code is contributed by ajit?> <script>// Javascript program Miller-Rabin primality test // Utility function to do// modular exponentiation.// It returns (x^y) % pfunction power(x, y, p){ // Initialize result let res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // This function is called// for all k trials. It returns// false if n is composite and// returns false if n is// probably prime. d is an odd// number such that d*2<sup>r</sup> = n-1// for some r >= 1function miillerTest(d, n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 let a = 2 + Math.floor(Math.random() * (n-2)) % (n - 4); // Compute a^d % n let x = power(a, d, n); if (x == 1 || x == n-1) return true; // Keep squaring x while one // of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n-1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n-1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime. k is an// input parameter that determines// accuracy level. Higher value of// k indicates more accuracy.function isPrime( n, k){ // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = // 2^d * r + 1 for some r >= 1 let d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (let i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Driver Code// Number of iterationslet k = 4; document.write("All primes smaller than 100: <br>");for (let n = 1; n < 100; n++) if (isPrime(n, k)) document.write(n , " "); // This code is contributed by gfgking</script> Output: All primes smaller than 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 How does this work? Below are some important facts behind the algorithm: Fermat’s theorem states that, If n is a prime number, then for every a, 1 <= a < n, an-1 % n = 1Base cases make sure that n must be odd. Since n is odd, n-1 must be even. And an even number can be written as d * 2s where d is an odd number and s > 0.From the above two points, for every randomly picked number in the range [2, n-2], the value of ad*2r % n must be 1.As per Euclid’s Lemma, if x2 % n = 1 or (x2 – 1) % n = 0 or (x-1)(x+1)% n = 0. Then, for n to be prime, either n divides (x-1) or n divides (x+1). Which means either x % n = 1 or x % n = -1.From points 2 and 3, we can conclude Fermat’s theorem states that, If n is a prime number, then for every a, 1 <= a < n, an-1 % n = 1 Base cases make sure that n must be odd. Since n is odd, n-1 must be even. And an even number can be written as d * 2s where d is an odd number and s > 0. From the above two points, for every randomly picked number in the range [2, n-2], the value of ad*2r % n must be 1. As per Euclid’s Lemma, if x2 % n = 1 or (x2 – 1) % n = 0 or (x-1)(x+1)% n = 0. Then, for n to be prime, either n divides (x-1) or n divides (x+1). Which means either x % n = 1 or x % n = -1. From points 2 and 3, we can conclude For n to be prime, either ad % n = 1 OR ad*2i % n = -1 for some i, where 0 <= i <= r-1. Next Article : Primality Test | Set 4 (Solovay-Strassen)This article is contributed Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t kartikay101 Mithun Kumar Jitendra Kushwaha local-dante sakshikhachane gfgking simmytarika5 Modular Arithmetic number-theory Prime Number Mathematical number-theory Mathematical Prime Number Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Minimum number of jumps to reach end Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 24772, "s": 24744, "text": "\n07 Apr, 2022" }, { "code": null, "e": 25152, "s": 24772, "text": "Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabilistic method ( like Fermat), but it is generally preferred over Fermat’s method." }, { "code": null, "e": 25163, "s": 25152, "text": "Algorithm:" }, { "code": null, "e": 26191, "s": 25163, "text": "// It returns false if n is composite and returns true if n\n// is probably prime. k is an input parameter that determines\n// accuracy level. Higher value of k indicates more accuracy.\nbool isPrime(int n, int k)\n1) Handle base cases for n < 3\n2) If n is even, return false.\n3) Find an odd number d such that n-1 can be written as d*2r. \n Note that since n is odd, (n-1) must be even and r must be \n greater than 0.\n4) Do following k times\n if (millerTest(n, d) == false)\n return false\n5) Return true.\n\n// This function is called for all k trials. It returns \n// false if n is composite and returns true if n is probably\n// prime. \n// d is an odd number such that d*2r = n-1 for some r>=1\nbool millerTest(int n, int d)\n1) Pick a random number 'a' in range [2, n-2]\n2) Compute: x = pow(a, d) % n\n3) If x == 1 or x == n-1, return true.\n\n// Below loop mainly runs 'r-1' times.\n4) Do following while d doesn't become n-1.\n a) x = (x*x) % n.\n b) If (x == 1) return false.\n c) If (x == n-1) return true. " }, { "code": null, "e": 26201, "s": 26191, "text": "Example: " }, { "code": null, "e": 26808, "s": 26201, "text": "Input: n = 13, k = 2.\n\n1) Compute d and r such that d*2r = n-1, \n d = 3, r = 2. \n2) Call millerTest k times.\n\n1st Iteration:\n1) Pick a random number 'a' in range [2, n-2]\n Suppose a = 4\n\n2) Compute: x = pow(a, d) % n\n x = 43 % 13 = 12\n\n3) Since x = (n-1), return true.\n\nIInd Iteration:\n1) Pick a random number 'a' in range [2, n-2]\n Suppose a = 5\n\n2) Compute: x = pow(a, d) % n\n x = 53 % 13 = 8\n\n3) x neither 1 nor 12.\n\n4) Do following (r-1) = 1 times\n a) x = (x * x) % 13 = (8 * 8) % 13 = 12\n b) Since x = (n-1), return true.\n\nSince both iterations return true, we return true. " }, { "code": null, "e": 26877, "s": 26808, "text": "Implementation: Below is the implementation of the above algorithm. " }, { "code": null, "e": 26881, "s": 26877, "text": "C++" }, { "code": null, "e": 26886, "s": 26881, "text": "Java" }, { "code": null, "e": 26894, "s": 26886, "text": "Python3" }, { "code": null, "e": 26897, "s": 26894, "text": "C#" }, { "code": null, "e": 26901, "s": 26897, "text": "PHP" }, { "code": null, "e": 26912, "s": 26901, "text": "Javascript" }, { "code": "// C++ program Miller-Rabin primality test#include <bits/stdc++.h>using namespace std; // Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // This function is called for all k trials. It returns// false if n is composite and returns true if n is// probably prime.// d is an odd number such that d*2<sup>r</sup> = n-1// for some r >= 1bool miillerTest(int d, int n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + rand() % (n - 4); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n-1) return true; // Keep squaring x while one of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n-1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n-1) return true; } // Return composite return false;} // It returns false if n is composite and returns true if n// is probably prime. k is an input parameter that determines// accuracy level. Higher value of k indicates more accuracy.bool isPrime(int n, int k){ // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = 2^d * r + 1 for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Driver programint main(){ int k = 4; // Number of iterations cout << \"All primes smaller than 100: \\n\"; for (int n = 1; n < 100; n++) if (isPrime(n, k)) cout << n << \" \"; return 0;}", "e": 29014, "s": 26912, "text": null }, { "code": "// Java program Miller-Rabin primality testimport java.io.*;import java.math.*; class GFG { // Utility function to do modular // exponentiation. It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result //Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // This function is called for all k trials. // It returns false if n is composite and // returns false if n is probably prime. // d is an odd number such that d*2<sup>r</sup> // = n-1 for some r >= 1 static boolean miillerTest(int d, int n) { // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 int a = 2 + (int)(Math.random() % (n - 4)); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one of the // following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false; } // It returns false if n is composite // and returns true if n is probably // prime. k is an input parameter that // determines accuracy level. Higher // value of k indicates more accuracy. static boolean isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = 2^d * r + 1 // for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true; } // Driver program public static void main(String args[]) { int k = 4; // Number of iterations System.out.println(\"All primes smaller \" + \"than 100: \"); for (int n = 1; n < 100; n++) if (isPrime(n, k)) System.out.print(n + \" \"); }} /* This code is contributed by Nikita Tiwari.*/", "e": 31778, "s": 29014, "text": null }, { "code": "# Python3 program Miller-Rabin primality testimport random # Utility function to do# modular exponentiation.# It returns (x^y) % pdef power(x, y, p): # Initialize result res = 1; # Update x if it is more than or # equal to p x = x % p; while (y > 0): # If y is odd, multiply # x with result if (y & 1): res = (res * x) % p; # y must be even now y = y>>1; # y = y/2 x = (x * x) % p; return res; # This function is called# for all k trials. It returns# false if n is composite and# returns false if n is# probably prime. d is an odd# number such that d*2<sup>r</sup> = n-1# for some r >= 1def miillerTest(d, n): # Pick a random number in [2..n-2] # Corner cases make sure that n > 4 a = 2 + random.randint(1, n - 4); # Compute a^d % n x = power(a, d, n); if (x == 1 or x == n - 1): return True; # Keep squaring x while one # of the following doesn't # happen # (i) d does not reach n-1 # (ii) (x^2) % n is not 1 # (iii) (x^2) % n is not n-1 while (d != n - 1): x = (x * x) % n; d *= 2; if (x == 1): return False; if (x == n - 1): return True; # Return composite return False; # It returns false if n is# composite and returns true if n# is probably prime. k is an# input parameter that determines# accuracy level. Higher value of# k indicates more accuracy.def isPrime( n, k): # Corner cases if (n <= 1 or n == 4): return False; if (n <= 3): return True; # Find r such that n = # 2^d * r + 1 for some r >= 1 d = n - 1; while (d % 2 == 0): d //= 2; # Iterate given number of 'k' times for i in range(k): if (miillerTest(d, n) == False): return False; return True; # Driver Code# Number of iterationsk = 4; print(\"All primes smaller than 100: \");for n in range(1,100): if (isPrime(n, k)): print(n , end=\" \"); # This code is contributed by mits", "e": 33816, "s": 31778, "text": null }, { "code": "// C# program Miller-Rabin primality testusing System; class GFG{ // Utility function to do modular // exponentiation. It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result // Update x if it is more than // or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // This function is called for all k trials. // It returns false if n is composite and // returns false if n is probably prime. // d is an odd number such that d*2<sup>r</sup> // = n-1 for some r >= 1 static bool miillerTest(int d, int n) { // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 Random r = new Random(); int a = 2 + (int)(r.Next() % (n - 4)); // Compute a^d % n int x = power(a, d, n); if (x == 1 || x == n - 1) return true; // Keep squaring x while one of the // following doesn't happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // Return composite return false; } // It returns false if n is composite // and returns true if n is probably // prime. k is an input parameter that // determines accuracy level. Higher // value of k indicates more accuracy. static bool isPrime(int n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = 2^d * r + 1 // for some r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (int i = 0; i < k; i++) if (miillerTest(d, n) == false) return false; return true; } // Driver Code static void Main() { int k = 4; // Number of iterations Console.WriteLine(\"All primes smaller \" + \"than 100: \"); for (int n = 1; n < 100; n++) if (isPrime(n, k)) Console.Write(n + \" \"); }} // This code is contributed by mits", "e": 36565, "s": 33816, "text": null }, { "code": "<?php// PHP program Miller-Rabin primality test // Utility function to do// modular exponentiation.// It returns (x^y) % pfunction power($x, $y, $p){ // Initialize result $res = 1; // Update x if it is more than or // equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res*$x) % $p; // y must be even now $y = $y>>1; // $y = $y/2 $x = ($x*$x) % $p; } return $res;} // This function is called// for all k trials. It returns// false if n is composite and// returns false if n is// probably prime. d is an odd// number such that d*2<sup>r</sup> = n-1// for some r >= 1function miillerTest($d, $n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 $a = 2 + rand() % ($n - 4); // Compute a^d % n $x = power($a, $d, $n); if ($x == 1 || $x == $n-1) return true; // Keep squaring x while one // of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while ($d != $n-1) { $x = ($x * $x) % $n; $d *= 2; if ($x == 1) return false; if ($x == $n-1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime. k is an// input parameter that determines// accuracy level. Higher value of// k indicates more accuracy.function isPrime( $n, $k){ // Corner cases if ($n <= 1 || $n == 4) return false; if ($n <= 3) return true; // Find r such that n = // 2^d * r + 1 for some r >= 1 $d = $n - 1; while ($d % 2 == 0) $d /= 2; // Iterate given number of 'k' times for ($i = 0; $i < $k; $i++) if (!miillerTest($d, $n)) return false; return true;} // Driver Code // Number of iterations $k = 4; echo \"All primes smaller than 100: \\n\"; for ($n = 1; $n < 100; $n++) if (isPrime($n, $k)) echo $n , \" \"; // This code is contributed by ajit?>", "e": 38680, "s": 36565, "text": null }, { "code": "<script>// Javascript program Miller-Rabin primality test // Utility function to do// modular exponentiation.// It returns (x^y) % pfunction power(x, y, p){ // Initialize result let res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // This function is called// for all k trials. It returns// false if n is composite and// returns false if n is// probably prime. d is an odd// number such that d*2<sup>r</sup> = n-1// for some r >= 1function miillerTest(d, n){ // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 let a = 2 + Math.floor(Math.random() * (n-2)) % (n - 4); // Compute a^d % n let x = power(a, d, n); if (x == 1 || x == n-1) return true; // Keep squaring x while one // of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n-1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n-1) return true; } // Return composite return false;} // It returns false if n is// composite and returns true if n// is probably prime. k is an// input parameter that determines// accuracy level. Higher value of// k indicates more accuracy.function isPrime( n, k){ // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Find r such that n = // 2^d * r + 1 for some r >= 1 let d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given number of 'k' times for (let i = 0; i < k; i++) if (!miillerTest(d, n)) return false; return true;} // Driver Code// Number of iterationslet k = 4; document.write(\"All primes smaller than 100: <br>\");for (let n = 1; n < 100; n++) if (isPrime(n, k)) document.write(n , \" \"); // This code is contributed by gfgking</script>", "e": 40837, "s": 38680, "text": null }, { "code": null, "e": 40847, "s": 40837, "text": "Output: " }, { "code": null, "e": 40950, "s": 40847, "text": "All primes smaller than 100: \n2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 \n61 67 71 73 79 83 89 97 " }, { "code": null, "e": 41025, "s": 40950, "text": "How does this work? Below are some important facts behind the algorithm: " }, { "code": null, "e": 41618, "s": 41025, "text": "Fermat’s theorem states that, If n is a prime number, then for every a, 1 <= a < n, an-1 % n = 1Base cases make sure that n must be odd. Since n is odd, n-1 must be even. And an even number can be written as d * 2s where d is an odd number and s > 0.From the above two points, for every randomly picked number in the range [2, n-2], the value of ad*2r % n must be 1.As per Euclid’s Lemma, if x2 % n = 1 or (x2 – 1) % n = 0 or (x-1)(x+1)% n = 0. Then, for n to be prime, either n divides (x-1) or n divides (x+1). Which means either x % n = 1 or x % n = -1.From points 2 and 3, we can conclude" }, { "code": null, "e": 41715, "s": 41618, "text": "Fermat’s theorem states that, If n is a prime number, then for every a, 1 <= a < n, an-1 % n = 1" }, { "code": null, "e": 41870, "s": 41715, "text": "Base cases make sure that n must be odd. Since n is odd, n-1 must be even. And an even number can be written as d * 2s where d is an odd number and s > 0." }, { "code": null, "e": 41987, "s": 41870, "text": "From the above two points, for every randomly picked number in the range [2, n-2], the value of ad*2r % n must be 1." }, { "code": null, "e": 42178, "s": 41987, "text": "As per Euclid’s Lemma, if x2 % n = 1 or (x2 – 1) % n = 0 or (x-1)(x+1)% n = 0. Then, for n to be prime, either n divides (x-1) or n divides (x+1). Which means either x % n = 1 or x % n = -1." }, { "code": null, "e": 42215, "s": 42178, "text": "From points 2 and 3, we can conclude" }, { "code": null, "e": 42331, "s": 42215, "text": " For n to be prime, either\n ad % n = 1 \n OR \n ad*2i % n = -1 \n for some i, where 0 <= i <= r-1." }, { "code": null, "e": 42553, "s": 42331, "text": "Next Article : Primality Test | Set 4 (Solovay-Strassen)This article is contributed Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 42559, "s": 42553, "text": "jit_t" }, { "code": null, "e": 42571, "s": 42559, "text": "kartikay101" }, { "code": null, "e": 42584, "s": 42571, "text": "Mithun Kumar" }, { "code": null, "e": 42602, "s": 42584, "text": "Jitendra Kushwaha" }, { "code": null, "e": 42614, "s": 42602, "text": "local-dante" }, { "code": null, "e": 42629, "s": 42614, "text": "sakshikhachane" }, { "code": null, "e": 42637, "s": 42629, "text": "gfgking" }, { "code": null, "e": 42650, "s": 42637, "text": "simmytarika5" }, { "code": null, "e": 42669, "s": 42650, "text": "Modular Arithmetic" }, { "code": null, "e": 42683, "s": 42669, "text": "number-theory" }, { "code": null, "e": 42696, "s": 42683, "text": "Prime Number" }, { "code": null, "e": 42709, "s": 42696, "text": "Mathematical" }, { "code": null, "e": 42723, "s": 42709, "text": "number-theory" }, { "code": null, "e": 42736, "s": 42723, "text": "Mathematical" }, { "code": null, "e": 42749, "s": 42736, "text": "Prime Number" }, { "code": null, "e": 42768, "s": 42749, "text": "Modular Arithmetic" }, { "code": null, "e": 42866, "s": 42768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42890, "s": 42866, "text": "Merge two sorted arrays" }, { "code": null, "e": 42933, "s": 42890, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 42982, "s": 42933, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 43023, "s": 42982, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 43057, "s": 43023, "text": "Program for factorial of a number" }, { "code": null, "e": 43078, "s": 43057, "text": "Operators in C / C++" }, { "code": null, "e": 43121, "s": 43078, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 43174, "s": 43121, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 43211, "s": 43174, "text": "Minimum number of jumps to reach end" } ]