title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Perfect Number
22 Mar, 2022 A number is a perfect number if is equal to sum of its proper divisors, that is, sum of its positive divisors excluding the number itself. Write a function to check if a given number is perfect or not. Examples: Input: n = 15 Output: false Divisors of 15 are 1, 3 and 5. Sum of divisors is 9 which is not equal to 15. Input: n = 6 Output: true Divisors of 6 are 1, 2 and 3. Sum of divisors is 6. A Simple Solution is to go through every number from 1 to n-1 and check if it is a divisor. Maintain sum of all divisors. If sum becomes equal to n, then return true, else return false.An Efficient Solution is to go through numbers till square root of n. If a number ‘i’ divides n, then add both ‘i’ and n/i to sum. Below is the implementation of efficient solution. C++ Java Python3 C# PHP Javascript // C++ program to check if a given number is perfect// or not#include<iostream>using namespace std; // Returns true if n is perfectbool isPerfect(long long int n){ // To store sum of divisors long long int sum = 1; // Find all divisors and add them for (long long int i=2; i*i<=n; i++) { if (n%i==0) { if(i*i!=n) sum = sum + i + n/i; else sum=sum+i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver programint main(){ cout << "Below are all perfect numbers till 10000\n"; for (int n =2; n<10000; n++) if (isPerfect(n)) cout << n << " is a perfect number\n"; return 0;} // Java program to check if a given// number is perfect or notclass GFG{ // Returns true if n is perfectstatic boolean isPerfect(int n){ // To store sum of divisors int sum = 1; // Find all divisors and add them for (int i = 2; i * i <= n; i++) { if (n % i==0) { if(i * i != n) sum = sum + i + n / i; else sum = sum + i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver programpublic static void main (String[] args){ System.out.println("Below are all perfect" + "numbers till 10000"); for (int n = 2; n < 10000; n++) if (isPerfect(n)) System.out.println( n + " is a perfect number");}} // This code is contributed by mits # Python3 code to check if a given# number is perfect or not # Returns true if n is perfectdef isPerfect( n ): # To store sum of divisors sum = 1 # Find all divisors and add them i = 2 while i * i <= n: if n % i == 0: sum = sum + i + n/i i += 1 # If sum of divisors is equal to # n, then n is a perfect number return (True if sum == n and n!=1 else False) # Driver programprint("Below are all perfect numbers till 10000")n = 2for n in range (10000): if isPerfect (n): print(n , " is a perfect number") # This code is contributed by "Sharad_Bhardwaj". // C# program to check if a given// number is perfect or not class GFG{ // Returns true if n is perfectstatic bool isPerfect(int n){ // To store sum of divisors int sum = 1; // Find all divisors and add them for (int i = 2; i * i <= n; i++) { if (n % i==0) { if(i * i != n) sum = sum + i + n / i; else sum = sum + i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver programstatic void Main(){ System.Console.WriteLine("Below are all perfect" + "numbers till 10000"); for (int n = 2; n < 10000; n++) if (isPerfect(n)) System.Console.WriteLine( n + " is a perfect number");}} // This code is contributed by chandan_jnu <?php// PHP program to check if a given number// is perfect or not // Returns true if n is perfectfunction isPerfect($n){ // To store sum of divisors $sum = 1; // Find all divisors and add them for ($i = 2; $i * $i <= $n; $i++) { if ($n % $i == 0) { if($i * $i != $n) $sum = $sum + $i + (int)($n / $i); else $sum = $sum + $i; } } // If sum of divisors is equal to // n, then n is a perfect number if ($sum == $n && $n != 1) return true; return false;} // Driver Codeecho "Below are all perfect numbers till 10000\n";for ($n = 2; $n < 10000; $n++) if (isPerfect($n)) echo "$n is a perfect number\n"; // This code is contributed by mits?> <script> // Javascript program to check if a given number is perfect// or not // Returns true if n is perfectfunction isPerfect(n){ // To store sum of divisors sum = 1; // Find all divisors and add them for (let i=2; i*i<=n; i++) { if (n%i==0) { if(i*i!=n) sum = sum + i + n/i; else sum=sum+i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver program document.write("Below are all perfect numbers till 10000" + "<br>"); for (let n =2; n<10000; n++) if (isPerfect(n)) document.write(n + " is a perfect number" + "<br>"); // This code is contributed by Mayank Tyagi </script> Output: Below are all perfect numbers till 10000 6 is a perfect number 28 is a perfect number 496 is a perfect number 8128 is a perfect number Time Complexity: O(√n) Auxiliary Space: O(1)Below are some interesting facts about Perfect Numbers: 1) Every even perfect number is of the form 2p?1(2p ? 1) where 2p ? 1 is prime. 2) It is unknown whether there are any odd perfect numbers.References: https://en.wikipedia.org/wiki/Perfect_numberPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Milan1999 Mithun Kumar Akanksha_Rai Chandan_Kumar mayanktyagi1709 arorakashish0911 rohitkumarsinghcna Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Mar, 2022" }, { "code": null, "e": 265, "s": 52, "text": "A number is a perfect number if is equal to sum of its proper divisors, that is, sum of its positive divisors excluding the number itself. Write a function to check if a given number is perfect or not. Examples: " }, { "code": null, "e": 452, "s": 265, "text": "Input: n = 15\nOutput: false\nDivisors of 15 are 1, 3 and 5. Sum of \ndivisors is 9 which is not equal to 15.\n\nInput: n = 6\nOutput: true\nDivisors of 6 are 1, 2 and 3. Sum of \ndivisors is 6." }, { "code": null, "e": 823, "s": 454, "text": "A Simple Solution is to go through every number from 1 to n-1 and check if it is a divisor. Maintain sum of all divisors. If sum becomes equal to n, then return true, else return false.An Efficient Solution is to go through numbers till square root of n. If a number ‘i’ divides n, then add both ‘i’ and n/i to sum. Below is the implementation of efficient solution. " }, { "code": null, "e": 827, "s": 823, "text": "C++" }, { "code": null, "e": 832, "s": 827, "text": "Java" }, { "code": null, "e": 840, "s": 832, "text": "Python3" }, { "code": null, "e": 843, "s": 840, "text": "C#" }, { "code": null, "e": 847, "s": 843, "text": "PHP" }, { "code": null, "e": 858, "s": 847, "text": "Javascript" }, { "code": "// C++ program to check if a given number is perfect// or not#include<iostream>using namespace std; // Returns true if n is perfectbool isPerfect(long long int n){ // To store sum of divisors long long int sum = 1; // Find all divisors and add them for (long long int i=2; i*i<=n; i++) { if (n%i==0) { if(i*i!=n) sum = sum + i + n/i; else sum=sum+i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver programint main(){ cout << \"Below are all perfect numbers till 10000\\n\"; for (int n =2; n<10000; n++) if (isPerfect(n)) cout << n << \" is a perfect number\\n\"; return 0;}", "e": 1661, "s": 858, "text": null }, { "code": "// Java program to check if a given// number is perfect or notclass GFG{ // Returns true if n is perfectstatic boolean isPerfect(int n){ // To store sum of divisors int sum = 1; // Find all divisors and add them for (int i = 2; i * i <= n; i++) { if (n % i==0) { if(i * i != n) sum = sum + i + n / i; else sum = sum + i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver programpublic static void main (String[] args){ System.out.println(\"Below are all perfect\" + \"numbers till 10000\"); for (int n = 2; n < 10000; n++) if (isPerfect(n)) System.out.println( n + \" is a perfect number\");}} // This code is contributed by mits", "e": 2558, "s": 1661, "text": null }, { "code": "# Python3 code to check if a given# number is perfect or not # Returns true if n is perfectdef isPerfect( n ): # To store sum of divisors sum = 1 # Find all divisors and add them i = 2 while i * i <= n: if n % i == 0: sum = sum + i + n/i i += 1 # If sum of divisors is equal to # n, then n is a perfect number return (True if sum == n and n!=1 else False) # Driver programprint(\"Below are all perfect numbers till 10000\")n = 2for n in range (10000): if isPerfect (n): print(n , \" is a perfect number\") # This code is contributed by \"Sharad_Bhardwaj\".", "e": 3196, "s": 2558, "text": null }, { "code": "// C# program to check if a given// number is perfect or not class GFG{ // Returns true if n is perfectstatic bool isPerfect(int n){ // To store sum of divisors int sum = 1; // Find all divisors and add them for (int i = 2; i * i <= n; i++) { if (n % i==0) { if(i * i != n) sum = sum + i + n / i; else sum = sum + i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver programstatic void Main(){ System.Console.WriteLine(\"Below are all perfect\" + \"numbers till 10000\"); for (int n = 2; n < 10000; n++) if (isPerfect(n)) System.Console.WriteLine( n + \" is a perfect number\");}} // This code is contributed by chandan_jnu", "e": 4087, "s": 3196, "text": null }, { "code": "<?php// PHP program to check if a given number// is perfect or not // Returns true if n is perfectfunction isPerfect($n){ // To store sum of divisors $sum = 1; // Find all divisors and add them for ($i = 2; $i * $i <= $n; $i++) { if ($n % $i == 0) { if($i * $i != $n) $sum = $sum + $i + (int)($n / $i); else $sum = $sum + $i; } } // If sum of divisors is equal to // n, then n is a perfect number if ($sum == $n && $n != 1) return true; return false;} // Driver Codeecho \"Below are all perfect numbers till 10000\\n\";for ($n = 2; $n < 10000; $n++) if (isPerfect($n)) echo \"$n is a perfect number\\n\"; // This code is contributed by mits?>", "e": 4846, "s": 4087, "text": null }, { "code": "<script> // Javascript program to check if a given number is perfect// or not // Returns true if n is perfectfunction isPerfect(n){ // To store sum of divisors sum = 1; // Find all divisors and add them for (let i=2; i*i<=n; i++) { if (n%i==0) { if(i*i!=n) sum = sum + i + n/i; else sum=sum+i; } } // If sum of divisors is equal to // n, then n is a perfect number if (sum == n && n != 1) return true; return false;} // Driver program document.write(\"Below are all perfect numbers till 10000\" + \"<br>\"); for (let n =2; n<10000; n++) if (isPerfect(n)) document.write(n + \" is a perfect number\" + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 5642, "s": 4846, "text": null }, { "code": null, "e": 5652, "s": 5642, "text": "Output: " }, { "code": null, "e": 5787, "s": 5652, "text": "Below are all perfect numbers till 10000\n6 is a perfect number\n28 is a perfect number\n496 is a perfect number\n8128 is a perfect number" }, { "code": null, "e": 5810, "s": 5787, "text": "Time Complexity: O(√n)" }, { "code": null, "e": 6207, "s": 5810, "text": "Auxiliary Space: O(1)Below are some interesting facts about Perfect Numbers: 1) Every even perfect number is of the form 2p?1(2p ? 1) where 2p ? 1 is prime. 2) It is unknown whether there are any odd perfect numbers.References: https://en.wikipedia.org/wiki/Perfect_numberPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 6217, "s": 6207, "text": "Milan1999" }, { "code": null, "e": 6230, "s": 6217, "text": "Mithun Kumar" }, { "code": null, "e": 6243, "s": 6230, "text": "Akanksha_Rai" }, { "code": null, "e": 6257, "s": 6243, "text": "Chandan_Kumar" }, { "code": null, "e": 6273, "s": 6257, "text": "mayanktyagi1709" }, { "code": null, "e": 6290, "s": 6273, "text": "arorakashish0911" }, { "code": null, "e": 6309, "s": 6290, "text": "rohitkumarsinghcna" }, { "code": null, "e": 6322, "s": 6309, "text": "Mathematical" }, { "code": null, "e": 6335, "s": 6322, "text": "Mathematical" } ]
Python | Size Range Combinations in list
23 Jan, 2020 The problem of finding the combinations of list elements of specific size has been discussed. But sometimes, we require more and we wish to have all the combinations of elements of all sizes in range between i and j. Let’s discuss certain ways in which this function can be performed. Method #1 : Using list comprehension + combinations()This task can be performed using the list comprehension which can perform the task of varying the combination length and combination() can perform the actual task of finding combinations. # Python3 code to demonstrate working of# Size Range Combinations in list# Using list comprehension + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint("The original list is : " + str(test_list)) # initializing i, j i, j = 2, 4 # Size Range Combinations in list# Using list comprehension + combinations()res1 = [com for sub in range(j) for com in combinations(test_list, sub + 1)]res2 = [com for sub in range(i - 1) for com in combinations(test_list, sub + 1)]res = list(set(res1) - set(res2)) # Printing resultprint("The combinations of elements in range of i and j : " + str(res)) The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements in range of i and j : [(7, 3), (4, 7), (4, 5, 6, 3), (4, 8), (5, 6), (5, 6, 3), (4, 6, 8), (5, 7, 8), (5, 6, 7, 8), (6, 7, 3), (6, 7, 3, 8), (5, 8), (5, 3, 8), (5, 6, 7), (6, 7), (4, 7, 3, 8), (5, 6, 3, 8), (5, 6, 8), (4, 6, 7, 8), (6, 3), (6, 3, 8), (5, 7, 3, 8), (7, 3, 8), (5, 7, 3), (4, 5, 7, 3), (4, 7, 8), (4, 6, 7), (4, 5, 3), (4, 5), (4, 6, 7, 3), (6, 7, 8), (4, 6, 3, 8), (4, 5, 6, 8), (4, 3, 8), (4, 5, 7, 8), (4, 5, 6), (5, 3), (4, 6, 3), (4, 5, 6, 7), (4, 5, 7), (4, 6), (6, 8), (4, 5, 3, 8), (4, 5, 8), (5, 7), (3, 8), (4, 3), (5, 6, 7, 3), (4, 7, 3), (7, 8)] Method 2 : Using loop + extend() + combinations()This method is similar to above method, just the loop is being using to iterate for combination size and extend() performs the task of adding the combinations one after another to final result. # Python3 code to demonstrate working of# Size Range Combinations in list# Using loop + extend() + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint("The original list is : " + str(test_list)) # initializing i, j i, j = 2, 4 # Size Range Combinations in list# Using loop + extend() + combinations()res = []for sub in range(j): if sub >= (i - 1): res.extend(combinations(test_list, sub + 1)) # Printing resultprint("The combinations of elements in range of i and j : " + str(res)) The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements in range of i and j : [(7, 3), (4, 7), (4, 5, 6, 3), (4, 8), (5, 6), (5, 6, 3), (4, 6, 8), (5, 7, 8), (5, 6, 7, 8), (6, 7, 3), (6, 7, 3, 8), (5, 8), (5, 3, 8), (5, 6, 7), (6, 7), (4, 7, 3, 8), (5, 6, 3, 8), (5, 6, 8), (4, 6, 7, 8), (6, 3), (6, 3, 8), (5, 7, 3, 8), (7, 3, 8), (5, 7, 3), (4, 5, 7, 3), (4, 7, 8), (4, 6, 7), (4, 5, 3), (4, 5), (4, 6, 7, 3), (6, 7, 8), (4, 6, 3, 8), (4, 5, 6, 8), (4, 3, 8), (4, 5, 7, 8), (4, 5, 6), (5, 3), (4, 6, 3), (4, 5, 6, 7), (4, 5, 7), (4, 6), (6, 8), (4, 5, 3, 8), (4, 5, 8), (5, 7), (3, 8), (4, 3), (5, 6, 7, 3), (4, 7, 3), (7, 8)] Python list-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2020" }, { "code": null, "e": 313, "s": 28, "text": "The problem of finding the combinations of list elements of specific size has been discussed. But sometimes, we require more and we wish to have all the combinations of elements of all sizes in range between i and j. Let’s discuss certain ways in which this function can be performed." }, { "code": null, "e": 554, "s": 313, "text": "Method #1 : Using list comprehension + combinations()This task can be performed using the list comprehension which can perform the task of varying the combination length and combination() can perform the actual task of finding combinations." }, { "code": "# Python3 code to demonstrate working of# Size Range Combinations in list# Using list comprehension + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing i, j i, j = 2, 4 # Size Range Combinations in list# Using list comprehension + combinations()res1 = [com for sub in range(j) for com in combinations(test_list, sub + 1)]res2 = [com for sub in range(i - 1) for com in combinations(test_list, sub + 1)]res = list(set(res1) - set(res2)) # Printing resultprint(\"The combinations of elements in range of i and j : \" + str(res))", "e": 1221, "s": 554, "text": null }, { "code": null, "e": 1864, "s": 1221, "text": "The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements in range of i and j : [(7, 3), (4, 7), (4, 5, 6, 3), (4, 8), (5, 6), (5, 6, 3), (4, 6, 8), (5, 7, 8), (5, 6, 7, 8), (6, 7, 3), (6, 7, 3, 8), (5, 8), (5, 3, 8), (5, 6, 7), (6, 7), (4, 7, 3, 8), (5, 6, 3, 8), (5, 6, 8), (4, 6, 7, 8), (6, 3), (6, 3, 8), (5, 7, 3, 8), (7, 3, 8), (5, 7, 3), (4, 5, 7, 3), (4, 7, 8), (4, 6, 7), (4, 5, 3), (4, 5), (4, 6, 7, 3), (6, 7, 8), (4, 6, 3, 8), (4, 5, 6, 8), (4, 3, 8), (4, 5, 7, 8), (4, 5, 6), (5, 3), (4, 6, 3), (4, 5, 6, 7), (4, 5, 7), (4, 6), (6, 8), (4, 5, 3, 8), (4, 5, 8), (5, 7), (3, 8), (4, 3), (5, 6, 7, 3), (4, 7, 3), (7, 8)]" }, { "code": null, "e": 2109, "s": 1866, "text": "Method 2 : Using loop + extend() + combinations()This method is similar to above method, just the loop is being using to iterate for combination size and extend() performs the task of adding the combinations one after another to final result." }, { "code": "# Python3 code to demonstrate working of# Size Range Combinations in list# Using loop + extend() + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing i, j i, j = 2, 4 # Size Range Combinations in list# Using loop + extend() + combinations()res = []for sub in range(j): if sub >= (i - 1): res.extend(combinations(test_list, sub + 1)) # Printing resultprint(\"The combinations of elements in range of i and j : \" + str(res))", "e": 2683, "s": 2109, "text": null }, { "code": null, "e": 3326, "s": 2683, "text": "The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements in range of i and j : [(7, 3), (4, 7), (4, 5, 6, 3), (4, 8), (5, 6), (5, 6, 3), (4, 6, 8), (5, 7, 8), (5, 6, 7, 8), (6, 7, 3), (6, 7, 3, 8), (5, 8), (5, 3, 8), (5, 6, 7), (6, 7), (4, 7, 3, 8), (5, 6, 3, 8), (5, 6, 8), (4, 6, 7, 8), (6, 3), (6, 3, 8), (5, 7, 3, 8), (7, 3, 8), (5, 7, 3), (4, 5, 7, 3), (4, 7, 8), (4, 6, 7), (4, 5, 3), (4, 5), (4, 6, 7, 3), (6, 7, 8), (4, 6, 3, 8), (4, 5, 6, 8), (4, 3, 8), (4, 5, 7, 8), (4, 5, 6), (5, 3), (4, 6, 3), (4, 5, 6, 7), (4, 5, 7), (4, 6), (6, 8), (4, 5, 3, 8), (4, 5, 8), (5, 7), (3, 8), (4, 3), (5, 6, 7, 3), (4, 7, 3), (7, 8)]" }, { "code": null, "e": 3347, "s": 3326, "text": "Python list-programs" }, { "code": null, "e": 3354, "s": 3347, "text": "Python" } ]
How to sort a list in C# | List.Sort() Method Set -1
12 Feb, 2019 List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of this method as follows: Sort(IComparer<T>)Sort(Int32, Int32, IComparer)Sort()Sort(Comparison<T>) Sort(IComparer<T>) Sort(Int32, Int32, IComparer) Sort() Sort(Comparison<T>) Here, we will discuss the first two methods. This method is used to sort the elements in the entire List<T> using the specified comparer. Syntax: public void Sort (System.Collections.Generic.IComparer<T> comparer); Here, the comparer is the IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default. Exceptions: InvalidOperationException: If the comparer is null, and the default comparer Default cannot find the implementation of the IComparable<T> generic interface or the IComparable interface for type T. ArgumentException: If the implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself. Example 1: // C# program to demonstrate the concept of // List<T>.Sort(IComparer <T>) methodusing System;using System.Collections.Generic; class GFG : IComparer<int>{ public int Compare(int x, int y) { if (x == 0 || y == 0) { return 0; } // CompareTo() method return x.CompareTo(y); }} public class geek{ // Main Method public static void Main() { // List initialize List<int> list1 = new List<int> { // list elements 1,5,6,2,4,3 }; Console.WriteLine("Original List"); foreach(int g in list1) { // Display Original List Console.WriteLine(g); } // "gg" is the object oif class GFG GFG gg = new GFG(); Console.WriteLine("\nSort with a comparer:"); // use of List<T>.Sort(IComparer<T>) // method. The comparer is "gg" list1.Sort(gg); foreach( int g in list1 ) { // Display sorted list Console.WriteLine(g); } }} Original List 1 5 6 2 4 3 Sort with a comparer: 1 2 3 4 5 6 Example 2: // C# program to demonstrate the concept of // List<T>.Sort(IComparer <T>) methodusing System;using System.Collections.Generic; class GFG : IComparer<string>{ public int Compare(string x, string y) { if (x == null || y == null) { return 0; } // "CompareTo()" method return x.CompareTo(y); }} public class geek{ // Main Method public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add("A"); list1.Add("I"); list1.Add("G"); list1.Add("B"); list1.Add("E"); list1.Add("H"); list1.Add("F"); list1.Add("C"); list1.Add("J"); Console.WriteLine("Original List"); // Display Original List Display(list1); // "gg" is the object GFG gg = new GFG(); Console.WriteLine("\nSort with a comparer:"); // sort the list with a // specified comparer "gg" list1.Sort(gg); // Display sorted List Display(list1); Console.WriteLine("\nBinarySearch and Insert D"); // Binary Search for "D" // using List.BinarySearch(T) method int index = list1.BinarySearch("D"); if (index < 0) { // range++; list1.Insert(~index, "D"); } // Display the List after // inserting "D" Display(list1); } // Display function public static void Display(List<string> list) { foreach( string g in list ) { Console.WriteLine(g); } }} Original List A I G B E H F C J Sort with a comparer: A B C E F G H I J BinarySearch and Insert D A B C D E F G H I J This method is used to sort the elements in a range of elements in List<T> using the specified comparer. Syntax: public void Sort(int index, int len, IComparer<T> comparer) Parameters: index : It is the zero-based starting index of the range in which sort will happen. len : It is the length of the range. comparer : When comparing elements then use the IComparer implementation or null to use the default comparer Default. Exceptions: ArgumentOutOfRangeException : If indexor len is less than 0. ArgumentException : If index and count do not specify a valid range in the List. InvalidOperationException : If comparer is null. Example: // C# program to demonstrate the use of // List<T>.Sort(Int32, Int32, IComparer<T>)// Methodusing System;using System.Collections.Generic; class GFG : IComparer<string>{ public int Compare(string x, string y) { if (x == null || y == null) { return 0; } // "CompareTo()" method return x.CompareTo(y); }} public class geek{ public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add("C++"); list1.Add("Java"); list1.Add("C"); list1.Add("Python"); list1.Add("HTML"); list1.Add("CSS"); list1.Add("Scala"); list1.Add("Ruby"); list1.Add("Perl"); int range = 4; Console.WriteLine("Original List"); // Display Original List Display(list1); // "gg" is the object GFG gg = new GFG(); Console.WriteLine("\nSort a range with comparer:"); // sort the list within a // range of index 1 to 4 // where range = 4 list1.Sort(1, range, gg); // Display sorted List Display(list1); Console.WriteLine("\nBinarySearch and Insert Dart"); // Binary Search and storing // index value to "index" int index = list1.BinarySearch(0, range, "Dart", gg); if (index < 0) { list1.Insert(~index, "Dart"); range++; } // Display the List // after inserting "Dart" Display(list1); } // Display function public static void Display(List<string> list) { foreach(string g in list) { Console.WriteLine(g); } }} Original List C++ Java C Python HTML CSS Scala Ruby Perl Sort a range with comparer: C++ C HTML Java Python CSS Scala Ruby Perl BinarySearch and Insert Dart C++ C Dart HTML Java Python CSS Scala Ruby Perl Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=netframework-4.7.2 CSharp-Generic-List CSharp-Generic-Namespace CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 326, "s": 28, "text": "List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of this method as follows:" }, { "code": null, "e": 399, "s": 326, "text": "Sort(IComparer<T>)Sort(Int32, Int32, IComparer)Sort()Sort(Comparison<T>)" }, { "code": null, "e": 418, "s": 399, "text": "Sort(IComparer<T>)" }, { "code": null, "e": 448, "s": 418, "text": "Sort(Int32, Int32, IComparer)" }, { "code": null, "e": 455, "s": 448, "text": "Sort()" }, { "code": null, "e": 475, "s": 455, "text": "Sort(Comparison<T>)" }, { "code": null, "e": 520, "s": 475, "text": "Here, we will discuss the first two methods." }, { "code": null, "e": 613, "s": 520, "text": "This method is used to sort the elements in the entire List<T> using the specified comparer." }, { "code": null, "e": 621, "s": 613, "text": "Syntax:" }, { "code": null, "e": 690, "s": 621, "text": "public void Sort (System.Collections.Generic.IComparer<T> comparer);" }, { "code": null, "e": 821, "s": 690, "text": "Here, the comparer is the IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default." }, { "code": null, "e": 833, "s": 821, "text": "Exceptions:" }, { "code": null, "e": 1030, "s": 833, "text": "InvalidOperationException: If the comparer is null, and the default comparer Default cannot find the implementation of the IComparable<T> generic interface or the IComparable interface for type T." }, { "code": null, "e": 1193, "s": 1030, "text": "ArgumentException: If the implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself." }, { "code": null, "e": 1204, "s": 1193, "text": "Example 1:" }, { "code": "// C# program to demonstrate the concept of // List<T>.Sort(IComparer <T>) methodusing System;using System.Collections.Generic; class GFG : IComparer<int>{ public int Compare(int x, int y) { if (x == 0 || y == 0) { return 0; } // CompareTo() method return x.CompareTo(y); }} public class geek{ // Main Method public static void Main() { // List initialize List<int> list1 = new List<int> { // list elements 1,5,6,2,4,3 }; Console.WriteLine(\"Original List\"); foreach(int g in list1) { // Display Original List Console.WriteLine(g); } // \"gg\" is the object oif class GFG GFG gg = new GFG(); Console.WriteLine(\"\\nSort with a comparer:\"); // use of List<T>.Sort(IComparer<T>) // method. The comparer is \"gg\" list1.Sort(gg); foreach( int g in list1 ) { // Display sorted list Console.WriteLine(g); } }}", "e": 2425, "s": 1204, "text": null }, { "code": null, "e": 2487, "s": 2425, "text": "Original List\n1\n5\n6\n2\n4\n3\n\nSort with a comparer:\n1\n2\n3\n4\n5\n6\n" }, { "code": null, "e": 2498, "s": 2487, "text": "Example 2:" }, { "code": "// C# program to demonstrate the concept of // List<T>.Sort(IComparer <T>) methodusing System;using System.Collections.Generic; class GFG : IComparer<string>{ public int Compare(string x, string y) { if (x == null || y == null) { return 0; } // \"CompareTo()\" method return x.CompareTo(y); }} public class geek{ // Main Method public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add(\"A\"); list1.Add(\"I\"); list1.Add(\"G\"); list1.Add(\"B\"); list1.Add(\"E\"); list1.Add(\"H\"); list1.Add(\"F\"); list1.Add(\"C\"); list1.Add(\"J\"); Console.WriteLine(\"Original List\"); // Display Original List Display(list1); // \"gg\" is the object GFG gg = new GFG(); Console.WriteLine(\"\\nSort with a comparer:\"); // sort the list with a // specified comparer \"gg\" list1.Sort(gg); // Display sorted List Display(list1); Console.WriteLine(\"\\nBinarySearch and Insert D\"); // Binary Search for \"D\" // using List.BinarySearch(T) method int index = list1.BinarySearch(\"D\"); if (index < 0) { // range++; list1.Insert(~index, \"D\"); } // Display the List after // inserting \"D\" Display(list1); } // Display function public static void Display(List<string> list) { foreach( string g in list ) { Console.WriteLine(g); } }}", "e": 4232, "s": 2498, "text": null }, { "code": null, "e": 4353, "s": 4232, "text": "Original List\nA\nI\nG\nB\nE\nH\nF\nC\nJ\n\nSort with a comparer:\nA\nB\nC\nE\nF\nG\nH\nI\nJ\n\nBinarySearch and Insert D\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\n" }, { "code": null, "e": 4458, "s": 4353, "text": "This method is used to sort the elements in a range of elements in List<T> using the specified comparer." }, { "code": null, "e": 4466, "s": 4458, "text": "Syntax:" }, { "code": null, "e": 4526, "s": 4466, "text": "public void Sort(int index, int len, IComparer<T> comparer)" }, { "code": null, "e": 4538, "s": 4526, "text": "Parameters:" }, { "code": null, "e": 4622, "s": 4538, "text": "index : It is the zero-based starting index of the range in which sort will happen." }, { "code": null, "e": 4659, "s": 4622, "text": "len : It is the length of the range." }, { "code": null, "e": 4777, "s": 4659, "text": "comparer : When comparing elements then use the IComparer implementation or null to use the default comparer Default." }, { "code": null, "e": 4789, "s": 4777, "text": "Exceptions:" }, { "code": null, "e": 4850, "s": 4789, "text": "ArgumentOutOfRangeException : If indexor len is less than 0." }, { "code": null, "e": 4931, "s": 4850, "text": "ArgumentException : If index and count do not specify a valid range in the List." }, { "code": null, "e": 4980, "s": 4931, "text": "InvalidOperationException : If comparer is null." }, { "code": null, "e": 4989, "s": 4980, "text": "Example:" }, { "code": "// C# program to demonstrate the use of // List<T>.Sort(Int32, Int32, IComparer<T>)// Methodusing System;using System.Collections.Generic; class GFG : IComparer<string>{ public int Compare(string x, string y) { if (x == null || y == null) { return 0; } // \"CompareTo()\" method return x.CompareTo(y); }} public class geek{ public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add(\"C++\"); list1.Add(\"Java\"); list1.Add(\"C\"); list1.Add(\"Python\"); list1.Add(\"HTML\"); list1.Add(\"CSS\"); list1.Add(\"Scala\"); list1.Add(\"Ruby\"); list1.Add(\"Perl\"); int range = 4; Console.WriteLine(\"Original List\"); // Display Original List Display(list1); // \"gg\" is the object GFG gg = new GFG(); Console.WriteLine(\"\\nSort a range with comparer:\"); // sort the list within a // range of index 1 to 4 // where range = 4 list1.Sort(1, range, gg); // Display sorted List Display(list1); Console.WriteLine(\"\\nBinarySearch and Insert Dart\"); // Binary Search and storing // index value to \"index\" int index = list1.BinarySearch(0, range, \"Dart\", gg); if (index < 0) { list1.Insert(~index, \"Dart\"); range++; } // Display the List // after inserting \"Dart\" Display(list1); } // Display function public static void Display(List<string> list) { foreach(string g in list) { Console.WriteLine(g); } }}", "e": 6824, "s": 4989, "text": null }, { "code": null, "e": 7032, "s": 6824, "text": "Original List\nC++\nJava\nC\nPython\nHTML\nCSS\nScala\nRuby\nPerl\n\nSort a range with comparer:\nC++\nC\nHTML\nJava\nPython\nCSS\nScala\nRuby\nPerl\n\nBinarySearch and Insert Dart\nC++\nC\nDart\nHTML\nJava\nPython\nCSS\nScala\nRuby\nPerl\n" }, { "code": null, "e": 7043, "s": 7032, "text": "Reference:" }, { "code": null, "e": 7150, "s": 7043, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=netframework-4.7.2" }, { "code": null, "e": 7170, "s": 7150, "text": "CSharp-Generic-List" }, { "code": null, "e": 7195, "s": 7170, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 7209, "s": 7195, "text": "CSharp-method" }, { "code": null, "e": 7216, "s": 7209, "text": "Picked" }, { "code": null, "e": 7219, "s": 7216, "text": "C#" } ]
Python program to Sort a List of Strings by the Number of Unique Characters
01 Oct, 2020 Given a list of strings. The task is to sort the list of strings by the number of unique characters. Examples: Input : test_list = [‘gfg’, ‘best’, ‘for’, ‘geeks’], Output : [‘gfg’, ‘for’, ‘best’, ‘geeks’] Explanation : 2, 3, 4, 4 are unique elements in lists. Input : test_list = [‘gfg’, ‘for’, ‘geeks’], Output : [‘gfg’, ‘for’, ‘geeks’] Explanation : 2, 3, 4 are unique elements in lists. Method #1 : Using sort() + len() + set() In this, we perform task of sorting using sort(), and len and sort functions are used to get length of unique characters in string. Python3 # Python3 code to demonstrate working of # Sort Strings by Unique characters# Using sort() + len() + set() # helper functiondef hlper_fnc(ele): # getting Unique elements count return len(list(set(ele))) # initializing listtest_list = ['gfg', 'best', 'for', 'geeks'] # printing original listprint("The original list is : " + str(test_list)) # perform sorttest_list.sort(key = hlper_fnc) # printing result print("Sorted List : " + str(test_list)) The original list is : ['gfg', 'best', 'for', 'geeks'] Sorted List : ['gfg', 'for', 'best', 'geeks'] Method #2 : Using sorted() + len() + set() + lambda Similar to above method, difference being not inplace sort, and also uses lambda function for performing task. Python3 # Python3 code to demonstrate working of # Sort Strings by Unique characters# Using sorted() + len() + set() + lambda # initializing listtest_list = ['gfg', 'best', 'for', 'geeks'] # printing original listprint("The original list is : " + str(test_list)) # perform sortres = sorted(test_list, key = lambda sub : len(list(set(sub)))) # printing result print("Sorted List : " + str(res)) The original list is : ['gfg', 'best', 'for', 'geeks'] Sorted List : ['gfg', 'for', 'best', 'geeks'] Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 129, "s": 28, "text": "Given a list of strings. The task is to sort the list of strings by the number of unique characters." }, { "code": null, "e": 139, "s": 129, "text": "Examples:" }, { "code": null, "e": 288, "s": 139, "text": "Input : test_list = [‘gfg’, ‘best’, ‘for’, ‘geeks’], Output : [‘gfg’, ‘for’, ‘best’, ‘geeks’] Explanation : 2, 3, 4, 4 are unique elements in lists." }, { "code": null, "e": 419, "s": 288, "text": "Input : test_list = [‘gfg’, ‘for’, ‘geeks’], Output : [‘gfg’, ‘for’, ‘geeks’] Explanation : 2, 3, 4 are unique elements in lists. " }, { "code": null, "e": 460, "s": 419, "text": "Method #1 : Using sort() + len() + set()" }, { "code": null, "e": 592, "s": 460, "text": "In this, we perform task of sorting using sort(), and len and sort functions are used to get length of unique characters in string." }, { "code": null, "e": 600, "s": 592, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sort Strings by Unique characters# Using sort() + len() + set() # helper functiondef hlper_fnc(ele): # getting Unique elements count return len(list(set(ele))) # initializing listtest_list = ['gfg', 'best', 'for', 'geeks'] # printing original listprint(\"The original list is : \" + str(test_list)) # perform sorttest_list.sort(key = hlper_fnc) # printing result print(\"Sorted List : \" + str(test_list))", "e": 1067, "s": 600, "text": null }, { "code": null, "e": 1169, "s": 1067, "text": "The original list is : ['gfg', 'best', 'for', 'geeks']\nSorted List : ['gfg', 'for', 'best', 'geeks']\n" }, { "code": null, "e": 1221, "s": 1169, "text": "Method #2 : Using sorted() + len() + set() + lambda" }, { "code": null, "e": 1333, "s": 1221, "text": "Similar to above method, difference being not inplace sort, and also uses lambda function for performing task. " }, { "code": null, "e": 1341, "s": 1333, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sort Strings by Unique characters# Using sorted() + len() + set() + lambda # initializing listtest_list = ['gfg', 'best', 'for', 'geeks'] # printing original listprint(\"The original list is : \" + str(test_list)) # perform sortres = sorted(test_list, key = lambda sub : len(list(set(sub)))) # printing result print(\"Sorted List : \" + str(res))", "e": 1735, "s": 1341, "text": null }, { "code": null, "e": 1837, "s": 1735, "text": "The original list is : ['gfg', 'best', 'for', 'geeks']\nSorted List : ['gfg', 'for', 'best', 'geeks']\n" }, { "code": null, "e": 1858, "s": 1837, "text": "Python list-programs" }, { "code": null, "e": 1881, "s": 1858, "text": "Python string-programs" }, { "code": null, "e": 1888, "s": 1881, "text": "Python" }, { "code": null, "e": 1904, "s": 1888, "text": "Python Programs" } ]
Navigation Bars in Flask
26 May, 2022 Navigation across HTML pages is quite a common way to work across pages. The client-side navigation approach is commonly used in HTML. However, having custom server-end navigations can provide greater flexibilities as far as customizations are concerned. This article walks you through a way to integrate Server end navigation using Navbars in Flask. This module is used to build navigation bars in the flask application. Allows server end navigation from one page to another. Helps to define HTML classes and Navigation items from Python. To install this module type the below command in the terminal. pip install Flask-Navigation nav.Bar(name, items) : Initializing name of navigation class with items definition.nav.Item( label, url, args) : Assigns items or lists for each bar. Label name, its linked page URL and extra args like parameter and value of dictionary. After installation, the next step is to initialize the app context with Navigation(), and define the basic HTML to navigate. Navigation bars also need to be defined in the code using Bar(), with takes position and list of items are parameters of Navigation Bars. Each Item is input with its label, URL, and parameters passed in the URL. Step 1: Importing Libraries, adding app context and Initializing Navigation Class Object. Python3 from flask import Flask, render_templatefrom flask_navigation import Navigation app = Flask(__name__)nav = Navigation(app) Step 2: Adding Navigation Definition Python3 # initializing Navigationsnav.Bar('top', [ nav.Item('Home', 'index'), nav.Item('Gfg', 'gfg', {'page': 5}),]) Step 3: Adding flask Routes and run application. Python3 @app.route('/')def index(): return render_template('index.html') @app.route('/navpage')def navpage(): return render_template('navpage.html') @app.route('/gfg/<int:page>')def gfg(page): return render_template('gfg.html', page=page) if __name__ == '__main__': app.run() navpage.html In this, for loop is used to iterate to render all the items defined under the top bar, with their url and labels. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><ul> {% for item in nav.top %} <li class="{{ 'active' if item.is_active else '' }}"> <a href="{{ item.url }}">{{ item.label }}</a> </li> {% endfor %}</ul></body></html> index.html HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><b>Index page</b></body></html> gfg.html HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><b>GFG Page 5</b></body></html> While opening navpage.html, on click of each item, the page is navigated to the required URL as configured for navigation. Output: Explanation: In navpage.html, each item of navbar is iterated and rendered. Onclick, class is activated and anchor tag takes to the defined path, the linked pages. Flask Projects Python Flask Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2022" }, { "code": null, "e": 379, "s": 28, "text": "Navigation across HTML pages is quite a common way to work across pages. The client-side navigation approach is commonly used in HTML. However, having custom server-end navigations can provide greater flexibilities as far as customizations are concerned. This article walks you through a way to integrate Server end navigation using Navbars in Flask." }, { "code": null, "e": 450, "s": 379, "text": "This module is used to build navigation bars in the flask application." }, { "code": null, "e": 505, "s": 450, "text": "Allows server end navigation from one page to another." }, { "code": null, "e": 568, "s": 505, "text": "Helps to define HTML classes and Navigation items from Python." }, { "code": null, "e": 631, "s": 568, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 660, "s": 631, "text": "pip install Flask-Navigation" }, { "code": null, "e": 897, "s": 660, "text": "nav.Bar(name, items) : Initializing name of navigation class with items definition.nav.Item( label, url, args) : Assigns items or lists for each bar. Label name, its linked page URL and extra args like parameter and value of dictionary." }, { "code": null, "e": 1234, "s": 897, "text": "After installation, the next step is to initialize the app context with Navigation(), and define the basic HTML to navigate. Navigation bars also need to be defined in the code using Bar(), with takes position and list of items are parameters of Navigation Bars. Each Item is input with its label, URL, and parameters passed in the URL." }, { "code": null, "e": 1326, "s": 1234, "text": "Step 1: Importing Libraries, adding app context and Initializing Navigation Class Object. " }, { "code": null, "e": 1334, "s": 1326, "text": "Python3" }, { "code": "from flask import Flask, render_templatefrom flask_navigation import Navigation app = Flask(__name__)nav = Navigation(app)", "e": 1458, "s": 1334, "text": null }, { "code": null, "e": 1495, "s": 1458, "text": "Step 2: Adding Navigation Definition" }, { "code": null, "e": 1503, "s": 1495, "text": "Python3" }, { "code": "# initializing Navigationsnav.Bar('top', [ nav.Item('Home', 'index'), nav.Item('Gfg', 'gfg', {'page': 5}),])", "e": 1618, "s": 1503, "text": null }, { "code": null, "e": 1667, "s": 1618, "text": "Step 3: Adding flask Routes and run application." }, { "code": null, "e": 1675, "s": 1667, "text": "Python3" }, { "code": "@app.route('/')def index(): return render_template('index.html') @app.route('/navpage')def navpage(): return render_template('navpage.html') @app.route('/gfg/<int:page>')def gfg(page): return render_template('gfg.html', page=page) if __name__ == '__main__': app.run()", "e": 1964, "s": 1675, "text": null }, { "code": null, "e": 1977, "s": 1964, "text": "navpage.html" }, { "code": null, "e": 2092, "s": 1977, "text": "In this, for loop is used to iterate to render all the items defined under the top bar, with their url and labels." }, { "code": null, "e": 2097, "s": 2092, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Title</title></head><body><ul> {% for item in nav.top %} <li class=\"{{ 'active' if item.is_active else '' }}\"> <a href=\"{{ item.url }}\">{{ item.label }}</a> </li> {% endfor %}</ul></body></html>", "e": 2385, "s": 2097, "text": null }, { "code": null, "e": 2396, "s": 2385, "text": "index.html" }, { "code": null, "e": 2401, "s": 2396, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Title</title></head><body><b>Index page</b></body></html>", "e": 2533, "s": 2401, "text": null }, { "code": null, "e": 2542, "s": 2533, "text": "gfg.html" }, { "code": null, "e": 2547, "s": 2542, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Title</title></head><body><b>GFG Page 5</b></body></html>", "e": 2679, "s": 2547, "text": null }, { "code": null, "e": 2803, "s": 2679, "text": "While opening navpage.html, on click of each item, the page is navigated to the required URL as configured for navigation. " }, { "code": null, "e": 2811, "s": 2803, "text": "Output:" }, { "code": null, "e": 2824, "s": 2811, "text": "Explanation:" }, { "code": null, "e": 2975, "s": 2824, "text": "In navpage.html, each item of navbar is iterated and rendered. Onclick, class is activated and anchor tag takes to the defined path, the linked pages." }, { "code": null, "e": 2990, "s": 2975, "text": "Flask Projects" }, { "code": null, "e": 3003, "s": 2990, "text": "Python Flask" }, { "code": null, "e": 3010, "s": 3003, "text": "Python" } ]
Python – Create acronyms from words
21 Jun, 2022 Given a string, the task is to write a Python program to extract the acronym from that string. Examples: Input: Computer Science Engineering Output: CSE Input: geeks for geeks Output: GFG Input: Uttar pradesh Output: UP Approach 1: The following steps are required: Take input as a string. Add the first letter of string to output. Iterate over the full string and add every next letter to space to output. Change the output to uppercase(required acronym). Python3 # function to create acronymdef fxn(stng): # add first letter oupt = stng[0] # iterate over string for i in range(1, len(stng)): if stng[i-1] == ' ': # add letter next to space oupt += stng[i] # uppercase oupt oupt = oupt.upper() return oupt # input stringinpt1 = "Computer Science Engineering" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "geeks for geeks" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "Uttar pradesh" # output acronymprint(fxn(inpt1)) Output: CSE GFG UP Time Complexity: O(n) -> looping once through string of length n. Space Complexity: O(n) -> as space is required for storing individual characters of a string of length n. Approach 2: The following steps are required: Take input as a string. Split the words. Iterate over words and add the first letter to output. Change the output to uppercase(required acronym). Python3 # function to create acronymdef fxn(stng): # get all words lst = stng.split() oupt = "" # iterate over words for word in lst: # get first letter of each word oupt += word[0] # uppercase oupt oupt = oupt.upper() return oupt # input stringinpt1 = "Computer Science Engineering" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "geeks for geeks" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "Uttar pradesh" # output acronymprint(fxn(inpt1)) Output: CSE GFG UP Time Complexity: O(n) -> looping once through an array of length n. Space Complexity: O(n) -> as space is required for storing individual characters of a string and an array of length n. harshmaster07705 Python string-programs Python Python Programs 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 How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 149, "s": 54, "text": "Given a string, the task is to write a Python program to extract the acronym from that string." }, { "code": null, "e": 159, "s": 149, "text": "Examples:" }, { "code": null, "e": 195, "s": 159, "text": "Input: Computer Science Engineering" }, { "code": null, "e": 207, "s": 195, "text": "Output: CSE" }, { "code": null, "e": 230, "s": 207, "text": "Input: geeks for geeks" }, { "code": null, "e": 242, "s": 230, "text": "Output: GFG" }, { "code": null, "e": 263, "s": 242, "text": "Input: Uttar pradesh" }, { "code": null, "e": 274, "s": 263, "text": "Output: UP" }, { "code": null, "e": 286, "s": 274, "text": "Approach 1:" }, { "code": null, "e": 320, "s": 286, "text": "The following steps are required:" }, { "code": null, "e": 344, "s": 320, "text": "Take input as a string." }, { "code": null, "e": 386, "s": 344, "text": "Add the first letter of string to output." }, { "code": null, "e": 461, "s": 386, "text": "Iterate over the full string and add every next letter to space to output." }, { "code": null, "e": 511, "s": 461, "text": "Change the output to uppercase(required acronym)." }, { "code": null, "e": 519, "s": 511, "text": "Python3" }, { "code": "# function to create acronymdef fxn(stng): # add first letter oupt = stng[0] # iterate over string for i in range(1, len(stng)): if stng[i-1] == ' ': # add letter next to space oupt += stng[i] # uppercase oupt oupt = oupt.upper() return oupt # input stringinpt1 = \"Computer Science Engineering\" # output acronymprint(fxn(inpt1)) # input stringinpt1 = \"geeks for geeks\" # output acronymprint(fxn(inpt1)) # input stringinpt1 = \"Uttar pradesh\" # output acronymprint(fxn(inpt1))", "e": 1077, "s": 519, "text": null }, { "code": null, "e": 1085, "s": 1077, "text": "Output:" }, { "code": null, "e": 1096, "s": 1085, "text": "CSE\nGFG\nUP" }, { "code": null, "e": 1162, "s": 1096, "text": "Time Complexity: O(n) -> looping once through string of length n." }, { "code": null, "e": 1268, "s": 1162, "text": "Space Complexity: O(n) -> as space is required for storing individual characters of a string of length n." }, { "code": null, "e": 1280, "s": 1268, "text": "Approach 2:" }, { "code": null, "e": 1314, "s": 1280, "text": "The following steps are required:" }, { "code": null, "e": 1338, "s": 1314, "text": "Take input as a string." }, { "code": null, "e": 1355, "s": 1338, "text": "Split the words." }, { "code": null, "e": 1410, "s": 1355, "text": "Iterate over words and add the first letter to output." }, { "code": null, "e": 1460, "s": 1410, "text": "Change the output to uppercase(required acronym)." }, { "code": null, "e": 1468, "s": 1460, "text": "Python3" }, { "code": "# function to create acronymdef fxn(stng): # get all words lst = stng.split() oupt = \"\" # iterate over words for word in lst: # get first letter of each word oupt += word[0] # uppercase oupt oupt = oupt.upper() return oupt # input stringinpt1 = \"Computer Science Engineering\" # output acronymprint(fxn(inpt1)) # input stringinpt1 = \"geeks for geeks\" # output acronymprint(fxn(inpt1)) # input stringinpt1 = \"Uttar pradesh\" # output acronymprint(fxn(inpt1))", "e": 1987, "s": 1468, "text": null }, { "code": null, "e": 1995, "s": 1987, "text": "Output:" }, { "code": null, "e": 2006, "s": 1995, "text": "CSE\nGFG\nUP" }, { "code": null, "e": 2074, "s": 2006, "text": "Time Complexity: O(n) -> looping once through an array of length n." }, { "code": null, "e": 2193, "s": 2074, "text": "Space Complexity: O(n) -> as space is required for storing individual characters of a string and an array of length n." }, { "code": null, "e": 2210, "s": 2193, "text": "harshmaster07705" }, { "code": null, "e": 2233, "s": 2210, "text": "Python string-programs" }, { "code": null, "e": 2240, "s": 2233, "text": "Python" }, { "code": null, "e": 2256, "s": 2240, "text": "Python Programs" }, { "code": null, "e": 2354, "s": 2256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2372, "s": 2354, "text": "Python Dictionary" }, { "code": null, "e": 2414, "s": 2372, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2436, "s": 2414, "text": "Enumerate() in Python" }, { "code": null, "e": 2471, "s": 2436, "text": "Read a file line by line in Python" }, { "code": null, "e": 2503, "s": 2471, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2546, "s": 2503, "text": "Python program to convert a list to string" }, { "code": null, "e": 2568, "s": 2546, "text": "Defaultdict in Python" }, { "code": null, "e": 2607, "s": 2568, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2645, "s": 2607, "text": "Python | Convert a list to dictionary" } ]
Python | sympy.integrate() using limits
12 Jun, 2019 With the help of sympy.integrate(expression, limit) method, we can find the integration of mathematical expressions using limits in the form of variables by using sympy.integrate(expression, limit) method. Syntax : sympy.integrate(expression, reference variable, limit)Return : Return integration of mathematical expression. Example #1 : In this example we can see that by using sympy.integrate(expression, limits) method, we can find the integration of mathematical expression using limits with variables. Here we use symbols() method also to declare a variable as symbol. # import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = cos(x) print("Before Integration : {}".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, (x, -oo, oo)) print("After Integration : {}".format(intr)) Output : Before Integration : cos(x) After Integration : AccumBounds(-2, 2) Example #2 : # import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = tan(x) print("Before Integration : {}".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, (x, -1, 1)) print("After Integration : {}".format(intr)) Output : Before Integration : tan(x) After Integration : 0 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2019" }, { "code": null, "e": 234, "s": 28, "text": "With the help of sympy.integrate(expression, limit) method, we can find the integration of mathematical expressions using limits in the form of variables by using sympy.integrate(expression, limit) method." }, { "code": null, "e": 353, "s": 234, "text": "Syntax : sympy.integrate(expression, reference variable, limit)Return : Return integration of mathematical expression." }, { "code": null, "e": 366, "s": 353, "text": "Example #1 :" }, { "code": null, "e": 602, "s": 366, "text": "In this example we can see that by using sympy.integrate(expression, limits) method, we can find the integration of mathematical expression using limits with variables. Here we use symbols() method also to declare a variable as symbol." }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = cos(x) print(\"Before Integration : {}\".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, (x, -oo, oo)) print(\"After Integration : {}\".format(intr))", "e": 844, "s": 602, "text": null }, { "code": null, "e": 853, "s": 844, "text": "Output :" }, { "code": null, "e": 881, "s": 853, "text": "Before Integration : cos(x)" }, { "code": null, "e": 920, "s": 881, "text": "After Integration : AccumBounds(-2, 2)" }, { "code": null, "e": 934, "s": 920, "text": " Example #2 :" }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y')gfg_exp = tan(x) print(\"Before Integration : {}\".format(gfg_exp)) # Use sympy.integrate() methodintr = integrate(gfg_exp, (x, -1, 1)) print(\"After Integration : {}\".format(intr))", "e": 1174, "s": 934, "text": null }, { "code": null, "e": 1183, "s": 1174, "text": "Output :" }, { "code": null, "e": 1211, "s": 1183, "text": "Before Integration : tan(x)" }, { "code": null, "e": 1233, "s": 1211, "text": "After Integration : 0" }, { "code": null, "e": 1239, "s": 1233, "text": "SymPy" }, { "code": null, "e": 1246, "s": 1239, "text": "Python" } ]
GATE | GATE CS 2011 | Question 4
16 Mar, 2018 Consider different activities related to email: m1: Send an email from a mail client to a mail server m2: Download an email from mailbox server to a mail client m3: Checking email in a web browser Which is the application level protocol used in each activity?(A) m1: HTTP m2: SMTP m3: POP(B) m1: SMTP m2: FTP m3: HTTP(C) m1: SMTP m2: POP m3: HTTP(D) m1: POP m2: SMTP m3: IMAPAnswer: (C)Explanation: Simple Mail Transfer Protocol (SMTP) is typically used by user clients for sending mails.Post Office Protocol (POP) is used by clients for receiving mails.Checking mails in web browser is a simple HTTP process. Option (C) is correct. Quiz of this Question GATE-CS-2011 GATE-GATE CS 2011 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Mar, 2018" }, { "code": null, "e": 101, "s": 53, "text": "Consider different activities related to email:" }, { "code": null, "e": 250, "s": 101, "text": "m1: Send an email from a mail client to a mail server\nm2: Download an email from mailbox server to a mail client\nm3: Checking email in a web browser" }, { "code": null, "e": 663, "s": 250, "text": "Which is the application level protocol used in each activity?(A) m1: HTTP m2: SMTP m3: POP(B) m1: SMTP m2: FTP m3: HTTP(C) m1: SMTP m2: POP m3: HTTP(D) m1: POP m2: SMTP m3: IMAPAnswer: (C)Explanation: Simple Mail Transfer Protocol (SMTP) is typically used by user clients for sending mails.Post Office Protocol (POP) is used by clients for receiving mails.Checking mails in web browser is a simple HTTP process." }, { "code": null, "e": 686, "s": 663, "text": "Option (C) is correct." }, { "code": null, "e": 708, "s": 686, "text": "Quiz of this Question" }, { "code": null, "e": 721, "s": 708, "text": "GATE-CS-2011" }, { "code": null, "e": 739, "s": 721, "text": "GATE-GATE CS 2011" }, { "code": null, "e": 744, "s": 739, "text": "GATE" } ]
Find Median of List in Python
03 Oct, 2019 Sometimes, while working with Python list we can have a problem in which we need to find Median of list. This problem is quite common in the mathematical domains and generic calculations. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + "~" operatorThis task can be performed in brute force manner using the combination of above functionalities. In this, we sort the list and the by using the property of “~” operator to perform negation, we access the list from front and rear, performing the required computation required for finding median. # Python3 code to demonstrate working of# Median of list# Using loop + "~" operator # initializing listtest_list = [4, 5, 8, 9, 10, 17] # printing listprint("The original list : " + str(test_list)) # Median of list# Using loop + "~" operatortest_list.sort()mid = len(test_list) // 2res = (test_list[mid] + test_list[~mid]) / 2 # Printing resultprint("Median of list is : " + str(res)) The original list : [4, 5, 8, 9, 10, 17] Median of list is : 8.5 Method #2 : Using statistics.median()This is the most generic method to perform this task. In this we directly use inbuilt function to perform the median of the list. # Python3 code to demonstrate working of# Median of list# Using statistics.median()import statistics # initializing listtest_list = [4, 5, 8, 9, 10, 17] # printing listprint("The original list : " + str(test_list)) # Median of list# Using statistics.median()res = statistics.median(test_list) # Printing resultprint("Median of list is : " + str(res)) The original list : [4, 5, 8, 9, 10, 17] Median of list is : 8.5 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Oct, 2019" }, { "code": null, "e": 305, "s": 53, "text": "Sometimes, while working with Python list we can have a problem in which we need to find Median of list. This problem is quite common in the mathematical domains and generic calculations. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 637, "s": 305, "text": "Method #1 : Using loop + \"~\" operatorThis task can be performed in brute force manner using the combination of above functionalities. In this, we sort the list and the by using the property of “~” operator to perform negation, we access the list from front and rear, performing the required computation required for finding median." }, { "code": "# Python3 code to demonstrate working of# Median of list# Using loop + \"~\" operator # initializing listtest_list = [4, 5, 8, 9, 10, 17] # printing listprint(\"The original list : \" + str(test_list)) # Median of list# Using loop + \"~\" operatortest_list.sort()mid = len(test_list) // 2res = (test_list[mid] + test_list[~mid]) / 2 # Printing resultprint(\"Median of list is : \" + str(res))", "e": 1026, "s": 637, "text": null }, { "code": null, "e": 1094, "s": 1026, "text": " \nThe original list : [4, 5, 8, 9, 10, 17]\nMedian of list is : 8.5\n" }, { "code": null, "e": 1263, "s": 1096, "text": "Method #2 : Using statistics.median()This is the most generic method to perform this task. In this we directly use inbuilt function to perform the median of the list." }, { "code": "# Python3 code to demonstrate working of# Median of list# Using statistics.median()import statistics # initializing listtest_list = [4, 5, 8, 9, 10, 17] # printing listprint(\"The original list : \" + str(test_list)) # Median of list# Using statistics.median()res = statistics.median(test_list) # Printing resultprint(\"Median of list is : \" + str(res))", "e": 1618, "s": 1263, "text": null }, { "code": null, "e": 1686, "s": 1618, "text": " \nThe original list : [4, 5, 8, 9, 10, 17]\nMedian of list is : 8.5\n" }, { "code": null, "e": 1707, "s": 1686, "text": "Python list-programs" }, { "code": null, "e": 1714, "s": 1707, "text": "Python" }, { "code": null, "e": 1730, "s": 1714, "text": "Python Programs" } ]
How to read large text files in Python?
29 Dec, 2020 Python is an open-source dynamically typed and interpreted programming language. Reading and writing files are an integral part of programming. In Python, files are read by using the readlines() method. The readlines() method returns a list where each item of the list is a complete sentence in the file. This method is useful when the file size is small. Since readlines() method appends each line to the list and then returns the entire list it will be time-consuming if the file size is extremely large say in GB. Also, the list will consume a large chunk of the memory which can cause memory leakage if sufficient memory is unavailable. To avoid this problem, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates over the entire file and does not require any additional data structure for data storage, the memory consumed is less comparatively. Also, the iterator does not perform expensive operations like appending hence it is time-efficient as well. Files are iterable in Python hence it is advisable to use iterators. The following two programs demonstrate how large text files can be read using Python. Method 1: The first approach makes use of iterator to iterate over the file. In this technique, we use the fileinput module in Python. The input() method of fileinput module can be used to read files. The advantage of using this method over readlines() is fileinput.input() does not load the entire file into memory. Hence, there is no chance of memory leakage. The fileinput.input() method takes a list of filenames and if no parameter is passed it accepts input from the stdin. The method returns an iterator which returns individual lines from the text file being scanned. Code Implementation: Python3 # import moduleimport fileinputimport time #time at the start of program is notedstart = time.time() #keeps a track of number of lines in the filecount = 0for lines in fileinput.input(['sample.txt']): print(lines) count = count + 1 #time at the end of program execution is notedend = time.time() #total time taken to print the fileprint("Execution time in seconds: ",(end - start))print("No. of lines printed: ",count) Output: Explanation: The input() method returns an iterator which scans the entire file and prints each line. Method 2: The second approach also uses an iterator to read the file. The only difference is we will use iterator of a file object. The method used is open() wraps the entire file into a file object. Next, we use an iterator to get the lines in the file object. We open the file in a ‘with’ block as it automatically closes the file as soon as the entire block executes. As the with block completes the __exit__() method is called which releases any open resources. Code Implementation: Python3 import time start = time.time()count = 0with open("sample.txt") as file: for line in file: print(line) count = count + 1end = time.time()print("Execution time in seconds: ",(end-start))print("No of lines printed: ",count) Output: Explanation: The time required in this approach is comparatively less. This program can be written without the block as well but in that case, we must make sure to close the file resource explicitly. Python file-handling-programs python-file-handling Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 1134, "s": 28, "text": "Python is an open-source dynamically typed and interpreted programming language. Reading and writing files are an integral part of programming. In Python, files are read by using the readlines() method. The readlines() method returns a list where each item of the list is a complete sentence in the file. This method is useful when the file size is small. Since readlines() method appends each line to the list and then returns the entire list it will be time-consuming if the file size is extremely large say in GB. Also, the list will consume a large chunk of the memory which can cause memory leakage if sufficient memory is unavailable. To avoid this problem, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates over the entire file and does not require any additional data structure for data storage, the memory consumed is less comparatively. Also, the iterator does not perform expensive operations like appending hence it is time-efficient as well. Files are iterable in Python hence it is advisable to use iterators. " }, { "code": null, "e": 1220, "s": 1134, "text": "The following two programs demonstrate how large text files can be read using Python." }, { "code": null, "e": 1230, "s": 1220, "text": "Method 1:" }, { "code": null, "e": 1796, "s": 1230, "text": "The first approach makes use of iterator to iterate over the file. In this technique, we use the fileinput module in Python. The input() method of fileinput module can be used to read files. The advantage of using this method over readlines() is fileinput.input() does not load the entire file into memory. Hence, there is no chance of memory leakage. The fileinput.input() method takes a list of filenames and if no parameter is passed it accepts input from the stdin. The method returns an iterator which returns individual lines from the text file being scanned." }, { "code": null, "e": 1817, "s": 1796, "text": "Code Implementation:" }, { "code": null, "e": 1825, "s": 1817, "text": "Python3" }, { "code": "# import moduleimport fileinputimport time #time at the start of program is notedstart = time.time() #keeps a track of number of lines in the filecount = 0for lines in fileinput.input(['sample.txt']): print(lines) count = count + 1 #time at the end of program execution is notedend = time.time() #total time taken to print the fileprint(\"Execution time in seconds: \",(end - start))print(\"No. of lines printed: \",count)", "e": 2258, "s": 1825, "text": null }, { "code": null, "e": 2266, "s": 2258, "text": "Output:" }, { "code": null, "e": 2279, "s": 2266, "text": "Explanation:" }, { "code": null, "e": 2368, "s": 2279, "text": "The input() method returns an iterator which scans the entire file and prints each line." }, { "code": null, "e": 2378, "s": 2368, "text": "Method 2:" }, { "code": null, "e": 2834, "s": 2378, "text": "The second approach also uses an iterator to read the file. The only difference is we will use iterator of a file object. The method used is open() wraps the entire file into a file object. Next, we use an iterator to get the lines in the file object. We open the file in a ‘with’ block as it automatically closes the file as soon as the entire block executes. As the with block completes the __exit__() method is called which releases any open resources." }, { "code": null, "e": 2855, "s": 2834, "text": "Code Implementation:" }, { "code": null, "e": 2863, "s": 2855, "text": "Python3" }, { "code": "import time start = time.time()count = 0with open(\"sample.txt\") as file: for line in file: print(line) count = count + 1end = time.time()print(\"Execution time in seconds: \",(end-start))print(\"No of lines printed: \",count)", "e": 3102, "s": 2863, "text": null }, { "code": null, "e": 3110, "s": 3102, "text": "Output:" }, { "code": null, "e": 3123, "s": 3110, "text": "Explanation:" }, { "code": null, "e": 3310, "s": 3123, "text": "The time required in this approach is comparatively less. This program can be written without the block as well but in that case, we must make sure to close the file resource explicitly." }, { "code": null, "e": 3340, "s": 3310, "text": "Python file-handling-programs" }, { "code": null, "e": 3361, "s": 3340, "text": "python-file-handling" }, { "code": null, "e": 3385, "s": 3361, "text": "Technical Scripter 2020" }, { "code": null, "e": 3392, "s": 3385, "text": "Python" }, { "code": null, "e": 3411, "s": 3392, "text": "Technical Scripter" } ]
Sum of the first N Prime numbers
23 Mar, 2021 Given an integer ‘n’, the task is to find the sum of first ‘n’ prime numbers. First few prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, ...... Examples: Input: N = 4 Output: 17 2, 3, 5, 7 are first 4 prime numbers so their sum is equal to 17 Input: N = 40 Output: 3087 Approach: Create a sieve which will help us to identify if the number is prime or not in O(1) time. Run a loop starting from 1 until and unless we find n prime numbers. Add all the prime numbers and neglect those which are not prime. Then, display the sum of 1st N prime numbers. Below is the implementation of the above solution C++ Java Python 3 C# Javascript // C++ implementation of above solution#include <bits/stdc++.h>using namespace std;#define MAX 10000 // Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.bool prime[MAX + 1];void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // find the sum of 1st N prime numbersint solve(int n){ // count of prime numbers int count = 0, num = 1; // sum of prime numbers long long int sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return sum;} // Driver codeint main(){ // create the sieve SieveOfEratosthenes(); int n = 4; // find the value of 1st n prime numbers cout << "Sum of 1st N prime numbers are :" << solve(n); return 0;} // Java implementation of above solutionpublic class Improve { final static double MAX = 10000 ; // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. static boolean prime[] = new boolean [(int) (MAX + 1.0)] ; static void SieveOfEratosthenes() { for(int i = 0; i <= MAX; i++) prime[i] = true ; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } } // find the sum of 1st N prime numbers static int solve(int n) { // count of prime numbers int count = 0, num = 1; // sum of prime numbers long sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return (int) sum; } // Driver code public static void main(String args[]) { // create the sieve SieveOfEratosthenes(); int n = 4; // find the value of 1st n prime numbers System.out.println("Sum of 1st N prime numbers are :" + solve(n)); } // This Code is contributed by ANKITRAI1} # Python3 implementation of# above solutionMAX = 10000 # Create a boolean array "prime[0..n]"# and initialize all entries it as true.# A value in prime[i] will finally be# false if i is Not a prime, else true.prime = [True for i in range(MAX + 1)]def SieveOfEratosthenes(): prime[1] = False for p in range(2, MAX + 1): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Set all multiples of # p to non-prime i = p * 2 while(i <= MAX): prime[i] = False i = i + p # find the sum of 1st# N prime numbersdef solve( n): # count of prime numbers count = 0 num = 1 # sum of prime numbers total = 0 while (count < n): # if the number is prime add it if ( prime[num] ): total = total + num # increase the count count = count + 1 # get to next number num = num + 1 return total # Driver code# create the sieveSieveOfEratosthenes() n = 4 # find the value of 1st# n prime numbersprint("Sum of 1st N prime " + "numbers are :", solve(n)) # This code is contributed by ash264 //C# implementation of above solution using System; public class GFG{ static double MAX = 10000 ; // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. static bool []prime = new bool [(int)(MAX + 1.0)] ; static void SieveOfEratosthenes() { for(int i = 0; i <= MAX; i++) prime[i] = true ; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } } // find the sum of 1st N prime numbers static int solve(int n) { // count of prime numbers int count = 0, num = 1; // sum of prime numbers long sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return (int) sum; } // Driver code static public void Main (){ // create the sieve SieveOfEratosthenes(); int n = 4; // find the value of 1st n prime numbers Console.WriteLine("Sum of 1st N prime numbers are :" + solve(n)); }// This Code is contributed by ajit.} <script> // javascript implementation of above solution var MAX = 10000 ;// Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.var prime = Array.from({length: parseInt( (MAX + 1.0))}, (_, i) => false);function SieveOfEratosthenes(){ for(i = 0; i <= MAX; i++) prime[i] = true ; prime[1] = false; for (p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // find the sum of 1st N prime numbersfunction solve(n){ // count of prime numbers var count = 0, num = 1; // sum of prime numbers var sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return parseInt( sum);}// Driver code //create the sieveSieveOfEratosthenes(); var n = 4; // find the value of 1st n prime numbersdocument.write("Sum of 1st N prime numbers are :" + solve(n)); // This code is contributed by 29AjayKumar </script> Sum of 1st N prime numbers are :17 Note(For competitive programming): In a problem which contains a large number of queries, a vector can be used to store all the prime numbers in the range of 10^8, this will take extra O(N) space. We can also use prefix array to store the sum of first N prime numbers in the range of 10^8. ash264 ankthon jit_t 29AjayKumar Prime Number sieve Competitive Programming Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Mar, 2021" }, { "code": null, "e": 133, "s": 54, "text": "Given an integer ‘n’, the task is to find the sum of first ‘n’ prime numbers. " }, { "code": null, "e": 201, "s": 133, "text": "First few prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, ......" }, { "code": null, "e": 213, "s": 201, "text": "Examples: " }, { "code": null, "e": 330, "s": 213, "text": "Input: N = 4\nOutput: 17\n2, 3, 5, 7 are first 4 prime numbers so their sum is equal to 17\n\nInput: N = 40\nOutput: 3087" }, { "code": null, "e": 343, "s": 332, "text": "Approach: " }, { "code": null, "e": 433, "s": 343, "text": "Create a sieve which will help us to identify if the number is prime or not in O(1) time." }, { "code": null, "e": 502, "s": 433, "text": "Run a loop starting from 1 until and unless we find n prime numbers." }, { "code": null, "e": 567, "s": 502, "text": "Add all the prime numbers and neglect those which are not prime." }, { "code": null, "e": 613, "s": 567, "text": "Then, display the sum of 1st N prime numbers." }, { "code": null, "e": 665, "s": 613, "text": "Below is the implementation of the above solution " }, { "code": null, "e": 669, "s": 665, "text": "C++" }, { "code": null, "e": 674, "s": 669, "text": "Java" }, { "code": null, "e": 683, "s": 674, "text": "Python 3" }, { "code": null, "e": 686, "s": 683, "text": "C#" }, { "code": null, "e": 697, "s": 686, "text": "Javascript" }, { "code": "// C++ implementation of above solution#include <bits/stdc++.h>using namespace std;#define MAX 10000 // Create a boolean array \"prime[0..n]\" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.bool prime[MAX + 1];void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // find the sum of 1st N prime numbersint solve(int n){ // count of prime numbers int count = 0, num = 1; // sum of prime numbers long long int sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return sum;} // Driver codeint main(){ // create the sieve SieveOfEratosthenes(); int n = 4; // find the value of 1st n prime numbers cout << \"Sum of 1st N prime numbers are :\" << solve(n); return 0;}", "e": 1957, "s": 697, "text": null }, { "code": "// Java implementation of above solutionpublic class Improve { final static double MAX = 10000 ; // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. static boolean prime[] = new boolean [(int) (MAX + 1.0)] ; static void SieveOfEratosthenes() { for(int i = 0; i <= MAX; i++) prime[i] = true ; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } } // find the sum of 1st N prime numbers static int solve(int n) { // count of prime numbers int count = 0, num = 1; // sum of prime numbers long sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return (int) sum; } // Driver code public static void main(String args[]) { // create the sieve SieveOfEratosthenes(); int n = 4; // find the value of 1st n prime numbers System.out.println(\"Sum of 1st N prime numbers are :\" + solve(n)); } // This Code is contributed by ANKITRAI1}", "e": 3637, "s": 1957, "text": null }, { "code": "# Python3 implementation of# above solutionMAX = 10000 # Create a boolean array \"prime[0..n]\"# and initialize all entries it as true.# A value in prime[i] will finally be# false if i is Not a prime, else true.prime = [True for i in range(MAX + 1)]def SieveOfEratosthenes(): prime[1] = False for p in range(2, MAX + 1): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Set all multiples of # p to non-prime i = p * 2 while(i <= MAX): prime[i] = False i = i + p # find the sum of 1st# N prime numbersdef solve( n): # count of prime numbers count = 0 num = 1 # sum of prime numbers total = 0 while (count < n): # if the number is prime add it if ( prime[num] ): total = total + num # increase the count count = count + 1 # get to next number num = num + 1 return total # Driver code# create the sieveSieveOfEratosthenes() n = 4 # find the value of 1st# n prime numbersprint(\"Sum of 1st N prime \" + \"numbers are :\", solve(n)) # This code is contributed by ash264", "e": 4854, "s": 3637, "text": null }, { "code": "//C# implementation of above solution using System; public class GFG{ static double MAX = 10000 ; // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. static bool []prime = new bool [(int)(MAX + 1.0)] ; static void SieveOfEratosthenes() { for(int i = 0; i <= MAX; i++) prime[i] = true ; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } } // find the sum of 1st N prime numbers static int solve(int n) { // count of prime numbers int count = 0, num = 1; // sum of prime numbers long sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return (int) sum; } // Driver code static public void Main (){ // create the sieve SieveOfEratosthenes(); int n = 4; // find the value of 1st n prime numbers Console.WriteLine(\"Sum of 1st N prime numbers are :\" + solve(n)); }// This Code is contributed by ajit.}", "e": 6508, "s": 4854, "text": null }, { "code": "<script> // javascript implementation of above solution var MAX = 10000 ;// Create a boolean array \"prime[0..n]\" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.var prime = Array.from({length: parseInt( (MAX + 1.0))}, (_, i) => false);function SieveOfEratosthenes(){ for(i = 0; i <= MAX; i++) prime[i] = true ; prime[1] = false; for (p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Set all multiples of p to non-prime for (i = p * 2; i <= MAX; i += p) prime[i] = false; } }} // find the sum of 1st N prime numbersfunction solve(n){ // count of prime numbers var count = 0, num = 1; // sum of prime numbers var sum = 0; while (count < n) { // if the number is prime add it if (prime[num]) { sum += num; // increase the count count++; } // get to next number num++; } return parseInt( sum);}// Driver code //create the sieveSieveOfEratosthenes(); var n = 4; // find the value of 1st n prime numbersdocument.write(\"Sum of 1st N prime numbers are :\" + solve(n)); // This code is contributed by 29AjayKumar </script>", "e": 7848, "s": 6508, "text": null }, { "code": null, "e": 7883, "s": 7848, "text": "Sum of 1st N prime numbers are :17" }, { "code": null, "e": 8176, "s": 7885, "text": "Note(For competitive programming): In a problem which contains a large number of queries, a vector can be used to store all the prime numbers in the range of 10^8, this will take extra O(N) space. We can also use prefix array to store the sum of first N prime numbers in the range of 10^8. " }, { "code": null, "e": 8183, "s": 8176, "text": "ash264" }, { "code": null, "e": 8191, "s": 8183, "text": "ankthon" }, { "code": null, "e": 8197, "s": 8191, "text": "jit_t" }, { "code": null, "e": 8209, "s": 8197, "text": "29AjayKumar" }, { "code": null, "e": 8222, "s": 8209, "text": "Prime Number" }, { "code": null, "e": 8228, "s": 8222, "text": "sieve" }, { "code": null, "e": 8252, "s": 8228, "text": "Competitive Programming" }, { "code": null, "e": 8265, "s": 8252, "text": "Mathematical" }, { "code": null, "e": 8278, "s": 8265, "text": "Mathematical" }, { "code": null, "e": 8291, "s": 8278, "text": "Prime Number" }, { "code": null, "e": 8297, "s": 8291, "text": "sieve" } ]
How to iterate HashSet in Java?
15 Feb, 2022 HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. There are three simple ways to iterate over a HashSet, which is the following : Using IteratorWithout using Iterator (using for loop)Using for-each loop Using Iterator Without using Iterator (using for loop) Using for-each loop Method 1: Iterator method In this method, we iterate HashSet with the help of iterator. First, we make an iterator to iterate HashSet with the help of the iterator() method in Java. // Create a iterator of integer type to iterate HashSet Iterator<Integer> it = set.iterator(); And then iterate HashSet with the help of hasNext() and Next() method in Java. Where hasNext() method check whether HashSet has elements or not and, Next() method access the data of HashSet. Note: Use Next() method only one time after hasNext(). Example: Java // Java program to iterate the HashSet// using iterator import java.util.*; class GFG { public static void main(String[] args) { // Creating a new HashSet for iteration HashSet<Integer> set = new HashSet<>(); // Add data to HashMap set.add(10); set.add(20); // Duplicates not allowed in HashMap, so avoid by // HashMap set.add(10); set.add(50); // Duplicates not allowed in HashMap, so avoid by // HashMap set.add(50); // Create a iterator of type integer to iterate // HashSet Iterator<Integer> it = set.iterator(); System.out.println( "Iterate HashSet using iterator : "); // Iterate HashSet with the help of hasNext() and // next() method while (it.hasNext()) { // Print HashSet values System.out.print(it.next() + " "); } }} Iterate HashSet using iterator : 50 20 10 Method 2: Iterate using for loop In this method, we iterate HashSet using a simple for loop. Below is the implementation of this approach: Example: Java // Java program to iterate the HashSet// using for loop import java.util.*; class GFG { public static void main(String[] args) { // Creating a new HashSet for iteration HashSet<String> set = new HashSet<>(); // Add data to HashSet set.add("Hello"); set.add("geeks"); set.add("on"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add("geeks"); set.add("for"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add("geeks"); System.out.println( "Iterate HashSet using for loop : "); // Iterate throw a simple for loop for (String ele : set) { // Print HashSet data System.out.print(ele + " "); } }} Iterate HashSet using for loop : Hello geeks for on Method 3: Using forEach() method In this method, we iterate HashSet using forEach() loop in Java. Below is the implementation of this method: Example: Java // Java program to iterate using forEach() loop import java.util.*; class GFG { public static void main(String[] args) { // Creating a new HashSet for iteration HashSet<String> set = new HashSet<>(); // Add data to HashSet set.add("Hello"); set.add("geeks"); set.add("on"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add("geeks"); set.add("for"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add("geeks"); System.out.println( "Iterate HashSet using forEach loop : "); // Iterate throw a forEach method in Java set.forEach(System.out::println); }} Iterate HashSet using forEach loop : Hello geeks for on adnanirshad158 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2022" }, { "code": null, "e": 315, "s": 28, "text": "HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code." }, { "code": null, "e": 395, "s": 315, "text": "There are three simple ways to iterate over a HashSet, which is the following :" }, { "code": null, "e": 468, "s": 395, "text": "Using IteratorWithout using Iterator (using for loop)Using for-each loop" }, { "code": null, "e": 483, "s": 468, "text": "Using Iterator" }, { "code": null, "e": 523, "s": 483, "text": "Without using Iterator (using for loop)" }, { "code": null, "e": 543, "s": 523, "text": "Using for-each loop" }, { "code": null, "e": 569, "s": 543, "text": "Method 1: Iterator method" }, { "code": null, "e": 725, "s": 569, "text": "In this method, we iterate HashSet with the help of iterator. First, we make an iterator to iterate HashSet with the help of the iterator() method in Java." }, { "code": null, "e": 821, "s": 725, "text": "// Create a iterator of integer type to iterate HashSet\n\nIterator<Integer> it = set.iterator();" }, { "code": null, "e": 1012, "s": 821, "text": "And then iterate HashSet with the help of hasNext() and Next() method in Java. Where hasNext() method check whether HashSet has elements or not and, Next() method access the data of HashSet." }, { "code": null, "e": 1067, "s": 1012, "text": "Note: Use Next() method only one time after hasNext()." }, { "code": null, "e": 1076, "s": 1067, "text": "Example:" }, { "code": null, "e": 1081, "s": 1076, "text": "Java" }, { "code": "// Java program to iterate the HashSet// using iterator import java.util.*; class GFG { public static void main(String[] args) { // Creating a new HashSet for iteration HashSet<Integer> set = new HashSet<>(); // Add data to HashMap set.add(10); set.add(20); // Duplicates not allowed in HashMap, so avoid by // HashMap set.add(10); set.add(50); // Duplicates not allowed in HashMap, so avoid by // HashMap set.add(50); // Create a iterator of type integer to iterate // HashSet Iterator<Integer> it = set.iterator(); System.out.println( \"Iterate HashSet using iterator : \"); // Iterate HashSet with the help of hasNext() and // next() method while (it.hasNext()) { // Print HashSet values System.out.print(it.next() + \" \"); } }}", "e": 2008, "s": 1081, "text": null }, { "code": null, "e": 2051, "s": 2008, "text": "Iterate HashSet using iterator : \n50 20 10" }, { "code": null, "e": 2084, "s": 2051, "text": "Method 2: Iterate using for loop" }, { "code": null, "e": 2190, "s": 2084, "text": "In this method, we iterate HashSet using a simple for loop. Below is the implementation of this approach:" }, { "code": null, "e": 2199, "s": 2190, "text": "Example:" }, { "code": null, "e": 2204, "s": 2199, "text": "Java" }, { "code": "// Java program to iterate the HashSet// using for loop import java.util.*; class GFG { public static void main(String[] args) { // Creating a new HashSet for iteration HashSet<String> set = new HashSet<>(); // Add data to HashSet set.add(\"Hello\"); set.add(\"geeks\"); set.add(\"on\"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add(\"geeks\"); set.add(\"for\"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add(\"geeks\"); System.out.println( \"Iterate HashSet using for loop : \"); // Iterate throw a simple for loop for (String ele : set) { // Print HashSet data System.out.print(ele + \" \"); } }}", "e": 3011, "s": 2204, "text": null }, { "code": null, "e": 3064, "s": 3011, "text": "Iterate HashSet using for loop : \nHello geeks for on" }, { "code": null, "e": 3097, "s": 3064, "text": "Method 3: Using forEach() method" }, { "code": null, "e": 3206, "s": 3097, "text": "In this method, we iterate HashSet using forEach() loop in Java. Below is the implementation of this method:" }, { "code": null, "e": 3215, "s": 3206, "text": "Example:" }, { "code": null, "e": 3220, "s": 3215, "text": "Java" }, { "code": "// Java program to iterate using forEach() loop import java.util.*; class GFG { public static void main(String[] args) { // Creating a new HashSet for iteration HashSet<String> set = new HashSet<>(); // Add data to HashSet set.add(\"Hello\"); set.add(\"geeks\"); set.add(\"on\"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add(\"geeks\"); set.add(\"for\"); // duplicates not allowed in HashMap, so avoid by // HashMap set.add(\"geeks\"); System.out.println( \"Iterate HashSet using forEach loop : \"); // Iterate throw a forEach method in Java set.forEach(System.out::println); }}", "e": 3957, "s": 3220, "text": null }, { "code": null, "e": 4014, "s": 3957, "text": "Iterate HashSet using forEach loop : \nHello\ngeeks\nfor\non" }, { "code": null, "e": 4029, "s": 4014, "text": "adnanirshad158" }, { "code": null, "e": 4036, "s": 4029, "text": "Picked" }, { "code": null, "e": 4041, "s": 4036, "text": "Java" }, { "code": null, "e": 4055, "s": 4041, "text": "Java Programs" }, { "code": null, "e": 4060, "s": 4055, "text": "Java" } ]
Python | os.scandir() method - GeeksforGeeks
08 Aug, 2021 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality. The os.scandir() method in Python is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by the specified path. The entries are yielded in arbitrary order and special entries ‘.’ and ‘..’ are not included. Syntax: os.scandir(path = ‘.’)Parameter: path: A path-like object representing the file system path. This specify the directory to be scanned. If path is not specified then current working directory is used as path. A path-like object is a string or bytes object which represents a path.Return Type: This method returns an iterator of os.DirEntry objects corresponding to the entries in the given directory. Code: Use of os.scandir() method Python3 # Python program to explain os.scandir() method # importing os moduleimport os # Directory to be scannedpath = '/home/ihritik' # Scan the directory and get# an iterator of os.DirEntry objects# corresponding to entries in it# using os.scandir() methodobj = os.scandir(path) # List all files and directories# in the specified pathprint("Files and Directories in '% s':" % path)for entry in obj : if entry.is_dir() or entry.is_file(): print(entry.name) # entry.is_file() will check# if entry is a file or not and# entry.is_dir() method will# check if entry is a# directory or not. # To Close the iterator and# free acquired resources# use scandir.close() methodobj.close() # scandir.close() method is called automatically# when the iterator is exhausted# or garbage collected, or# when an error happens during iterating. Files and Directories in '/home': GeeksforGeeks Videos Downloads Pictures Documents sample.txt Public Desktop Images R Reference: https://docs.python.org/3/library/os.html#os.scandir sooda367 bassdropca python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24236, "s": 24208, "text": "\n08 Aug, 2021" }, { "code": null, "e": 24455, "s": 24236, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality." }, { "code": null, "e": 24615, "s": 24455, "text": "The os.scandir() method in Python is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by the specified path. " }, { "code": null, "e": 24711, "s": 24615, "text": "The entries are yielded in arbitrary order and special entries ‘.’ and ‘..’ are not included. " }, { "code": null, "e": 25121, "s": 24711, "text": "Syntax: os.scandir(path = ‘.’)Parameter: path: A path-like object representing the file system path. This specify the directory to be scanned. If path is not specified then current working directory is used as path. A path-like object is a string or bytes object which represents a path.Return Type: This method returns an iterator of os.DirEntry objects corresponding to the entries in the given directory. " }, { "code": null, "e": 25155, "s": 25121, "text": "Code: Use of os.scandir() method " }, { "code": null, "e": 25163, "s": 25155, "text": "Python3" }, { "code": "# Python program to explain os.scandir() method # importing os moduleimport os # Directory to be scannedpath = '/home/ihritik' # Scan the directory and get# an iterator of os.DirEntry objects# corresponding to entries in it# using os.scandir() methodobj = os.scandir(path) # List all files and directories# in the specified pathprint(\"Files and Directories in '% s':\" % path)for entry in obj : if entry.is_dir() or entry.is_file(): print(entry.name) # entry.is_file() will check# if entry is a file or not and# entry.is_dir() method will# check if entry is a# directory or not. # To Close the iterator and# free acquired resources# use scandir.close() methodobj.close() # scandir.close() method is called automatically# when the iterator is exhausted# or garbage collected, or# when an error happens during iterating.", "e": 25994, "s": 25163, "text": null }, { "code": null, "e": 26113, "s": 25994, "text": "Files and Directories in '/home':\nGeeksforGeeks\nVideos\nDownloads\nPictures\nDocuments\nsample.txt\nPublic\nDesktop\nImages\nR" }, { "code": null, "e": 26180, "s": 26115, "text": "Reference: https://docs.python.org/3/library/os.html#os.scandir " }, { "code": null, "e": 26189, "s": 26180, "text": "sooda367" }, { "code": null, "e": 26200, "s": 26189, "text": "bassdropca" }, { "code": null, "e": 26217, "s": 26200, "text": "python-os-module" }, { "code": null, "e": 26224, "s": 26217, "text": "Python" }, { "code": null, "e": 26322, "s": 26224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26340, "s": 26322, "text": "Python Dictionary" }, { "code": null, "e": 26375, "s": 26340, "text": "Read a file line by line in Python" }, { "code": null, "e": 26397, "s": 26375, "text": "Enumerate() in Python" }, { "code": null, "e": 26429, "s": 26397, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26459, "s": 26429, "text": "Iterate over a list in Python" }, { "code": null, "e": 26501, "s": 26459, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26527, "s": 26501, "text": "Python String | replace()" }, { "code": null, "e": 26564, "s": 26527, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26607, "s": 26564, "text": "Python program to convert a list to string" } ]
Powershell - Hashtables
Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys. This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods. To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an hashtable variable − $hash = @{ ID = 1; Shape = "Square"; Color = "Blue"} or $hash = @{} Note − Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are added whereas hashtables do not. The following code snippets are examples of this syntax − $hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"} Print the hashtable. $hash Name Value ---- ----- ID 1 Color Blue Shape Square The hashtable values are accessed through the keys. > $hash["ID"] 1 Dot notation can be used to access hashtables keys or values. > $hash.keys ID Color Shape > $hash.values 1 Blue Square Here is a complete example showing how to create, initialize, and process hashtable − $hash = @{ ID = 1; Shape = "Square"; Color = "Blue"} write-host("Print all hashtable keys") $hash.keys write-host("Print all hashtable values") $hash.values write-host("Get ID") $hash["ID"] write-host("Get Shape") $hash.Number write-host("print Size") $hash.Count write-host("Add key-value") $hash["Updated"] = "Now" write-host("Add key-value") $hash.Add("Created","Now") write-host("print Size") $hash.Count write-host("Remove key-value") $hash.Remove("Updated") write-host("print Size") $hash.Count write-host("sort by key") $hash.GetEnumerator() | Sort-Object -Property key This will produce the following result − Print all hashtable keys ID Color Shape Print all hashtable values 1 Blue Square Get ID 1 Get Shape print Size 3 Add key-value Add key-value print Size 5 Remove key-value print Size 4 sort by key Name Value ---- ----- Color Blue Created Now ID 1 Shape Square 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2246, "s": 2034, "text": "Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys." }, { "code": null, "e": 2367, "s": 2246, "text": "This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods." }, { "code": null, "e": 2514, "s": 2367, "text": "To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an hashtable variable −" }, { "code": null, "e": 2584, "s": 2514, "text": "$hash = @{ ID = 1; Shape = \"Square\"; Color = \"Blue\"}\nor\n$hash = @{} \n" }, { "code": null, "e": 2743, "s": 2584, "text": "Note − Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are added whereas hashtables do not." }, { "code": null, "e": 2801, "s": 2743, "text": "The following code snippets are examples of this syntax −" }, { "code": null, "e": 2863, "s": 2801, "text": "$hash = [ordered]@{ ID = 1; Shape = \"Square\"; Color = \"Blue\"}" }, { "code": null, "e": 2884, "s": 2863, "text": "Print the hashtable." }, { "code": null, "e": 2890, "s": 2884, "text": "$hash" }, { "code": null, "e": 3238, "s": 2890, "text": "Name Value \n---- ----- \nID 1 \nColor Blue \nShape Square \n" }, { "code": null, "e": 3290, "s": 3238, "text": "The hashtable values are accessed through the keys." }, { "code": null, "e": 3307, "s": 3290, "text": "> $hash[\"ID\"]\n 1" }, { "code": null, "e": 3369, "s": 3307, "text": "Dot notation can be used to access hashtables keys or values." }, { "code": null, "e": 3427, "s": 3369, "text": "> $hash.keys\nID\nColor\nShape\n\n> $hash.values\n1\nBlue\nSquare" }, { "code": null, "e": 3513, "s": 3427, "text": "Here is a complete example showing how to create, initialize, and process hashtable −" }, { "code": null, "e": 4101, "s": 3513, "text": "$hash = @{ ID = 1; Shape = \"Square\"; Color = \"Blue\"}\n\nwrite-host(\"Print all hashtable keys\")\n$hash.keys\n\nwrite-host(\"Print all hashtable values\")\n$hash.values\n\nwrite-host(\"Get ID\")\n$hash[\"ID\"]\n\nwrite-host(\"Get Shape\")\n$hash.Number\n\nwrite-host(\"print Size\")\n$hash.Count\n\nwrite-host(\"Add key-value\")\n$hash[\"Updated\"] = \"Now\"\n\nwrite-host(\"Add key-value\")\n$hash.Add(\"Created\",\"Now\")\n\nwrite-host(\"print Size\")\n$hash.Count\n\nwrite-host(\"Remove key-value\")\n$hash.Remove(\"Updated\")\n\nwrite-host(\"print Size\")\n$hash.Count\n\nwrite-host(\"sort by key\")\n$hash.GetEnumerator() | Sort-Object -Property key" }, { "code": null, "e": 4142, "s": 4101, "text": "This will produce the following result −" }, { "code": null, "e": 5063, "s": 4142, "text": "Print all hashtable keys\nID\nColor\nShape\nPrint all hashtable values\n1\nBlue\nSquare\nGet ID\n1\nGet Shape\nprint Size\n3\nAdd key-value\nAdd key-value\nprint Size\n5\nRemove key-value\nprint Size\n4\nsort by key\n\nName Value \n---- ----- \nColor Blue \nCreated Now \nID 1 \nShape \nSquare \n" }, { "code": null, "e": 5098, "s": 5063, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5119, "s": 5098, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 5154, "s": 5119, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5167, "s": 5154, "text": " Vijay Saini" }, { "code": null, "e": 5204, "s": 5167, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 5216, "s": 5204, "text": " Fettah Ben" }, { "code": null, "e": 5223, "s": 5216, "text": " Print" }, { "code": null, "e": 5234, "s": 5223, "text": " Add Notes" } ]
How to bind to port number less than 1024 with non root access? - GeeksforGeeks
26 Sep, 2017 Why are the first 1024 ports restricted to the root user only? Binding is an integral step for server side socket. It’s like providing some address to end-user (server). So, we assign an IP address and a port number for running a server. But we can not provide any random port number to a server. The port numbers from 1 to 1023 are restricted for root user only and we can not assign those ports without having root access. The reason behind this restriction is that most major network services like HTTP, FTP, SSH, Telnet, POP etc. runs in this range. So, if any one is allowed to run on those port, following circumstances may arise : An untrusted user could run a program that listened on these ports for login (access) details. An untrusted user could run an unauthorized server application. Below program verifies the fact that port numbers from 1 to 1023 are restricted for root access. We use bind() function which returns 0 on success and -1 on failure. We call bind in a loop for different port numbers until it returns 0. // Server side C program to demonstrate// that we can not assign port number less// than 1024 without root access#include<stdio.h>#include<arpa/inet.h> int main(){ int server = socket(AF_INET, SOCK_STREAM, 0); if (server < 0) printf("Error in server creating\n"); else printf("Server Created\n"); struct sockaddr_in my_addr, peer_addr; my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; my_addr.sin_addr.s_addr = inet_addr("10.32.40.213"); int b = 1, i = 0; while (b) { i++; // Assigning every port number starting // from one to check // if it is able to bind properly or not my_addr.sin_port = htons(i); // On correct binding, it return 0 // and so 0 in b will terminate loop b = bind(server, (struct sockaddr*) &my_addr, sizeof(my_addr)); } printf("Binded Correctly on port number %d\n", i);} Output: Server Created Binded Correctly on port number 1024 How to allow non root access to bind below port number 1024? But there are two method by which we can assign port number less than 1024 without having root privilege : Method 1 : Using CAP_NET_BIND_SERVICE to grant low-numbered port access to a process :For this, we just need to run following command in terminal :sudo setcap CAP_NET_BIND_SERVICE=+eip /path/to/binaryMethod 2 : Using authbind to grant one-time access, with finer user/group/port control. Let we have to assign port number 80. For this, following steps required :Install authbind using any package managerRun following two commands one by one in terminal :sudo touch /etc/authbind/byport/80 sudo chmod 777 /etc/authbind/byport/80Here, 80 is given in end of command as we are attempting to assign port number 80.Now execute following command in terminalauthbind --deep /path/to/binary command line args Method 1 : Using CAP_NET_BIND_SERVICE to grant low-numbered port access to a process :For this, we just need to run following command in terminal :sudo setcap CAP_NET_BIND_SERVICE=+eip /path/to/binary sudo setcap CAP_NET_BIND_SERVICE=+eip /path/to/binary Method 2 : Using authbind to grant one-time access, with finer user/group/port control. Let we have to assign port number 80. For this, following steps required :Install authbind using any package managerRun following two commands one by one in terminal :sudo touch /etc/authbind/byport/80 sudo chmod 777 /etc/authbind/byport/80Here, 80 is given in end of command as we are attempting to assign port number 80.Now execute following command in terminalauthbind --deep /path/to/binary command line args Install authbind using any package manager Run following two commands one by one in terminal :sudo touch /etc/authbind/byport/80 sudo chmod 777 /etc/authbind/byport/80Here, 80 is given in end of command as we are attempting to assign port number 80. sudo touch /etc/authbind/byport/80 sudo chmod 777 /etc/authbind/byport/80 Here, 80 is given in end of command as we are attempting to assign port number 80. Now execute following command in terminalauthbind --deep /path/to/binary command line args authbind --deep /path/to/binary command line args This article is contributed by Aditya Kumar. 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. system-programming C Language Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples TCP Server-Client implementation in C
[ { "code": null, "e": 24232, "s": 24204, "text": "\n26 Sep, 2017" }, { "code": null, "e": 24295, "s": 24232, "text": "Why are the first 1024 ports restricted to the root user only?" }, { "code": null, "e": 24657, "s": 24295, "text": "Binding is an integral step for server side socket. It’s like providing some address to end-user (server). So, we assign an IP address and a port number for running a server. But we can not provide any random port number to a server. The port numbers from 1 to 1023 are restricted for root user only and we can not assign those ports without having root access." }, { "code": null, "e": 24870, "s": 24657, "text": "The reason behind this restriction is that most major network services like HTTP, FTP, SSH, Telnet, POP etc. runs in this range. So, if any one is allowed to run on those port, following circumstances may arise :" }, { "code": null, "e": 24965, "s": 24870, "text": "An untrusted user could run a program that listened on these ports for login (access) details." }, { "code": null, "e": 25029, "s": 24965, "text": "An untrusted user could run an unauthorized server application." }, { "code": null, "e": 25126, "s": 25029, "text": "Below program verifies the fact that port numbers from 1 to 1023 are restricted for root access." }, { "code": null, "e": 25265, "s": 25126, "text": "We use bind() function which returns 0 on success and -1 on failure. We call bind in a loop for different port numbers until it returns 0." }, { "code": "// Server side C program to demonstrate// that we can not assign port number less// than 1024 without root access#include<stdio.h>#include<arpa/inet.h> int main(){ int server = socket(AF_INET, SOCK_STREAM, 0); if (server < 0) printf(\"Error in server creating\\n\"); else printf(\"Server Created\\n\"); struct sockaddr_in my_addr, peer_addr; my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; my_addr.sin_addr.s_addr = inet_addr(\"10.32.40.213\"); int b = 1, i = 0; while (b) { i++; // Assigning every port number starting // from one to check // if it is able to bind properly or not my_addr.sin_port = htons(i); // On correct binding, it return 0 // and so 0 in b will terminate loop b = bind(server, (struct sockaddr*) &my_addr, sizeof(my_addr)); } printf(\"Binded Correctly on port number %d\\n\", i);}", "e": 26226, "s": 25265, "text": null }, { "code": null, "e": 26234, "s": 26226, "text": "Output:" }, { "code": null, "e": 26287, "s": 26234, "text": "Server Created\nBinded Correctly on port number 1024\n" }, { "code": null, "e": 26348, "s": 26287, "text": "How to allow non root access to bind below port number 1024?" }, { "code": null, "e": 26455, "s": 26348, "text": "But there are two method by which we can assign port number less than 1024 without having root privilege :" }, { "code": null, "e": 27156, "s": 26455, "text": "Method 1 : Using CAP_NET_BIND_SERVICE to grant low-numbered port access to a process :For this, we just need to run following command in terminal :sudo setcap CAP_NET_BIND_SERVICE=+eip /path/to/binaryMethod 2 : Using authbind to grant one-time access, with finer user/group/port control. Let we have to assign port number 80. For this, following steps required :Install authbind using any package managerRun following two commands one by one in terminal :sudo touch /etc/authbind/byport/80\nsudo chmod 777 /etc/authbind/byport/80Here, 80 is given in end of command as we are attempting to assign port number 80.Now execute following command in terminalauthbind --deep /path/to/binary command line args" }, { "code": null, "e": 27357, "s": 27156, "text": "Method 1 : Using CAP_NET_BIND_SERVICE to grant low-numbered port access to a process :For this, we just need to run following command in terminal :sudo setcap CAP_NET_BIND_SERVICE=+eip /path/to/binary" }, { "code": null, "e": 27411, "s": 27357, "text": "sudo setcap CAP_NET_BIND_SERVICE=+eip /path/to/binary" }, { "code": null, "e": 27912, "s": 27411, "text": "Method 2 : Using authbind to grant one-time access, with finer user/group/port control. Let we have to assign port number 80. For this, following steps required :Install authbind using any package managerRun following two commands one by one in terminal :sudo touch /etc/authbind/byport/80\nsudo chmod 777 /etc/authbind/byport/80Here, 80 is given in end of command as we are attempting to assign port number 80.Now execute following command in terminalauthbind --deep /path/to/binary command line args" }, { "code": null, "e": 27955, "s": 27912, "text": "Install authbind using any package manager" }, { "code": null, "e": 28162, "s": 27955, "text": "Run following two commands one by one in terminal :sudo touch /etc/authbind/byport/80\nsudo chmod 777 /etc/authbind/byport/80Here, 80 is given in end of command as we are attempting to assign port number 80." }, { "code": null, "e": 28236, "s": 28162, "text": "sudo touch /etc/authbind/byport/80\nsudo chmod 777 /etc/authbind/byport/80" }, { "code": null, "e": 28319, "s": 28236, "text": "Here, 80 is given in end of command as we are attempting to assign port number 80." }, { "code": null, "e": 28410, "s": 28319, "text": "Now execute following command in terminalauthbind --deep /path/to/binary command line args" }, { "code": null, "e": 28460, "s": 28410, "text": "authbind --deep /path/to/binary command line args" }, { "code": null, "e": 28760, "s": 28460, "text": "This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28885, "s": 28760, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28904, "s": 28885, "text": "system-programming" }, { "code": null, "e": 28915, "s": 28904, "text": "C Language" }, { "code": null, "e": 28926, "s": 28915, "text": "Linux-Unix" }, { "code": null, "e": 29024, "s": 28926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29033, "s": 29024, "text": "Comments" }, { "code": null, "e": 29046, "s": 29033, "text": "Old Comments" }, { "code": null, "e": 29084, "s": 29046, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 29110, "s": 29084, "text": "Exception Handling in C++" }, { "code": null, "e": 29130, "s": 29110, "text": "Multithreading in C" }, { "code": null, "e": 29152, "s": 29130, "text": "'this' pointer in C++" }, { "code": null, "e": 29190, "s": 29152, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 29230, "s": 29190, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 29270, "s": 29230, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 29297, "s": 29270, "text": "grep command in Unix/Linux" }, { "code": null, "e": 29332, "s": 29297, "text": "cut command in Linux with examples" } ]
Remove repeated digits in a given number - GeeksforGeeks
20 Jan, 2022 Given an integer, remove consecutive repeated digits from it.Examples: Input: x = 12224 Output: 124 Input: x = 124422 Output: 1242 Input: x = 11332 Output: 132 We need to process all digits of n and remove consecutive representations. We can go through all digits by repeatedly dividing n with 10 and taking n%10. C++ Java Python3 C# PHP Javascript // C++ program to remove repeated digits#include <iostream>using namespace std; long int removeRecur(long int n){ // Store first digits as previous digit int prev_digit = n % 10; // Initialize power long int pow = 10; long int res = prev_digit; // Iterate through all digits of n, note that // the digits are processed from least significant // digit to most significant digit. while (n) { // Store current digit int curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to the beginning // of result res += curr_digit * pow; // Update previous result and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = n / 10; } return res;} // Driver programint main(){ long int n = 12224; cout << removeRecur(n); return 0;} // Java program to remove repeated digitsimport java.io.*; class GFG { static long removeRecur(long n) { // Store first digits as previous // digit long prev_digit = n % 10; // Initialize power long pow = 10; long res = prev_digit; // Iterate through all digits of n, // note that the digits are // processed from least significant // digit to most significant digit. while (n>0) { // Store current digit long curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to // the beginning of result res += curr_digit * pow; // Update previous result // and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = n / 10; } return res; } // Driver program public static void main (String[] args) { long n = 12224; System.out.println(removeRecur(n)); }} // This code is contributed by anuj_67. # Python 3 program to remove repeated digits def removeRecur(n): # Store first digits as previous digit prev_digit = n % 10 # Initialize power pow = 10 res = prev_digit # Iterate through all digits of n, note # that the digits are processed from # least significant digit to most # significant digit. while (n): # Store current digit curr_digit = n % 10 if (curr_digit != prev_digit): # Add the current digit to the # beginning of result res += curr_digit * pow # Update previous result and power prev_digit = curr_digit pow *= 10 # Remove last digit from n n = int(n / 10) return res # Driver Codeif __name__ == '__main__': n = 12224 print(removeRecur(n)) # This code is contributed by# Surendra_Gangwar // C# program to remove repeated digitsusing System; class GFG { static long removeRecur(long n) { // Store first digits as previous // digit long prev_digit = n % 10; // Initialize power long pow = 10; long res = prev_digit; // Iterate through all digits of n, // note that the digits are // processed from least significant // digit to most significant digit. while (n > 0) { // Store current digit long curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to // the beginning of result res += curr_digit * pow; // Update previous result // and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = n / 10; } return res; } // Driver program public static void Main () { long n = 12224; Console.WriteLine(removeRecur(n)); }} // This code is contributed by anuj_67. <?php// PHP program to remove// repeated digits function removeRecur($n){ // Store first digits // as previous digit $prev_digit = $n % 10; // Initialize power $pow = 10; $res = $prev_digit; // Iterate through all digits // of n, note that the digits // are processed from least // significant digit to most // significant digit. while ($n) { // Store current digit $curr_digit = $n%10; if ($curr_digit != $prev_digit) { // Add the current digit // to the beginning of // result $res += $curr_digit * $pow; // Update previous result // and power $prev_digit = $curr_digit; $pow *= 10; } // Remove last digit // from n $n = $n / 10; } return $res;} // Driver Code $n = 12224; echo removeRecur($n); // This code is contributed by ajit.?> <script> // Javascript program to // remove repeated digits function removeRecur(n) { // Store first digits as previous // digit let prev_digit = n % 10; // Initialize power let pow = 10; let res = prev_digit; // Iterate through all digits of n, // note that the digits are // processed from least significant // digit to most significant digit. while (n > 0) { // Store current digit let curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to // the beginning of result res += curr_digit * pow; // Update previous result // and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = parseInt(n / 10, 10); } return res; } let n = 12224; document.write(removeRecur(n)); </script> Output: 124 Time Complexity: O(log10n) Auxiliary Space: O(1) This article is contributed by Kartik. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t vt_m SURENDRA_GANGWAR Akanksha_Rai divyeshrabadiya07 subham348 surinderdawra388 number-digits Mathematical Stack Strings Strings Mathematical Stack 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 Prime Numbers Program to find sum of elements in a given array Program for Decimal to Binary Conversion Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Program for Tower of Hanoi
[ { "code": null, "e": 24776, "s": 24748, "text": "\n20 Jan, 2022" }, { "code": null, "e": 24849, "s": 24776, "text": "Given an integer, remove consecutive repeated digits from it.Examples: " }, { "code": null, "e": 24940, "s": 24849, "text": "Input: x = 12224\nOutput: 124\n\nInput: x = 124422\nOutput: 1242\n\nInput: x = 11332\nOutput: 132" }, { "code": null, "e": 25096, "s": 24940, "text": "We need to process all digits of n and remove consecutive representations. We can go through all digits by repeatedly dividing n with 10 and taking n%10. " }, { "code": null, "e": 25100, "s": 25096, "text": "C++" }, { "code": null, "e": 25105, "s": 25100, "text": "Java" }, { "code": null, "e": 25113, "s": 25105, "text": "Python3" }, { "code": null, "e": 25116, "s": 25113, "text": "C#" }, { "code": null, "e": 25120, "s": 25116, "text": "PHP" }, { "code": null, "e": 25131, "s": 25120, "text": "Javascript" }, { "code": "// C++ program to remove repeated digits#include <iostream>using namespace std; long int removeRecur(long int n){ // Store first digits as previous digit int prev_digit = n % 10; // Initialize power long int pow = 10; long int res = prev_digit; // Iterate through all digits of n, note that // the digits are processed from least significant // digit to most significant digit. while (n) { // Store current digit int curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to the beginning // of result res += curr_digit * pow; // Update previous result and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = n / 10; } return res;} // Driver programint main(){ long int n = 12224; cout << removeRecur(n); return 0;}", "e": 26050, "s": 25131, "text": null }, { "code": "// Java program to remove repeated digitsimport java.io.*; class GFG { static long removeRecur(long n) { // Store first digits as previous // digit long prev_digit = n % 10; // Initialize power long pow = 10; long res = prev_digit; // Iterate through all digits of n, // note that the digits are // processed from least significant // digit to most significant digit. while (n>0) { // Store current digit long curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to // the beginning of result res += curr_digit * pow; // Update previous result // and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = n / 10; } return res; } // Driver program public static void main (String[] args) { long n = 12224; System.out.println(removeRecur(n)); }} // This code is contributed by anuj_67.", "e": 27256, "s": 26050, "text": null }, { "code": "# Python 3 program to remove repeated digits def removeRecur(n): # Store first digits as previous digit prev_digit = n % 10 # Initialize power pow = 10 res = prev_digit # Iterate through all digits of n, note # that the digits are processed from # least significant digit to most # significant digit. while (n): # Store current digit curr_digit = n % 10 if (curr_digit != prev_digit): # Add the current digit to the # beginning of result res += curr_digit * pow # Update previous result and power prev_digit = curr_digit pow *= 10 # Remove last digit from n n = int(n / 10) return res # Driver Codeif __name__ == '__main__': n = 12224 print(removeRecur(n)) # This code is contributed by# Surendra_Gangwar", "e": 28138, "s": 27256, "text": null }, { "code": "// C# program to remove repeated digitsusing System; class GFG { static long removeRecur(long n) { // Store first digits as previous // digit long prev_digit = n % 10; // Initialize power long pow = 10; long res = prev_digit; // Iterate through all digits of n, // note that the digits are // processed from least significant // digit to most significant digit. while (n > 0) { // Store current digit long curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to // the beginning of result res += curr_digit * pow; // Update previous result // and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = n / 10; } return res; } // Driver program public static void Main () { long n = 12224; Console.WriteLine(removeRecur(n)); }} // This code is contributed by anuj_67.", "e": 29326, "s": 28138, "text": null }, { "code": "<?php// PHP program to remove// repeated digits function removeRecur($n){ // Store first digits // as previous digit $prev_digit = $n % 10; // Initialize power $pow = 10; $res = $prev_digit; // Iterate through all digits // of n, note that the digits // are processed from least // significant digit to most // significant digit. while ($n) { // Store current digit $curr_digit = $n%10; if ($curr_digit != $prev_digit) { // Add the current digit // to the beginning of // result $res += $curr_digit * $pow; // Update previous result // and power $prev_digit = $curr_digit; $pow *= 10; } // Remove last digit // from n $n = $n / 10; } return $res;} // Driver Code $n = 12224; echo removeRecur($n); // This code is contributed by ajit.?>", "e": 30289, "s": 29326, "text": null }, { "code": "<script> // Javascript program to // remove repeated digits function removeRecur(n) { // Store first digits as previous // digit let prev_digit = n % 10; // Initialize power let pow = 10; let res = prev_digit; // Iterate through all digits of n, // note that the digits are // processed from least significant // digit to most significant digit. while (n > 0) { // Store current digit let curr_digit = n % 10; if (curr_digit != prev_digit) { // Add the current digit to // the beginning of result res += curr_digit * pow; // Update previous result // and power prev_digit = curr_digit; pow *= 10; } // Remove last digit from n n = parseInt(n / 10, 10); } return res; } let n = 12224; document.write(removeRecur(n)); </script>", "e": 31405, "s": 30289, "text": null }, { "code": null, "e": 31414, "s": 31405, "text": "Output: " }, { "code": null, "e": 31418, "s": 31414, "text": "124" }, { "code": null, "e": 31445, "s": 31418, "text": "Time Complexity: O(log10n)" }, { "code": null, "e": 31467, "s": 31445, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31631, "s": 31467, "text": "This article is contributed by Kartik. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 31637, "s": 31631, "text": "jit_t" }, { "code": null, "e": 31642, "s": 31637, "text": "vt_m" }, { "code": null, "e": 31659, "s": 31642, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 31672, "s": 31659, "text": "Akanksha_Rai" }, { "code": null, "e": 31690, "s": 31672, "text": "divyeshrabadiya07" }, { "code": null, "e": 31700, "s": 31690, "text": "subham348" }, { "code": null, "e": 31717, "s": 31700, "text": "surinderdawra388" }, { "code": null, "e": 31731, "s": 31717, "text": "number-digits" }, { "code": null, "e": 31744, "s": 31731, "text": "Mathematical" }, { "code": null, "e": 31750, "s": 31744, "text": "Stack" }, { "code": null, "e": 31758, "s": 31750, "text": "Strings" }, { "code": null, "e": 31766, "s": 31758, "text": "Strings" }, { "code": null, "e": 31779, "s": 31766, "text": "Mathematical" }, { "code": null, "e": 31785, "s": 31779, "text": "Stack" }, { "code": null, "e": 31883, "s": 31785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31907, "s": 31883, "text": "Merge two sorted arrays" }, { "code": null, "e": 31950, "s": 31907, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31964, "s": 31950, "text": "Prime Numbers" }, { "code": null, "e": 32013, "s": 31964, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32054, "s": 32013, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 32102, "s": 32054, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32122, "s": 32102, "text": "Stack Class in Java" }, { "code": null, "e": 32138, "s": 32122, "text": "Stack in Python" }, { "code": null, "e": 32213, "s": 32138, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Structure declaration in C language
The structure is a collection of different datatype variables, grouped together under a single name. It is a heterogeneous collection of data items that share a common name. It is possible to copy the contents of all structural elements of different data types to another structure variable of its type by using an assignment operator. It is possible to copy the contents of all structural elements of different data types to another structure variable of its type by using an assignment operator. To handle complex datatypes, it is possible to create a structure within another structure, which is called nested structures. To handle complex datatypes, it is possible to create a structure within another structure, which is called nested structures. It is possible to pass an entire structure, individual elements of structure, and address of structure to a function. It is possible to pass an entire structure, individual elements of structure, and address of structure to a function. It is possible to create structure pointers. It is possible to create structure pointers. The general form of structure declaration is as follows − datatype member1; struct tagname{ datatype member2; datatype member n; }; Here, struct is the keyword. struct is the keyword. tagname specifies the name of a structure tagname specifies the name of a structure member1, member2 specifies the data items that makeup structure. member1, member2 specifies the data items that makeup structure. For example, struct book{ int pages; char author [30]; float price; }; There are three ways of declaring structure variables, which are as follows − Type 1 struct book{ int pages; char author[30]; float price; }b; Type 2 struct{ int pages; char author[30]; float price; }b; Type 3 struct book{ int pages; char author[30]; float price; }; struct book b;
[ { "code": null, "e": 1236, "s": 1062, "text": "The structure is a collection of different datatype variables, grouped together under a single name. It is a heterogeneous collection of data items that share a common name." }, { "code": null, "e": 1398, "s": 1236, "text": "It is possible to copy the contents of all structural elements of different data types to another structure variable of its type by using an assignment operator." }, { "code": null, "e": 1560, "s": 1398, "text": "It is possible to copy the contents of all structural elements of different data types to another structure variable of its type by using an assignment operator." }, { "code": null, "e": 1687, "s": 1560, "text": "To handle complex datatypes, it is possible to create a structure within another structure, which is called nested structures." }, { "code": null, "e": 1814, "s": 1687, "text": "To handle complex datatypes, it is possible to create a structure within another structure, which is called nested structures." }, { "code": null, "e": 1932, "s": 1814, "text": "It is possible to pass an entire structure, individual elements of structure, and address of structure to a function." }, { "code": null, "e": 2050, "s": 1932, "text": "It is possible to pass an entire structure, individual elements of structure, and address of structure to a function." }, { "code": null, "e": 2095, "s": 2050, "text": "It is possible to create structure pointers." }, { "code": null, "e": 2140, "s": 2095, "text": "It is possible to create structure pointers." }, { "code": null, "e": 2198, "s": 2140, "text": "The general form of structure declaration is as follows −" }, { "code": null, "e": 2278, "s": 2198, "text": "datatype member1;\nstruct tagname{\n datatype member2;\n datatype member n;\n};" }, { "code": null, "e": 2284, "s": 2278, "text": "Here," }, { "code": null, "e": 2307, "s": 2284, "text": "struct is the keyword." }, { "code": null, "e": 2330, "s": 2307, "text": "struct is the keyword." }, { "code": null, "e": 2372, "s": 2330, "text": "tagname specifies the name of a structure" }, { "code": null, "e": 2414, "s": 2372, "text": "tagname specifies the name of a structure" }, { "code": null, "e": 2479, "s": 2414, "text": "member1, member2 specifies the data items that makeup structure." }, { "code": null, "e": 2544, "s": 2479, "text": "member1, member2 specifies the data items that makeup structure." }, { "code": null, "e": 2557, "s": 2544, "text": "For example," }, { "code": null, "e": 2624, "s": 2557, "text": "struct book{\n int pages;\n char author [30];\n float price;\n};" }, { "code": null, "e": 2702, "s": 2624, "text": "There are three ways of declaring structure variables, which are as follows −" }, { "code": null, "e": 2709, "s": 2702, "text": "Type 1" }, { "code": null, "e": 2776, "s": 2709, "text": "struct book{\n int pages;\n char author[30];\n float price;\n}b;" }, { "code": null, "e": 2783, "s": 2776, "text": "Type 2" }, { "code": null, "e": 2845, "s": 2783, "text": "struct{\n int pages;\n char author[30];\n float price;\n}b;" }, { "code": null, "e": 2852, "s": 2845, "text": "Type 3" }, { "code": null, "e": 2933, "s": 2852, "text": "struct book{\n int pages;\n char author[30];\n float price;\n};\nstruct book b;" } ]
Draw a Hut using turtle module in Python - GeeksforGeeks
30 Aug, 2021 Turtle is a inbuilt module in Python, which has many functions like forward(), backward(), right() and left() etc. You can draw a hut on the screen just by using the turtle module in Python. In this article, we will create a hut using the turtle module. Approach: Import turtleSet the background color.Define a function to draw the front portion of the hut i.e rectangle.Define a function to draw the top portion of the hut i.e equilateral triangle.Define a function to draw the side portion of the hut i.e Parallelogram.Use penup() and pendown() function to draw windows and door for the hut.Fill the appropriate colors in the Hut. Import turtle Set the background color. Define a function to draw the front portion of the hut i.e rectangle. Define a function to draw the top portion of the hut i.e equilateral triangle. Define a function to draw the side portion of the hut i.e Parallelogram. Use penup() and pendown() function to draw windows and door for the hut. Fill the appropriate colors in the Hut. Below is the implementation. Python3 import turtleimport math # Set the background colorscreen = turtle.Screen()screen.bgcolor("lightpink") # Create our turtlet = turtle.Turtle()t.color("black")t.shape("turtle")t.speed(5) # Define a function to draw and# fill a rectangle with the given# dimensions and colordef drawRectangle(t, width, height, color): t.fillcolor(color) t.begin_fill() t.forward(width) t.left(90) t.forward(height) t.left(90) t.forward(width) t.left(90) t.forward(height) t.left(90) t.end_fill() # Define a function to draw and fill an equalateral right# triangle with the given hypotenuse length and color. This# is used to create a roof shape.def drawTriangle(t, length, color): t.fillcolor(color) t.begin_fill() t.forward(length) t.left(135) t.forward(length / math.sqrt(2)) t.left(90) t.forward(length / math.sqrt(2)) t.left(135) t.end_fill() # Define a function to draw and fill a parallelogram, used to# draw the side of the housedef drawParallelogram(t, width, height, color): t.fillcolor(color) t.begin_fill() t.left(30) t.forward(width) t.left(60) t.forward(height) t.left(120) t.forward(width) t.left(60) t.forward(height) t.left(90) t.end_fill() # Draw and fill the front of the houset.penup()t.goto(-150, -120)t.pendown()drawRectangle(t, 100, 110, "blue") # Draw and fill the front doort.penup()t.goto(-120, -120)t.pendown()drawRectangle(t, 40, 60, "lightgreen") # Front rooft.penup()t.goto(-150, -10)t.pendown()drawTriangle(t, 100, "magenta") # Side of the houset.penup()t.goto(-50, -120)t.pendown()drawParallelogram(t, 60, 110, "yellow") # Windowt.penup()t.goto(-30, -60)t.pendown()drawParallelogram(t, 20, 30, "brown") # Side rooft.penup()t.goto(-50, -10)t.pendown()t.fillcolor("orange")t.begin_fill()t.left(30)t.forward(60)t.left(105)t.forward(100 / math.sqrt(2))t.left(75)t.forward(60)t.left(105)t.forward(100 / math.sqrt(2))t.left(45)t.end_fill()turtle.done() Output: anikakapoor Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n30 Aug, 2021" }, { "code": null, "e": 24572, "s": 24318, "text": "Turtle is a inbuilt module in Python, which has many functions like forward(), backward(), right() and left() etc. You can draw a hut on the screen just by using the turtle module in Python. In this article, we will create a hut using the turtle module." }, { "code": null, "e": 24582, "s": 24572, "text": "Approach:" }, { "code": null, "e": 24951, "s": 24582, "text": "Import turtleSet the background color.Define a function to draw the front portion of the hut i.e rectangle.Define a function to draw the top portion of the hut i.e equilateral triangle.Define a function to draw the side portion of the hut i.e Parallelogram.Use penup() and pendown() function to draw windows and door for the hut.Fill the appropriate colors in the Hut." }, { "code": null, "e": 24965, "s": 24951, "text": "Import turtle" }, { "code": null, "e": 24991, "s": 24965, "text": "Set the background color." }, { "code": null, "e": 25061, "s": 24991, "text": "Define a function to draw the front portion of the hut i.e rectangle." }, { "code": null, "e": 25140, "s": 25061, "text": "Define a function to draw the top portion of the hut i.e equilateral triangle." }, { "code": null, "e": 25213, "s": 25140, "text": "Define a function to draw the side portion of the hut i.e Parallelogram." }, { "code": null, "e": 25286, "s": 25213, "text": "Use penup() and pendown() function to draw windows and door for the hut." }, { "code": null, "e": 25326, "s": 25286, "text": "Fill the appropriate colors in the Hut." }, { "code": null, "e": 25355, "s": 25326, "text": "Below is the implementation." }, { "code": null, "e": 25363, "s": 25355, "text": "Python3" }, { "code": "import turtleimport math # Set the background colorscreen = turtle.Screen()screen.bgcolor(\"lightpink\") # Create our turtlet = turtle.Turtle()t.color(\"black\")t.shape(\"turtle\")t.speed(5) # Define a function to draw and# fill a rectangle with the given# dimensions and colordef drawRectangle(t, width, height, color): t.fillcolor(color) t.begin_fill() t.forward(width) t.left(90) t.forward(height) t.left(90) t.forward(width) t.left(90) t.forward(height) t.left(90) t.end_fill() # Define a function to draw and fill an equalateral right# triangle with the given hypotenuse length and color. This# is used to create a roof shape.def drawTriangle(t, length, color): t.fillcolor(color) t.begin_fill() t.forward(length) t.left(135) t.forward(length / math.sqrt(2)) t.left(90) t.forward(length / math.sqrt(2)) t.left(135) t.end_fill() # Define a function to draw and fill a parallelogram, used to# draw the side of the housedef drawParallelogram(t, width, height, color): t.fillcolor(color) t.begin_fill() t.left(30) t.forward(width) t.left(60) t.forward(height) t.left(120) t.forward(width) t.left(60) t.forward(height) t.left(90) t.end_fill() # Draw and fill the front of the houset.penup()t.goto(-150, -120)t.pendown()drawRectangle(t, 100, 110, \"blue\") # Draw and fill the front doort.penup()t.goto(-120, -120)t.pendown()drawRectangle(t, 40, 60, \"lightgreen\") # Front rooft.penup()t.goto(-150, -10)t.pendown()drawTriangle(t, 100, \"magenta\") # Side of the houset.penup()t.goto(-50, -120)t.pendown()drawParallelogram(t, 60, 110, \"yellow\") # Windowt.penup()t.goto(-30, -60)t.pendown()drawParallelogram(t, 20, 30, \"brown\") # Side rooft.penup()t.goto(-50, -10)t.pendown()t.fillcolor(\"orange\")t.begin_fill()t.left(30)t.forward(60)t.left(105)t.forward(100 / math.sqrt(2))t.left(75)t.forward(60)t.left(105)t.forward(100 / math.sqrt(2))t.left(45)t.end_fill()turtle.done()", "e": 27324, "s": 25363, "text": null }, { "code": null, "e": 27332, "s": 27324, "text": "Output:" }, { "code": null, "e": 27344, "s": 27332, "text": "anikakapoor" }, { "code": null, "e": 27358, "s": 27344, "text": "Python-turtle" }, { "code": null, "e": 27365, "s": 27358, "text": "Python" }, { "code": null, "e": 27463, "s": 27365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27495, "s": 27463, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27551, "s": 27495, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27593, "s": 27551, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27635, "s": 27593, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27657, "s": 27635, "text": "Defaultdict in Python" }, { "code": null, "e": 27688, "s": 27657, "text": "Python | os.path.join() method" }, { "code": null, "e": 27727, "s": 27688, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27782, "s": 27727, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27811, "s": 27782, "text": "Create a directory in Python" } ]
CSS Flexbox and Its Properties - GeeksforGeeks
03 Dec, 2020 Before we dive in to CSS Flexbox, let us learn about Pre Flexbox Pre Flexbox: A recap of some properties in CSS which might be related to learning Flexbox. We have different positional properties such as ‘absolute’ and ‘relative’ depending on how we want to place our elements in our page. Floats, grids, clear fixes to help aid in the positioning. Fixed heights for columns (one of the main elements to create flexboxes). What exactly is a flexbox? Flexbox is a CSS display type design to help us craft CSS layouts quite easily. Control the position, size and spacing of elements relative to their parents elements and each other. They are great for responsive designing. It has its own set of properties. It defines formatting context, which controls layout. It is a parent-child relationship. Note: Not all browsers support the flexbox properties, so make sure that the browser you are using supports this property. Basics of Flexbox:Apply a display type of flexbox to the parent container, this would make all the child elements in it to adjust into the flex type and these would be called the “flex items”. This means they have become more flexible i.e. we can control how much they can shrink and how much they can grow and also the spacing between these elements. display: flex property: The flex container can change the width, height and order of the child elements. Items can grow or shrink to fill the available space or to prevent overflow. Available space is distributed among other items. Axes of flexbox: The main axis: A) left to right flex-direction: row B) right to left flex-direction: row-reverse C) top to bottom flex-direction: column D) bottom to top flex-direction: column The cross axis (perpendicular to main axis) Properties of flexbox: Parent properties: display defines a flex container – flex formatting context. flex-direction defines the main axis inside the container. flex-wrap allows flex items to wrap onto more than one line. flex-flow shorthand for flex-direction + flex-wrap. justify-content allows items to align along main axis. align-content allows items to align along cross axis in a single line. align-items aligns multiple lines of items on the cross axis. Parent properties: order allows the change of order of items without altering the source order. flex-grow allows an item to fill up the available free space. flex-shrink allows an item to shrink if there is no enough free space available. flex-basis defines the size of an item before space is distributed. flex is the shorthand for flex-grow + flex-shrink + flex-basis. flex-self has the ability to align one single item within the flex container. Example: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> body { display: flex; align-items: center; justify-content: center; color: green; font-size: 50; } h2 { margin: 10px; } </style> </head> <body> <h2>GeeksforGeeks</h2></body> </html> Before applying flex properties: After applying flex properties: Yes, only this much code in CSS can make such a huge difference using flex-box. Benefits of a flexbox: Navigation bars and menus Grid Layouts Bar charts Equal height columns Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n03 Dec, 2020" }, { "code": null, "e": 25441, "s": 25376, "text": "Before we dive in to CSS Flexbox, let us learn about Pre Flexbox" }, { "code": null, "e": 25532, "s": 25441, "text": "Pre Flexbox: A recap of some properties in CSS which might be related to learning Flexbox." }, { "code": null, "e": 25666, "s": 25532, "text": "We have different positional properties such as ‘absolute’ and ‘relative’ depending on how we want to place our elements in our page." }, { "code": null, "e": 25725, "s": 25666, "text": "Floats, grids, clear fixes to help aid in the positioning." }, { "code": null, "e": 25799, "s": 25725, "text": "Fixed heights for columns (one of the main elements to create flexboxes)." }, { "code": null, "e": 25826, "s": 25799, "text": "What exactly is a flexbox?" }, { "code": null, "e": 25906, "s": 25826, "text": "Flexbox is a CSS display type design to help us craft CSS layouts quite easily." }, { "code": null, "e": 26008, "s": 25906, "text": "Control the position, size and spacing of elements relative to their parents elements and each other." }, { "code": null, "e": 26049, "s": 26008, "text": "They are great for responsive designing." }, { "code": null, "e": 26083, "s": 26049, "text": "It has its own set of properties." }, { "code": null, "e": 26137, "s": 26083, "text": "It defines formatting context, which controls layout." }, { "code": null, "e": 26172, "s": 26137, "text": "It is a parent-child relationship." }, { "code": null, "e": 26295, "s": 26172, "text": "Note: Not all browsers support the flexbox properties, so make sure that the browser you are using supports this property." }, { "code": null, "e": 26647, "s": 26295, "text": "Basics of Flexbox:Apply a display type of flexbox to the parent container, this would make all the child elements in it to adjust into the flex type and these would be called the “flex items”. This means they have become more flexible i.e. we can control how much they can shrink and how much they can grow and also the spacing between these elements." }, { "code": null, "e": 26671, "s": 26647, "text": "display: flex property:" }, { "code": null, "e": 26752, "s": 26671, "text": "The flex container can change the width, height and order of the child elements." }, { "code": null, "e": 26829, "s": 26752, "text": "Items can grow or shrink to fill the available space or to prevent overflow." }, { "code": null, "e": 26879, "s": 26829, "text": "Available space is distributed among other items." }, { "code": null, "e": 26896, "s": 26879, "text": "Axes of flexbox:" }, { "code": null, "e": 26911, "s": 26896, "text": "The main axis:" }, { "code": null, "e": 26942, "s": 26911, "text": " A) left to right" }, { "code": null, "e": 26968, "s": 26942, "text": " flex-direction: row" }, { "code": null, "e": 26999, "s": 26968, "text": " B) right to left" }, { "code": null, "e": 27033, "s": 26999, "text": " flex-direction: row-reverse" }, { "code": null, "e": 27064, "s": 27033, "text": " C) top to bottom" }, { "code": null, "e": 27095, "s": 27064, "text": " flex-direction: column" }, { "code": null, "e": 27126, "s": 27095, "text": " D) bottom to top" }, { "code": null, "e": 27157, "s": 27126, "text": " flex-direction: column" }, { "code": null, "e": 27201, "s": 27157, "text": "The cross axis (perpendicular to main axis)" }, { "code": null, "e": 27224, "s": 27201, "text": "Properties of flexbox:" }, { "code": null, "e": 27243, "s": 27224, "text": "Parent properties:" }, { "code": null, "e": 27303, "s": 27243, "text": "display defines a flex container – flex formatting context." }, { "code": null, "e": 27362, "s": 27303, "text": "flex-direction defines the main axis inside the container." }, { "code": null, "e": 27423, "s": 27362, "text": "flex-wrap allows flex items to wrap onto more than one line." }, { "code": null, "e": 27475, "s": 27423, "text": "flex-flow shorthand for flex-direction + flex-wrap." }, { "code": null, "e": 27530, "s": 27475, "text": "justify-content allows items to align along main axis." }, { "code": null, "e": 27601, "s": 27530, "text": "align-content allows items to align along cross axis in a single line." }, { "code": null, "e": 27663, "s": 27601, "text": "align-items aligns multiple lines of items on the cross axis." }, { "code": null, "e": 27682, "s": 27663, "text": "Parent properties:" }, { "code": null, "e": 27759, "s": 27682, "text": "order allows the change of order of items without altering the source order." }, { "code": null, "e": 27821, "s": 27759, "text": "flex-grow allows an item to fill up the available free space." }, { "code": null, "e": 27902, "s": 27821, "text": "flex-shrink allows an item to shrink if there is no enough free space available." }, { "code": null, "e": 27970, "s": 27902, "text": "flex-basis defines the size of an item before space is distributed." }, { "code": null, "e": 28034, "s": 27970, "text": "flex is the shorthand for flex-grow + flex-shrink + flex-basis." }, { "code": null, "e": 28112, "s": 28034, "text": "flex-self has the ability to align one single item within the flex container." }, { "code": null, "e": 28121, "s": 28112, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> body { display: flex; align-items: center; justify-content: center; color: green; font-size: 50; } h2 { margin: 10px; } </style> </head> <body> <h2>GeeksforGeeks</h2></body> </html>", "e": 28568, "s": 28121, "text": null }, { "code": null, "e": 28601, "s": 28568, "text": "Before applying flex properties:" }, { "code": null, "e": 28634, "s": 28601, "text": "After applying flex properties: " }, { "code": null, "e": 28714, "s": 28634, "text": "Yes, only this much code in CSS can make such a huge difference using flex-box." }, { "code": null, "e": 28737, "s": 28714, "text": "Benefits of a flexbox:" }, { "code": null, "e": 28763, "s": 28737, "text": "Navigation bars and menus" }, { "code": null, "e": 28776, "s": 28763, "text": "Grid Layouts" }, { "code": null, "e": 28787, "s": 28776, "text": "Bar charts" }, { "code": null, "e": 28808, "s": 28787, "text": "Equal height columns" }, { "code": null, "e": 28945, "s": 28808, "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": 28954, "s": 28945, "text": "CSS-Misc" }, { "code": null, "e": 28964, "s": 28954, "text": "HTML-Misc" }, { "code": null, "e": 28988, "s": 28964, "text": "Technical Scripter 2020" }, { "code": null, "e": 28992, "s": 28988, "text": "CSS" }, { "code": null, "e": 28997, "s": 28992, "text": "HTML" }, { "code": null, "e": 29016, "s": 28997, "text": "Technical Scripter" }, { "code": null, "e": 29033, "s": 29016, "text": "Web Technologies" }, { "code": null, "e": 29038, "s": 29033, "text": "HTML" }, { "code": null, "e": 29136, "s": 29038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29145, "s": 29136, "text": "Comments" }, { "code": null, "e": 29158, "s": 29145, "text": "Old Comments" }, { "code": null, "e": 29195, "s": 29158, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29224, "s": 29195, "text": "Form validation using jQuery" }, { "code": null, "e": 29263, "s": 29224, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29305, "s": 29263, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29340, "s": 29305, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29400, "s": 29340, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29461, "s": 29400, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29514, "s": 29461, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29564, "s": 29514, "text": "How to Insert Form Data into Database using PHP ?" } ]
iText - Adding a Table
In this chapter, we will see how to create a PDF document and add a table to it using the iText library. You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. Then, to add a table to the document, you need to instantiate the Table class and add this object to the document using the add() method. Following are the steps to create a PDF document with a Table in it. The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created. Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below. // Creating a PdfWriter String dest = "C:/itextExamples/addingTable.pdf"; PdfWriter writer = new PdfWriter(dest); When the object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified. The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor. Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below. // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class. The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument. Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below. // Creating a Document Document document = new Document(pdfDoc); The Table class represents a two-dimensional grid filled with cells ordered in rows and columns. It belongs to the package com.itextpdf.layout.element. Instantiate the Table class as shown below. // Creating a table object float [] pointColumnWidths = {150F, 150F, 150F}; Table table = new Table(pointColumnWidths); Create a cell object by instantiating the Cell class of the package com.itextpdf.layout.element. Add the contents of the cell using the add() method of this class. Finally, to add this cell to the table, call the addCell() method of the Table class and pass the cell object as a parameter to this method, as shown below. // Adding cell 1 to the table Cell cell1 = new Cell(); // Creating a cell cell1.add("Name"); // Adding content to the cell table.addCell(cell1); // Adding cell to the table // Adding cell 2 to the table Cell cell2 = new Cell(); // Creating a cell cell2.add("Raju"); // Adding content to the cell table.addCell(cell2); // Adding cell to the table Add the table object created in the previous step using the add() method of the Document class as shown below. // Adding list to the document document.add(table); Close the document using the close() method of the Document class, as shown below. // Closing the document document.close(); The following Java program demonstrates how to create a PDF document and add a table to it using the iText library. It creates a PDF document with the name addingTable.pdf, adds a table to it, and saves it in the path C:/itextExamples/ Save this code in a file with the name AddingTable.java. import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Table; public class AddingTable { public static void main(String args[]) throws Exception { // Creating a PdfDocument object String dest = "C:/itextExamples/addingTable.pdf"; PdfWriter writer = new PdfWriter(dest); // Creating a PdfDocument object PdfDocument pdf = new PdfDocument(writer); // Creating a Document object Document doc = new Document(pdf); // Creating a table float [] pointColumnWidths = {150F, 150F, 150F}; Table table = new Table(pointColumnWidths); // Adding cells to the table table.addCell(new Cell().add("Name")); table.addCell(new Cell().add("Raju")); table.addCell(new Cell().add("Id")); table.addCell(new Cell().add("1001")); table.addCell(new Cell().add("Designation")); table.addCell(new Cell().add("Programmer")); // Adding Table to document doc.add(table); // Closing the document doc.close(); System.out.println("Table created successfully.."); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac AddingTable.java java AddingTable Upon execution, the above program creates a PDF document, displaying the following message. Table created successfully.. If you verify the specified path, you can find the created PDF document, as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2473, "s": 2368, "text": "In this chapter, we will see how to create a PDF document and add a table to it using the iText library." }, { "code": null, "e": 2790, "s": 2473, "text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. Then, to add a table to the document, you need to instantiate the Table class and add this object to the document using the add() method." }, { "code": null, "e": 2859, "s": 2790, "text": "Following are the steps to create a PDF document with a Table in it." }, { "code": null, "e": 3088, "s": 2859, "text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created." }, { "code": null, "e": 3237, "s": 3088, "text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below." }, { "code": null, "e": 3354, "s": 3237, "text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/addingTable.pdf\"; \nPdfWriter writer = new PdfWriter(dest);\n" }, { "code": null, "e": 3495, "s": 3354, "text": "When the object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified." }, { "code": null, "e": 3747, "s": 3495, "text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor." }, { "code": null, "e": 3863, "s": 3747, "text": "Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below." }, { "code": null, "e": 3939, "s": 3863, "text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n" }, { "code": null, "e": 4110, "s": 3939, "text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class." }, { "code": null, "e": 4304, "s": 4110, "text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument." }, { "code": null, "e": 4429, "s": 4304, "text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below." }, { "code": null, "e": 4499, "s": 4429, "text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n" }, { "code": null, "e": 4651, "s": 4499, "text": "The Table class represents a two-dimensional grid filled with cells ordered in rows and columns. It belongs to the package com.itextpdf.layout.element." }, { "code": null, "e": 4695, "s": 4651, "text": "Instantiate the Table class as shown below." }, { "code": null, "e": 4819, "s": 4695, "text": "// Creating a table object \nfloat [] pointColumnWidths = {150F, 150F, 150F}; \nTable table = new Table(pointColumnWidths); \n" }, { "code": null, "e": 4983, "s": 4819, "text": "Create a cell object by instantiating the Cell class of the package com.itextpdf.layout.element. Add the contents of the cell using the add() method of this class." }, { "code": null, "e": 5140, "s": 4983, "text": "Finally, to add this cell to the table, call the addCell() method of the Table class and pass the cell object as a parameter to this method, as shown below." }, { "code": null, "e": 5534, "s": 5140, "text": "// Adding cell 1 to the table \nCell cell1 = new Cell(); // Creating a cell \ncell1.add(\"Name\"); // Adding content to the cell \ntable.addCell(cell1); // Adding cell to the table \n\n// Adding cell 2 to the table Cell \ncell2 = new Cell(); // Creating a cell \ncell2.add(\"Raju\"); // Adding content to the cell \ntable.addCell(cell2); // Adding cell to the table \n" }, { "code": null, "e": 5645, "s": 5534, "text": "Add the table object created in the previous step using the add() method of the Document class as shown below." }, { "code": null, "e": 5699, "s": 5645, "text": "// Adding list to the document \ndocument.add(table);\n" }, { "code": null, "e": 5782, "s": 5699, "text": "Close the document using the close() method of the Document class, as shown below." }, { "code": null, "e": 5827, "s": 5782, "text": "// Closing the document \ndocument.close(); \n" }, { "code": null, "e": 6063, "s": 5827, "text": "The following Java program demonstrates how to create a PDF document and add a table to it using the iText library. It creates a PDF document with the name addingTable.pdf, adds a table to it, and saves it in the path C:/itextExamples/" }, { "code": null, "e": 6120, "s": 6063, "text": "Save this code in a file with the name AddingTable.java." }, { "code": null, "e": 7596, "s": 6120, "text": "import com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \n\nimport com.itextpdf.layout.Document; \nimport com.itextpdf.layout.element.Cell; \nimport com.itextpdf.layout.element.Table; \n\npublic class AddingTable { \n public static void main(String args[]) throws Exception { \n // Creating a PdfDocument object \n String dest = \"C:/itextExamples/addingTable.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfDocument object \n PdfDocument pdf = new PdfDocument(writer); \n \n // Creating a Document object \n Document doc = new Document(pdf); \n \n // Creating a table \n float [] pointColumnWidths = {150F, 150F, 150F}; \n Table table = new Table(pointColumnWidths); \n \n // Adding cells to the table \n table.addCell(new Cell().add(\"Name\")); \n table.addCell(new Cell().add(\"Raju\")); \n table.addCell(new Cell().add(\"Id\")); \n table.addCell(new Cell().add(\"1001\")); \n table.addCell(new Cell().add(\"Designation\")); \n table.addCell(new Cell().add(\"Programmer\")); \n \n // Adding Table to document \n doc.add(table); \n \n // Closing the document \n doc.close();\n System.out.println(\"Table created successfully..\"); \n } \n}" }, { "code": null, "e": 7691, "s": 7596, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 7733, "s": 7691, "text": "javac AddingTable.java \njava AddingTable\n" }, { "code": null, "e": 7825, "s": 7733, "text": "Upon execution, the above program creates a PDF document, displaying the following message." }, { "code": null, "e": 7855, "s": 7825, "text": "Table created successfully..\n" }, { "code": null, "e": 7944, "s": 7855, "text": "If you verify the specified path, you can find the created PDF document, as shown below." }, { "code": null, "e": 7951, "s": 7944, "text": " Print" }, { "code": null, "e": 7962, "s": 7951, "text": " Add Notes" } ]
Convert a NumPy array into a csv file - GeeksforGeeks
02 Sep, 2020 In this article, we are going to see different methods to save an NumPy array into a CSV file. CSV file format is the easiest and useful format for storing data There are different methods by which we can save the NumPy array into a CSV file Method 1: Using Dataframe.to_csv(). This method is used to write a Dataframe into a CSV file. Example: Converting the array into pandas Dataframe and then saving it to CSV format. Python3 # import necessary librariesimport pandas as pdimport numpy as np # create a dummy arrayarr = np.arange(1,11).reshape(2,5) # display the arrayprint(arr) # convert array into dataframeDF = pd.DataFrame(arr) # save the dataframe as a csv fileDF.to_csv("data1.csv") Output: [[ 1 2 3 4 5] [ 6 7 8 9 10]] Method 2: Using numpy_array.tofile(). This method is used to write an array into the file. Example: Create an array then save into a CSV file. Python3 # import the necessary libraryimport numpy as np # create a dummy arrayarr = np.arange(1,11) # display the arrayprint(arr) # use the tofile() method # and use ',' as a separator# as we have to generate a csv filearr.tofile('data2.csv', sep = ',') Output: [ 1 2 3 4 5 6 7 8 9 10] Method 3: Using numpy.savetext(). This method is used to save an array to a text file. Example: Create an array then save as a CSV file. Python3 # import numpy libraryimport numpy # create an arraya = numpy.array([[1, 6, 4], [2, 4, 8], [3, 9, 1]]) # save array into csv filenumpy.savetxt("data3.csv", a, delimiter = ",") Output: Python numpy-io Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Reading and Writing to text files in Python Create a Pandas DataFrame from Lists sum() function in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24489, "s": 24461, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24650, "s": 24489, "text": "In this article, we are going to see different methods to save an NumPy array into a CSV file. CSV file format is the easiest and useful format for storing data" }, { "code": null, "e": 24731, "s": 24650, "text": "There are different methods by which we can save the NumPy array into a CSV file" }, { "code": null, "e": 24767, "s": 24731, "text": "Method 1: Using Dataframe.to_csv()." }, { "code": null, "e": 24825, "s": 24767, "text": "This method is used to write a Dataframe into a CSV file." }, { "code": null, "e": 24911, "s": 24825, "text": "Example: Converting the array into pandas Dataframe and then saving it to CSV format." }, { "code": null, "e": 24919, "s": 24911, "text": "Python3" }, { "code": "# import necessary librariesimport pandas as pdimport numpy as np # create a dummy arrayarr = np.arange(1,11).reshape(2,5) # display the arrayprint(arr) # convert array into dataframeDF = pd.DataFrame(arr) # save the dataframe as a csv fileDF.to_csv(\"data1.csv\")", "e": 25186, "s": 24919, "text": null }, { "code": null, "e": 25194, "s": 25186, "text": "Output:" }, { "code": null, "e": 25231, "s": 25194, "text": "[[ 1 2 3 4 5]\n[ 6 7 8 9 10]]\n" }, { "code": null, "e": 25269, "s": 25231, "text": "Method 2: Using numpy_array.tofile()." }, { "code": null, "e": 25322, "s": 25269, "text": "This method is used to write an array into the file." }, { "code": null, "e": 25374, "s": 25322, "text": "Example: Create an array then save into a CSV file." }, { "code": null, "e": 25382, "s": 25374, "text": "Python3" }, { "code": "# import the necessary libraryimport numpy as np # create a dummy arrayarr = np.arange(1,11) # display the arrayprint(arr) # use the tofile() method # and use ',' as a separator# as we have to generate a csv filearr.tofile('data2.csv', sep = ',')", "e": 25632, "s": 25382, "text": null }, { "code": null, "e": 25640, "s": 25632, "text": "Output:" }, { "code": null, "e": 25673, "s": 25640, "text": "[ 1 2 3 4 5 6 7 8 9 10]\n" }, { "code": null, "e": 25707, "s": 25673, "text": "Method 3: Using numpy.savetext()." }, { "code": null, "e": 25760, "s": 25707, "text": "This method is used to save an array to a text file." }, { "code": null, "e": 25810, "s": 25760, "text": "Example: Create an array then save as a CSV file." }, { "code": null, "e": 25818, "s": 25810, "text": "Python3" }, { "code": "# import numpy libraryimport numpy # create an arraya = numpy.array([[1, 6, 4], [2, 4, 8], [3, 9, 1]]) # save array into csv filenumpy.savetxt(\"data3.csv\", a, delimiter = \",\")", "e": 26042, "s": 25818, "text": null }, { "code": null, "e": 26050, "s": 26042, "text": "Output:" }, { "code": null, "e": 26066, "s": 26050, "text": "Python numpy-io" }, { "code": null, "e": 26079, "s": 26066, "text": "Python-numpy" }, { "code": null, "e": 26086, "s": 26079, "text": "Python" }, { "code": null, "e": 26184, "s": 26086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26193, "s": 26184, "text": "Comments" }, { "code": null, "e": 26206, "s": 26193, "text": "Old Comments" }, { "code": null, "e": 26224, "s": 26206, "text": "Python Dictionary" }, { "code": null, "e": 26259, "s": 26224, "text": "Read a file line by line in Python" }, { "code": null, "e": 26281, "s": 26259, "text": "Enumerate() in Python" }, { "code": null, "e": 26313, "s": 26281, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26343, "s": 26313, "text": "Iterate over a list in Python" }, { "code": null, "e": 26385, "s": 26343, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26429, "s": 26385, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26466, "s": 26429, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26491, "s": 26466, "text": "sum() function in Python" } ]
Flutter - Ephemeral State Management
Since Flutter application is composed of widgets, the state management is also done by widgets. The entry point of the state management is Statefulwidget. Widget can be inherited from Statefulwidget to maintain its state and its children state. Statefulwidget provides an option for a widget to create a state, State (where T is the inherited widget) when the widget is created for the first time through createState method and then a method, setState to change the state whenever needed. The state change will be done through gestures. For example, the rating of a product can be changed by tapping a star in the rating widget. Let us create a widget, RatingBox with state maintenance. The purpose of the widget is to show the current rating of a specific product. The step by step process for creating a RatingBox widget with state maintenance is as follows − Create the widget, RatingBox by inheriting StatefulWidget. Create the widget, RatingBox by inheriting StatefulWidget. class RatingBox extends StatefulWidget { } Create a state for RatingBox, _RatingBoxState by inheriting State<T> Create a state for RatingBox, _RatingBoxState by inheriting State<T> class _RatingBoxState extends State<RatingBox> { } Override the createState of StatefulWidget method to create the state, _RatingBoxState. Override the createState of StatefulWidget method to create the state, _RatingBoxState. class RatingBox extends StatefulWidget { @override _RatingBoxState createState() => _RatingBoxState(); } Create the user interface of the RatingBox widget in build method of _RatingBoxState. Usually, the user interface will be done in the build method of RatingBox widget itself. But, when state maintenance is needed, we need to build the user interface in _RatingBoxState widget. This ensures the re-rendering of user interface whenever the state of the widget is changed. Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], iconSize: _size, ), ), ], ); } Here, we have used three star, created using IconButton widget and arranged it using Row widget in a single row. The idea is to show the rating through the sequence of red stars. For example, if the rating is two star, then first two star will be red and the last one is in white. Write methods in _RatingBoxState to change / set the state of the widget. Write methods in _RatingBoxState to change / set the state of the widget. void _setRatingAsOne() { setState( () { _rating = 1; }); } void _setRatingAsTwo() { setState( () { _rating = 2; }); } void _setRatingAsThree() { setState( () { _rating = 3; }); } Here, each method sets the current rating of the widget through setState. Here, each method sets the current rating of the widget through setState. Wire the user gesture (tapping the star) to the proper state changing method. Wire the user gesture (tapping the star) to the proper state changing method. Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsTwo, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsThree, iconSize: _size, ), ), ], ); } Here, the onPressed event calls the relevant function to change the state and subsequently change the user interface. For example, if a user clicks the third star, then _setRatingAsThree will be called and it will change the _rating to 3. Since the state is changed, the build method will be called again and the user interface will be build and rendered again. The complete code of the widget, RatingBox is as follows − The complete code of the widget, RatingBox is as follows − class RatingBox extends StatefulWidget { @override _RatingBoxState createState() => _RatingBoxState(); } class _RatingBoxState extends State<RatingBox> { int _rating = 0; void _setRatingAsOne() { setState( () { _rating = 1; }); } void _setRatingAsTwo() { setState( () { _rating = 2; }); } void _setRatingAsThree() { setState( () { _rating = 3; }); } Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsTwo, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsThree, iconSize: _size, ), ), ], ); } } Let us create a new application and use our newly created RatingBox widget to show the rating of the product. Create a new Flutter application in Android studio, product_state_app. Create a new Flutter application in Android studio, product_state_app. Replace main.dart code with below code − import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Product state demo home page'), ); } } class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), body: Center( child: Text( 'Hello World', ) ), ); } } Here, Here, We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed relevant code. We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed relevant code. Include our newly created RatingBox widget. Include our newly created RatingBox widget. Create a ProductBox widget to list the product along with rating as specified below − Create a ProductBox widget to list the product along with rating as specified below − class ProductBox extends StatelessWidget { ProductBox({Key key, this.name, this.description, this.price, this.image}) : super(key: key); final String name; final String description; final int price; final String image; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 120, child: Card( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.asset("assets/appimages/" + image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.name, style: TextStyle( fontWeight: FontWeight.bold)), Text(this.description), Text("Price: " + this.price.toString()), RatingBox(), ], ) ) ) ] ) ) ); } } Update the MyHomePage widget to include the ProductBox widget as specified below − Update the MyHomePage widget to include the ProductBox widget as specified below − class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Product Listing")), body: ListView( shrinkWrap: true, padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0), children: <Widget>[ ProductBox( name: "iPhone", description: "iPhone is the stylist phone ever", price: 1000, image: "iphone.png" ), ProductBox( name: "Pixel", description: "Pixel is the most feature phone ever", price: 800, image: "pixel.png" ), ProductBox( name: "Laptop", description: "Laptop is most productive development tool", price: 2000, image: "laptop.png" ), ProductBox( name: "Tablet", description: "Tablet is the most useful device ever for meeting", price: 1500, image: "tablet.png" ), ProductBox( name: "Pendrive", description: "Pendrive is useful storage medium", price: 100, image: "pendrive.png" ), ProductBox( name: "Floppy Drive", description: "Floppy drive is useful rescue storage medium", price: 20, image: "floppy.png" ), ], ) ); } } The complete code of the application is as follows − The complete code of the application is as follows − import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage( title: 'Product layout demo home page'), ); } } class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Product Listing")), body: ListView( shrinkWrap: true, padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0), children: <Widget>[ ProductBox( name: "iPhone", description: "iPhone is the stylist phone ever", price: 1000, image: "iphone.png" ), ProductBox( name: "Pixel", description: "Pixel is the most featureful phone ever", price: 800, image: "pixel.png" ), ProductBox( name: "Laptop", description: "Laptop is most productive development tool", price: 2000, image: "laptop.png" ), ProductBox( name: "Tablet", description: "Tablet is the most useful device ever for meeting", price: 1500, image: "tablet.png" ), ProductBox( name: "Pendrive", description: "iPhone is the stylist phone ever", price: 100, image: "pendrive.png" ), ProductBox( name: "Floppy Drive", description: "iPhone is the stylist phone ever", price: 20, image: "floppy.png" ), ProductBox( name: "iPhone", description: "iPhone is the stylist phone ever", price: 1000, image: "iphone.png" ), ProductBox( name: "iPhone", description: "iPhone is the stylist phone ever", price: 1000, image: "iphone.png" ), ], ) ); } } class RatingBox extends StatefulWidget { @override _RatingBoxState createState() => _RatingBoxState(); } class _RatingBoxState extends State<RatingBox> { int _rating = 0; void _setRatingAsOne() { setState( () { _rating = 1; }); } void _setRatingAsTwo() { setState( () { _rating = 2; }); } void _setRatingAsThree() { setState( () { _rating = 3; }); } Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), color: Colors.red[500], onPressed: _setRatingAsTwo, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) : Icon(Icons.star_border, size: _size,)), Colors.red[500], onPressed: _setRatingAsThree, iconSize: _size, ), ), ], ); } } class ProductBox extends StatelessWidget { ProductBox({Key key, this.name, this.description, this.price, this.image}) : super(key: key); final String name; final String description; final int price; final String image; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.asset("assets/appimages/" + image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.name, style: TextStyle(fontWeight: FontWeight.bold)), Text(this.description), Text("Price: " + this.price.toString()), RatingBox(), ], ) ) ) ] ) ) ); } } Clicking the rating star will update the rating of the product. For example, setting 2-star rating for iPhone will display the rating as below − 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": 2847, "s": 2218, "text": "Since Flutter application is composed of widgets, the state management is also done by widgets. The entry point of the state management is Statefulwidget. Widget can be inherited from Statefulwidget to maintain its state and its children state. Statefulwidget provides an option for a widget to create a state, State (where T is the inherited widget) when the widget is created for the first time through createState method and then a method, setState to change the state whenever needed. The state change will be done through gestures. For example, the rating of a product can be changed by tapping a star in the rating widget." }, { "code": null, "e": 3080, "s": 2847, "text": "Let us create a widget, RatingBox with state maintenance. The purpose of the widget is to show the current rating of a specific product. The step by step process for creating a RatingBox widget with state maintenance is as follows −" }, { "code": null, "e": 3139, "s": 3080, "text": "Create the widget, RatingBox by inheriting StatefulWidget." }, { "code": null, "e": 3198, "s": 3139, "text": "Create the widget, RatingBox by inheriting StatefulWidget." }, { "code": null, "e": 3242, "s": 3198, "text": "class RatingBox extends StatefulWidget { }\n" }, { "code": null, "e": 3311, "s": 3242, "text": "Create a state for RatingBox, _RatingBoxState by inheriting State<T>" }, { "code": null, "e": 3380, "s": 3311, "text": "Create a state for RatingBox, _RatingBoxState by inheriting State<T>" }, { "code": null, "e": 3432, "s": 3380, "text": "class _RatingBoxState extends State<RatingBox> { }\n" }, { "code": null, "e": 3520, "s": 3432, "text": "Override the createState of StatefulWidget method to create the state, _RatingBoxState." }, { "code": null, "e": 3608, "s": 3520, "text": "Override the createState of StatefulWidget method to create the state, _RatingBoxState." }, { "code": null, "e": 3722, "s": 3608, "text": "class RatingBox extends StatefulWidget { \n @override \n _RatingBoxState createState() => _RatingBoxState(); \n}" }, { "code": null, "e": 4092, "s": 3722, "text": "Create the user interface of the RatingBox widget in build method of _RatingBoxState. Usually, the user interface will be done in the build method of RatingBox widget itself. But, when state maintenance is needed, we need to build the user interface in _RatingBoxState widget. This ensures the re-rendering of user interface whenever the state of the widget is changed." }, { "code": null, "e": 5299, "s": 4092, "text": "Widget build(BuildContext context) { \n double _size = 20; \n print(_rating); \n\n return Row(\n mainAxisAlignment: MainAxisAlignment.end,\n crossAxisAlignment: CrossAxisAlignment.end,\n mainAxisSize: MainAxisSize.max,\n children: <Widget>[\n Container(\n padding: EdgeInsets.all(0), \n child: IconButton( \n icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) : \n Icon(Icons.star_border, size: _size,)), \n color: Colors.red[500], \n iconSize: _size, \n ), \n ), Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) :\n Icon(Icons.star_border, size: _size,)),\n color: Colors.red[500],\n iconSize: _size,\n ),\n ), Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) :\n Icon(Icons.star_border, size: _size,)),\n color: Colors.red[500],\n iconSize: _size,\n ),\n ),\n ],\n );\n}" }, { "code": null, "e": 5580, "s": 5299, "text": "Here, we have used three star, created using IconButton widget and arranged it using Row widget in a single row. The idea is to show the rating through the sequence of red stars. For example, if the rating is two star, then first two star will be red and the last one is in white." }, { "code": null, "e": 5654, "s": 5580, "text": "Write methods in _RatingBoxState to change / set the state of the widget." }, { "code": null, "e": 5728, "s": 5654, "text": "Write methods in _RatingBoxState to change / set the state of the widget." }, { "code": null, "e": 5951, "s": 5728, "text": "void _setRatingAsOne() { \n setState( () { \n _rating = 1; \n }); \n}\nvoid _setRatingAsTwo() {\n setState( () {\n _rating = 2;\n });\n}\nvoid _setRatingAsThree() { \n setState( () { \n _rating = 3; \n }); \n}" }, { "code": null, "e": 6025, "s": 5951, "text": "Here, each method sets the current rating of the widget through setState." }, { "code": null, "e": 6099, "s": 6025, "text": "Here, each method sets the current rating of the widget through setState." }, { "code": null, "e": 6177, "s": 6099, "text": "Wire the user gesture (tapping the star) to the proper state changing method." }, { "code": null, "e": 6255, "s": 6177, "text": "Wire the user gesture (tapping the star) to the proper state changing method." }, { "code": null, "e": 7608, "s": 6255, "text": "Widget build(BuildContext context) { \n double _size = 20; \n print(_rating); \n \n return Row(\n mainAxisAlignment: MainAxisAlignment.end, \n crossAxisAlignment: CrossAxisAlignment.end,\n mainAxisSize: MainAxisSize.max,\n children: <Widget>[\n Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) :\n Icon(Icons.star_border, size: _size,)),\n color: Colors.red[500],\n onPressed: _setRatingAsOne,\n iconSize: _size,\n ),\n ),\n Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) :\n Icon(Icons.star_border, size: _size,)),\n color: Colors.red[500],\n onPressed: _setRatingAsTwo,\n iconSize: _size,\n ),\n ),\n Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) :\n Icon(Icons.star_border, size: _size,)),\n color: Colors.red[500],\n onPressed: _setRatingAsThree,\n iconSize: _size,\n ),\n ),\n ],\n );\n}" }, { "code": null, "e": 7970, "s": 7608, "text": "Here, the onPressed event calls the relevant function to change the state and subsequently change the user interface. For example, if a user clicks the third star, then _setRatingAsThree will be called and it will change the _rating to 3. Since the state is changed, the build method will be called again and the user interface will be build and rendered again." }, { "code": null, "e": 8029, "s": 7970, "text": "The complete code of the widget, RatingBox is as follows −" }, { "code": null, "e": 8088, "s": 8029, "text": "The complete code of the widget, RatingBox is as follows −" }, { "code": null, "e": 10029, "s": 8088, "text": "class RatingBox extends StatefulWidget { \n @override \n _RatingBoxState createState() => _RatingBoxState(); \n}\nclass _RatingBoxState extends State<RatingBox> { \n int _rating = 0; \n void _setRatingAsOne() {\n setState( () {\n _rating = 1; \n }); \n } \n void _setRatingAsTwo() {\n setState( () {\n _rating = 2;\n });\n }\n void _setRatingAsThree() {\n setState( () {\n _rating = 3;\n });\n }\n Widget build(BuildContext context) {\n double _size = 20; \n print(_rating); \n return Row(\n mainAxisAlignment: MainAxisAlignment.end, \n crossAxisAlignment: CrossAxisAlignment.end, \n mainAxisSize: MainAxisSize.max, \n children: <Widget>[ \n Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) :\n Icon(Icons.star_border, size: _size,)),\n color: Colors.red[500],\n onPressed: _setRatingAsOne,\n iconSize: _size,\n ),\n ),\n Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) :\n Icon(Icons.star_border, size: _size,)), \n color: Colors.red[500], \n onPressed: _setRatingAsTwo, \n iconSize: _size, \n ), \n ), \n Container(\n padding: EdgeInsets.all(0), \n child: IconButton(\n icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) : \n Icon(Icons.star_border, size: _size,)), \n color: Colors.red[500], \n onPressed: _setRatingAsThree, \n iconSize: _size, \n ), \n ), \n ], \n ); \n } \n}" }, { "code": null, "e": 10139, "s": 10029, "text": "Let us create a new application and use our newly created RatingBox widget to show the rating of the product." }, { "code": null, "e": 10210, "s": 10139, "text": "Create a new Flutter application in Android studio, product_state_app." }, { "code": null, "e": 10281, "s": 10210, "text": "Create a new Flutter application in Android studio, product_state_app." }, { "code": null, "e": 10322, "s": 10281, "text": "Replace main.dart code with below code −" }, { "code": null, "e": 11121, "s": 10322, "text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp());\n\nclass MyApp extends StatelessWidget { \n // This widget is the root of your application. \n @override \n Widget build(BuildContext context) { \n return MaterialApp(\n title: 'Flutter Demo',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ), home: MyHomePage(title: 'Product state demo home page'),\n );\n }\n}\nclass MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key);\n \n final String title;\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text(this.title),\n ),\n body: Center(\n child: Text( 'Hello World', )\n ),\n );\n }\n}" }, { "code": null, "e": 11127, "s": 11121, "text": "Here," }, { "code": null, "e": 11133, "s": 11127, "text": "Here," }, { "code": null, "e": 11262, "s": 11133, "text": "We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed relevant code." }, { "code": null, "e": 11391, "s": 11262, "text": "We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed relevant code." }, { "code": null, "e": 11435, "s": 11391, "text": "Include our newly created RatingBox widget." }, { "code": null, "e": 11479, "s": 11435, "text": "Include our newly created RatingBox widget." }, { "code": null, "e": 11565, "s": 11479, "text": "Create a ProductBox widget to list the product along with rating as specified below −" }, { "code": null, "e": 11651, "s": 11565, "text": "Create a ProductBox widget to list the product along with rating as specified below −" }, { "code": null, "e": 12974, "s": 11651, "text": "class ProductBox extends StatelessWidget {\n ProductBox({Key key, this.name, this.description, this.price, this.image})\n : super(key: key); \n \n final String name; \n final String description; \n final int price; \n final String image; \n \n Widget build(BuildContext context) { \n return Container(\n padding: EdgeInsets.all(2), \n height: 120, \n child: Card(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n children: <Widget>[\n Image.asset(\"assets/appimages/\" + image),\n Expanded(\n child: Container( \n padding: EdgeInsets.all(5), \n child: Column( \n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[\n Text(this.name, style: TextStyle(\n fontWeight: FontWeight.bold)), \n Text(this.description), \n Text(\"Price: \" + this.price.toString()), \n RatingBox(), \n ], \n )\n )\n )\n ]\n )\n )\n );\n }\n}" }, { "code": null, "e": 13057, "s": 12974, "text": "Update the MyHomePage widget to include the ProductBox widget as specified below −" }, { "code": null, "e": 13140, "s": 13057, "text": "Update the MyHomePage widget to include the ProductBox widget as specified below −" }, { "code": null, "e": 14955, "s": 13140, "text": "class MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n\n @override \n Widget build(BuildContext context) {\n return Scaffold( \n appBar: AppBar(title: Text(\"Product Listing\")), \n body: ListView( \n shrinkWrap: true, padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0), \n children: <Widget>[\n ProductBox( \n name: \"iPhone\", \n description: \"iPhone is the stylist phone ever\", \n price: 1000, \n image: \"iphone.png\"\n ), \n ProductBox( \n name: \"Pixel\", \n description: \"Pixel is the most feature phone ever\", \n price: 800, \n image: \"pixel.png\"\n ), \n ProductBox( \n name: \"Laptop\", \n description: \"Laptop is most productive development tool\",\n price: 2000, \n image: \"laptop.png\"\n ),\n ProductBox( \n name: \"Tablet\", \n description: \"Tablet is the most useful device ever for meeting\", \n price: 1500, \n image: \"tablet.png\"\n ),\n ProductBox( \n name: \"Pendrive\", \n description: \"Pendrive is useful storage medium\", \n price: 100, \n image: \"pendrive.png\"\n ),\n ProductBox( \n name: \"Floppy Drive\", \n description: \"Floppy drive is useful rescue storage medium\", \n price: 20, \n image: \"floppy.png\"\n ),\n ], \n )\n ); \n }\n}" }, { "code": null, "e": 15008, "s": 14955, "text": "The complete code of the application is as follows −" }, { "code": null, "e": 15061, "s": 15008, "text": "The complete code of the application is as follows −" }, { "code": null, "e": 20969, "s": 15061, "text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp()); \n\nclass MyApp extends StatelessWidget { \n // This widget is the root of your application. \n @override \n Widget build(BuildContext context) { \n return MaterialApp( \n title: 'Flutter Demo', \n theme: ThemeData( \n primarySwatch: Colors.blue, \n ), \n home: MyHomePage( title: 'Product layout demo home page'), \n ); \n }\n}\nclass MyHomePage extends StatelessWidget { \n MyHomePage({Key key, this.title}) : super(key: key); \n\n final String title; \n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title: Text(\"Product Listing\")),\n body: ListView(\n shrinkWrap: true,\n padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0),\n children: <Widget>[\n ProductBox(\n name: \"iPhone\",\n description: \"iPhone is the stylist phone ever\",\n price: 1000,\n image: \"iphone.png\"\n ),\n ProductBox(\n name: \"Pixel\",\n description: \"Pixel is the most featureful phone ever\",\n price: 800,\n image: \"pixel.png\"\n ),\n ProductBox(\n name: \"Laptop\",\n description: \"Laptop is most productive development tool\",\n price: 2000,\n image: \"laptop.png\"\n ),\n ProductBox(\n name: \"Tablet\",\n description: \"Tablet is the most useful device ever for meeting\",\n price: 1500,\n image: \"tablet.png\"\n ),\n ProductBox(\n name: \"Pendrive\",\n description: \"iPhone is the stylist phone ever\",\n price: 100,\n image: \"pendrive.png\"\n ),\n ProductBox(\n name: \"Floppy Drive\",\n description: \"iPhone is the stylist phone ever\",\n price: 20,\n image: \"floppy.png\"\n ),\n ProductBox(\n name: \"iPhone\",\n description: \"iPhone is the stylist phone ever\",\n price: 1000,\n image: \"iphone.png\"\n ),\n ProductBox(\n name: \"iPhone\",\n description: \"iPhone is the stylist phone ever\",\n price: 1000,\n image: \"iphone.png\"\n ),\n ],\n )\n );\n }\n}\nclass RatingBox extends StatefulWidget {\n @override \n _RatingBoxState createState() => \n _RatingBoxState(); \n}\nclass _RatingBoxState extends State<RatingBox> {\n int _rating = 0; \n void _setRatingAsOne() {\n setState( () {\n _rating = 1;\n }); \n } \n void _setRatingAsTwo() { \n setState( () { \n _rating = 2; \n }); \n } \n void _setRatingAsThree() { \n setState( () { \n _rating = 3; \n }); \n } \n Widget build(BuildContext context) { \n double _size = 20; \n print(_rating); \n return Row( \n mainAxisAlignment: MainAxisAlignment.end, \n crossAxisAlignment: CrossAxisAlignment.end, \n mainAxisSize: MainAxisSize.max, \n children: <Widget>[\n Container(\n padding: EdgeInsets.all(0), \n child: IconButton( \n icon: (_rating >= 1 ? Icon(Icons.star, size: _size,) : \n Icon(Icons.star_border, size: _size,)), \n color: Colors.red[500], \n onPressed: _setRatingAsOne, \n iconSize: _size, \n ), \n ), \n Container( \n padding: EdgeInsets.all(0), \n child: IconButton( \n icon: (_rating >= 2 ? Icon(Icons.star, size: _size,) : \n Icon(Icons.star_border, size: _size,)), \n color: Colors.red[500], \n onPressed: _setRatingAsTwo, \n iconSize: _size, \n ), \n ), \n Container(\n padding: EdgeInsets.all(0),\n child: IconButton(\n icon: (_rating >= 3 ? Icon(Icons.star, size: _size,) : \n Icon(Icons.star_border, size: _size,)),\n Colors.red[500], \n onPressed: _setRatingAsThree, \n iconSize: _size, \n ), \n ), \n ], \n ); \n }\n}\nclass ProductBox extends StatelessWidget {\n ProductBox({Key key, this.name, this.description, this.price, this.image}) : \n super(key: key); \n final String name; \n final String description; \n final int price; \n final String image; \n Widget build(BuildContext context) {\n return Container(\n padding: EdgeInsets.all(2),\n height: 140,\n child: Card(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n children: <Widget>[\n Image.asset(\"assets/appimages/\" + image),\n Expanded(\n child: Container(\n padding: EdgeInsets.all(5),\n child: Column(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[\n Text(this.name, style: TextStyle(fontWeight: FontWeight.bold)), \n Text(this.description), \n Text(\"Price: \" + this.price.toString()), \n RatingBox(), \n ], \n )\n )\n )\n ]\n )\n )\n ); \n }\n}" }, { "code": null, "e": 21114, "s": 20969, "text": "Clicking the rating star will update the rating of the product. For example, setting 2-star rating for iPhone will display the rating as below −" }, { "code": null, "e": 21147, "s": 21114, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 21167, "s": 21147, "text": " Sriyank Siddhartha" }, { "code": null, "e": 21202, "s": 21167, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 21219, "s": 21202, "text": " Frahaan Hussain" }, { "code": null, "e": 21252, "s": 21219, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 21272, "s": 21252, "text": " Skillbakerystudios" }, { "code": null, "e": 21304, "s": 21272, "text": "\n 17 Lectures \n 51 mins\n" }, { "code": null, "e": 21324, "s": 21304, "text": " Harsh Kumar Khatri" }, { "code": null, "e": 21359, "s": 21324, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 21374, "s": 21359, "text": " Pramila Rawat" }, { "code": null, "e": 21410, "s": 21374, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 21425, "s": 21410, "text": " Rahul Agarwal" }, { "code": null, "e": 21432, "s": 21425, "text": " Print" }, { "code": null, "e": 21443, "s": 21432, "text": " Add Notes" } ]
Bootstrap lead class
The lead class in Bootstrap is used to add emphasis to a paragraph. You can try to run the following code to implement the lead class in Bootstrap − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap lead class</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <h2>Lead Example</h2> <p class = "lead">This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is an example paragraph demonstrating the use of lead body copy. </p> </body> </html>
[ { "code": null, "e": 1130, "s": 1062, "text": "The lead class in Bootstrap is used to add emphasis to a paragraph." }, { "code": null, "e": 1211, "s": 1130, "text": "You can try to run the following code to implement the lead class in Bootstrap −" }, { "code": null, "e": 1222, "s": 1211, "text": " Live Demo" }, { "code": null, "e": 1981, "s": 1222, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap lead class</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h2>Lead Example</h2>\n <p class = \"lead\">This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is an example paragraph demonstrating the use of lead body copy.\n </p>\n </body>\n</html>" } ]
How to convert a Base64 string into a Bitmap image in Android app?
This example demonstrates how to do I 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" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:padding="16dp"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Base64 string into a BitMap image in Android App" android:textSize="16sp" android:textStyle="bold|italic" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Base64; import android.widget.ImageView; import java.io.ByteArrayOutputStream; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ImageView imageView; @SuppressLint("WrongThread") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] imageBytes = byteArrayOutputStream.toByteArray(); String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); imageBytes = Base64.decode(imageString, Base64.DEFAULT); Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); imageView.setImageBitmap(decodedImage); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the 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": 1112, "s": 1062, "text": "This example demonstrates how to do I in android." }, { "code": null, "e": 1241, "s": 1112, "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": 1306, "s": 1241, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1988, "s": 1306, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Base64 string into a BitMap image in Android App\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\" />\n</LinearLayout>" }, { "code": null, "e": 2045, "s": 1988, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3240, "s": 2045, "text": "import android.annotation.SuppressLint;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.os.Bundle;\nimport android.util.Base64;\nimport android.widget.ImageView;\nimport java.io.ByteArrayOutputStream;\nimport androidx.appcompat.app.AppCompatActivity;\npublic class MainActivity extends AppCompatActivity {\n ImageView imageView;\n @SuppressLint(\"WrongThread\")\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);\n bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);\n byte[] imageBytes = byteArrayOutputStream.toByteArray();\n String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);\n imageBytes = Base64.decode(imageString, Base64.DEFAULT);\n Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);\n imageView.setImageBitmap(decodedImage);\n }\n}" }, { "code": null, "e": 3295, "s": 3240, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3968, "s": 3295, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4322, "s": 3968, "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 the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
Bidirectional Associative Memory (BAM) Implementation from Scratch - GeeksforGeeks
06 Oct, 2021 Prerequisite: ANN | Bidirectional Associative Memory (BAM) Learning AlgorithmTo implement BAM model, here are some essential consideration and approach- Consider the value of M, as BAM will be constructed with M pairs of patterns. Here the value of M is 4.Set A: Input PatternsSet B: Corresponding Target PatternsAssign the neurons in input and output layer. Here, neurons in input layer are 6 and output layer are 3Compute the Weight Matrix using the BAM AlgorithmTest the BAM model for the input patterns which will return the corresponding target patterns as output. As well as for each of the target patterns, the BAM model will return the corresponding input patterns. Consider the value of M, as BAM will be constructed with M pairs of patterns. Here the value of M is 4. Set A: Input Patterns Set B: Corresponding Target Patterns Assign the neurons in input and output layer. Here, neurons in input layer are 6 and output layer are 3 Compute the Weight Matrix using the BAM Algorithm Test the BAM model for the input patterns which will return the corresponding target patterns as output. As well as for each of the target patterns, the BAM model will return the corresponding input patterns. Python Implementation of BAM: Python3 # Import Python Librariesimport numpy as np # Take two sets of patterns:# Set A: Input Patternx1 = np.array([1, 1, 1, 1, 1, 1]).reshape(6, 1)x2 = np.array([-1, -1, -1, -1, -1, -1]).reshape(6, 1)x3 = np.array([1, 1, -1, -1, 1, 1]).reshape(6, 1)x4 = np.array([-1, -1, 1, 1, -1, -1]).reshape(6, 1) # Set B: Target Patterny1 = np.array([1, 1, 1]).reshape(3, 1)y2 = np.array([-1, -1, -1]).reshape(3, 1)y3 = np.array([1, -1, 1]).reshape(3, 1)y4 = np.array([-1, 1, -1]).reshape(3, 1) '''print("Set A: Input Pattern, Set B: Target Pattern")print("\nThe input for pattern 1 is")print(x1)print("\nThe target for pattern 1 is")print(y1)print("\nThe input for pattern 2 is")print(x2)print("\nThe target for pattern 2 is")print(y2)print("\nThe input for pattern 3 is")print(x3)print("\nThe target for pattern 3 is")print(y3)print("\nThe input for pattern 4 is")print(x4)print("\nThe target for pattern 4 is")print(y4) print("\n------------------------------")'''# Calculate weight Matrix: WinputSet = np.concatenate((x1, x2, x3, x4), axis = 1)targetSet = np.concatenate((y1.T, y2.T, y3.T, y4.T), axis = 0)print("\nWeight matrix:")weight = np.dot(inputSet, targetSet)print(weight) print("\n------------------------------") # Testing Phase# Test for Input Patterns: Set Aprint("\nTesting for input patterns: Set A")def testInputs(x, weight): # Multiply the input pattern with the weight matrix # (weight.T X x) y = np.dot(weight.T, x) y[y < 0] = -1 y[y >= 0] = 1 return np.array(y) print("\nOutput of input pattern 1")print(testInputs(x1, weight))print("\nOutput of input pattern 2")print(testInputs(x2, weight))print("\nOutput of input pattern 3")print(testInputs(x3, weight))print("\nOutput of input pattern 4")print(testInputs(x4, weight)) # Test for Target Patterns: Set Bprint("\nTesting for target patterns: Set B")def testTargets(y, weight): # Multiply the target pattern with the weight matrix # (weight X y) x = np.dot(weight, y) x[x <= 0] = -1 x[x > 0] = 1 return np.array(x) print("\nOutput of target pattern 1")print(testTargets(y1, weight))print("\nOutput of target pattern 2")print(testTargets(y2, weight))print("\nOutput of target pattern 3")print(testTargets(y3, weight))print("\nOutput of target pattern 4")print(testTargets(y4, weight)) Weight matrix: [[4 0 4] [4 0 4] [0 4 0] [0 4 0] [4 0 4] [4 0 4]] ------------------------------ Testing for input patterns: Set A Output of input pattern 1 [[1] [1] [1]] Output of input pattern 2 [[-1] [-1] [-1]] Output of input pattern 3 [[ 1] [-1] [ 1]] Output of input pattern 4 [[-1] [ 1] [-1]] Testing for target patterns: Set B Output of target pattern 1 [[1] [1] [1] [1] [1] [1]] Output of target pattern 2 [[-1] [-1] [-1] [-1] [-1] [-1]] Output of target pattern 3 [[ 1] [ 1] [-1] [-1] [ 1] [ 1]] Output of target pattern 4 [[-1] [-1] [ 1] [ 1] [-1] [-1]] Here, for each of the input patterns, the BAM model gives the correct target patterns and for the target patterns, the model also gives the corresponding input patterns. Hence, it signifies that the BAM model is correctly implemented. arorakashish0911 Neural Network Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree Search Algorithms in AI Python | Decision tree implementation Decision Tree Introduction with example Elbow Method for optimal value of k in KMeans 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": 24484, "s": 24456, "text": "\n06 Oct, 2021" }, { "code": null, "e": 24639, "s": 24484, "text": "Prerequisite: ANN | Bidirectional Associative Memory (BAM) Learning AlgorithmTo implement BAM model, here are some essential consideration and approach- " }, { "code": null, "e": 25160, "s": 24639, "text": "Consider the value of M, as BAM will be constructed with M pairs of patterns. Here the value of M is 4.Set A: Input PatternsSet B: Corresponding Target PatternsAssign the neurons in input and output layer. Here, neurons in input layer are 6 and output layer are 3Compute the Weight Matrix using the BAM AlgorithmTest the BAM model for the input patterns which will return the corresponding target patterns as output. As well as for each of the target patterns, the BAM model will return the corresponding input patterns." }, { "code": null, "e": 25264, "s": 25160, "text": "Consider the value of M, as BAM will be constructed with M pairs of patterns. Here the value of M is 4." }, { "code": null, "e": 25286, "s": 25264, "text": "Set A: Input Patterns" }, { "code": null, "e": 25323, "s": 25286, "text": "Set B: Corresponding Target Patterns" }, { "code": null, "e": 25427, "s": 25323, "text": "Assign the neurons in input and output layer. Here, neurons in input layer are 6 and output layer are 3" }, { "code": null, "e": 25477, "s": 25427, "text": "Compute the Weight Matrix using the BAM Algorithm" }, { "code": null, "e": 25686, "s": 25477, "text": "Test the BAM model for the input patterns which will return the corresponding target patterns as output. As well as for each of the target patterns, the BAM model will return the corresponding input patterns." }, { "code": null, "e": 25718, "s": 25686, "text": "Python Implementation of BAM: " }, { "code": null, "e": 25726, "s": 25718, "text": "Python3" }, { "code": "# Import Python Librariesimport numpy as np # Take two sets of patterns:# Set A: Input Patternx1 = np.array([1, 1, 1, 1, 1, 1]).reshape(6, 1)x2 = np.array([-1, -1, -1, -1, -1, -1]).reshape(6, 1)x3 = np.array([1, 1, -1, -1, 1, 1]).reshape(6, 1)x4 = np.array([-1, -1, 1, 1, -1, -1]).reshape(6, 1) # Set B: Target Patterny1 = np.array([1, 1, 1]).reshape(3, 1)y2 = np.array([-1, -1, -1]).reshape(3, 1)y3 = np.array([1, -1, 1]).reshape(3, 1)y4 = np.array([-1, 1, -1]).reshape(3, 1) '''print(\"Set A: Input Pattern, Set B: Target Pattern\")print(\"\\nThe input for pattern 1 is\")print(x1)print(\"\\nThe target for pattern 1 is\")print(y1)print(\"\\nThe input for pattern 2 is\")print(x2)print(\"\\nThe target for pattern 2 is\")print(y2)print(\"\\nThe input for pattern 3 is\")print(x3)print(\"\\nThe target for pattern 3 is\")print(y3)print(\"\\nThe input for pattern 4 is\")print(x4)print(\"\\nThe target for pattern 4 is\")print(y4) print(\"\\n------------------------------\")'''# Calculate weight Matrix: WinputSet = np.concatenate((x1, x2, x3, x4), axis = 1)targetSet = np.concatenate((y1.T, y2.T, y3.T, y4.T), axis = 0)print(\"\\nWeight matrix:\")weight = np.dot(inputSet, targetSet)print(weight) print(\"\\n------------------------------\") # Testing Phase# Test for Input Patterns: Set Aprint(\"\\nTesting for input patterns: Set A\")def testInputs(x, weight): # Multiply the input pattern with the weight matrix # (weight.T X x) y = np.dot(weight.T, x) y[y < 0] = -1 y[y >= 0] = 1 return np.array(y) print(\"\\nOutput of input pattern 1\")print(testInputs(x1, weight))print(\"\\nOutput of input pattern 2\")print(testInputs(x2, weight))print(\"\\nOutput of input pattern 3\")print(testInputs(x3, weight))print(\"\\nOutput of input pattern 4\")print(testInputs(x4, weight)) # Test for Target Patterns: Set Bprint(\"\\nTesting for target patterns: Set B\")def testTargets(y, weight): # Multiply the target pattern with the weight matrix # (weight X y) x = np.dot(weight, y) x[x <= 0] = -1 x[x > 0] = 1 return np.array(x) print(\"\\nOutput of target pattern 1\")print(testTargets(y1, weight))print(\"\\nOutput of target pattern 2\")print(testTargets(y2, weight))print(\"\\nOutput of target pattern 3\")print(testTargets(y3, weight))print(\"\\nOutput of target pattern 4\")print(testTargets(y4, weight))", "e": 27978, "s": 25726, "text": null }, { "code": null, "e": 28586, "s": 27978, "text": "Weight matrix:\n[[4 0 4]\n [4 0 4]\n [0 4 0]\n [0 4 0]\n [4 0 4]\n [4 0 4]]\n\n------------------------------\n\nTesting for input patterns: Set A\n\nOutput of input pattern 1\n[[1]\n [1]\n [1]]\n\nOutput of input pattern 2\n[[-1]\n [-1]\n [-1]]\n\nOutput of input pattern 3\n[[ 1]\n [-1]\n [ 1]]\n\nOutput of input pattern 4\n[[-1]\n [ 1]\n [-1]]\n\nTesting for target patterns: Set B\n\nOutput of target pattern 1\n[[1]\n [1]\n [1]\n [1]\n [1]\n [1]]\n\nOutput of target pattern 2\n[[-1]\n [-1]\n [-1]\n [-1]\n [-1]\n [-1]]\n\nOutput of target pattern 3\n[[ 1]\n [ 1]\n [-1]\n [-1]\n [ 1]\n [ 1]]\n\nOutput of target pattern 4\n[[-1]\n [-1]\n [ 1]\n [ 1]\n [-1]\n [-1]]" }, { "code": null, "e": 28824, "s": 28588, "text": "Here, for each of the input patterns, the BAM model gives the correct target patterns and for the target patterns, the model also gives the corresponding input patterns. Hence, it signifies that the BAM model is correctly implemented. " }, { "code": null, "e": 28841, "s": 28824, "text": "arorakashish0911" }, { "code": null, "e": 28856, "s": 28841, "text": "Neural Network" }, { "code": null, "e": 28873, "s": 28856, "text": "Machine Learning" }, { "code": null, "e": 28880, "s": 28873, "text": "Python" }, { "code": null, "e": 28897, "s": 28880, "text": "Machine Learning" }, { "code": null, "e": 28995, "s": 28897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29004, "s": 28995, "text": "Comments" }, { "code": null, "e": 29017, "s": 29004, "text": "Old Comments" }, { "code": null, "e": 29031, "s": 29017, "text": "Decision Tree" }, { "code": null, "e": 29055, "s": 29031, "text": "Search Algorithms in AI" }, { "code": null, "e": 29093, "s": 29055, "text": "Python | Decision tree implementation" }, { "code": null, "e": 29133, "s": 29093, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29179, "s": 29133, "text": "Elbow Method for optimal value of k in KMeans" }, { "code": null, "e": 29207, "s": 29179, "text": "Read JSON file using Python" }, { "code": null, "e": 29257, "s": 29207, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29279, "s": 29257, "text": "Python map() function" } ]
How to use Meta Tag to redirect an HTML page? - GeeksforGeeks
17 Oct, 2019 URL redirection, also called URL forwarding is a way to send users to a different URL from the one they originally requested. The three most commonly used redirects are 301, 302, and Meta Refresh.Meta Refresh Redirect is a client-side redirect. Unlike 301 and 302 redirects that happen on the webserver, Meta Refresh Redirect takes place in a web browser and instructs the web browser to go to a different web page after a specified time span.The use of Meta Refresh Redirect is deprecated or in other words, disapproved by W3C(World Wide Web Consortium), since it is a non-standard procedure of redirection, it disorients users, and it can also disrupt a browser’s history of visited pages. Syntax: <meta http-equiv = "refresh" content = "20; url = https://ide.geeksforgeeks.org"/> Example: <!DOCTYPE html><html> <head> <title>Meta Refresh Redirection</title> <meta http-equiv="refresh" content="20; url = https://ide.geeksforgeeks.org" /></head> <body> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <p style="text-align:center;"> If your browser supports Refresh, you'll be redirected to GeeksforGeeks IDE, in 20 seconds. </p></body> </html> Output:Before:After: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamr238 Picked HTML Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery DOM (Document Object Model) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24920, "s": 24892, "text": "\n17 Oct, 2019" }, { "code": null, "e": 25612, "s": 24920, "text": "URL redirection, also called URL forwarding is a way to send users to a different URL from the one they originally requested. The three most commonly used redirects are 301, 302, and Meta Refresh.Meta Refresh Redirect is a client-side redirect. Unlike 301 and 302 redirects that happen on the webserver, Meta Refresh Redirect takes place in a web browser and instructs the web browser to go to a different web page after a specified time span.The use of Meta Refresh Redirect is deprecated or in other words, disapproved by W3C(World Wide Web Consortium), since it is a non-standard procedure of redirection, it disorients users, and it can also disrupt a browser’s history of visited pages." }, { "code": null, "e": 25620, "s": 25612, "text": "Syntax:" }, { "code": null, "e": 25704, "s": 25620, "text": "<meta http-equiv = \"refresh\" content = \"20; url = https://ide.geeksforgeeks.org\"/>\n" }, { "code": null, "e": 25713, "s": 25704, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Meta Refresh Redirection</title> <meta http-equiv=\"refresh\" content=\"20; url = https://ide.geeksforgeeks.org\" /></head> <body> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <p style=\"text-align:center;\"> If your browser supports Refresh, you'll be redirected to GeeksforGeeks IDE, in 20 seconds. </p></body> </html>", "e": 26131, "s": 25713, "text": null }, { "code": null, "e": 26152, "s": 26131, "text": "Output:Before:After:" }, { "code": null, "e": 26289, "s": 26152, "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": 26301, "s": 26289, "text": "shubhamr238" }, { "code": null, "e": 26308, "s": 26301, "text": "Picked" }, { "code": null, "e": 26313, "s": 26308, "text": "HTML" }, { "code": null, "e": 26332, "s": 26313, "text": "Technical Scripter" }, { "code": null, "e": 26349, "s": 26332, "text": "Web Technologies" }, { "code": null, "e": 26376, "s": 26349, "text": "Web technologies Questions" }, { "code": null, "e": 26381, "s": 26376, "text": "HTML" }, { "code": null, "e": 26479, "s": 26381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26503, "s": 26479, "text": "REST API (Introduction)" }, { "code": null, "e": 26540, "s": 26503, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26560, "s": 26540, "text": "Angular File Upload" }, { "code": null, "e": 26589, "s": 26560, "text": "Form validation using jQuery" }, { "code": null, "e": 26617, "s": 26589, "text": "DOM (Document Object Model)" }, { "code": null, "e": 26659, "s": 26617, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26692, "s": 26659, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26735, "s": 26692, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26780, "s": 26735, "text": "Convert a string to an integer in JavaScript" } ]
Find N random points within a Circle - GeeksforGeeks
07 Feb, 2022 Given four integers N, R, X, and Y such that it represents a circle of radius R with [X, Y] as coordinates of the center. The task is to find N random points inside or on the circle. Examples: Input: R = 12, X = 3, Y = 3, N = 5 Output: (7.05, -3.36) (5.21, -7.49) (7.53, 0.19) (-2.37, 12.05) (1.45, 11.80)Input: R = 5, X = 1, Y = 1, N = 3 Output: (4.75, 1.03) (2.57, 5.21) (-1.98, -0.76) Approach: To find a random point in or on a circle we need two components, an angle(theta) and distance(D) from the center. After that Now, the point (xi, yi) can be expressed as: xi = X + D * cos(theta) yi = Y + D * sin(theta) Below is the implementation of the above approach: C++ Java Python3 C# // C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define PI 3.141592653589 // Return a random double between 0 & 1double uniform(){ return (double)rand() / RAND_MAX;} // Function to find the N random points on// the given circlevector<pair<double, double> > randPoint( int r, int x, int y, int n){ // Result vector vector<pair<double, double> > res; for (int i = 0; i < n; i++) { // Get Angle in radians double theta = 2 * PI * uniform(); // Get length from center double len = sqrt(uniform()) * r; // Add point to results. res.push_back({ x + len * cos(theta), y + len * sin(theta) }); } // Return the N points return res;} // Function to display the content of// the vector Avoid printVector( vector<pair<double, double> > A){ // Iterate over A for (pair<double, double> P : A) { // Print the N random points stored printf("(%.2lf, %.2lf)\n", P.first, P.second); }} // Driver Codeint main(){ // Given dimensions int R = 12; int X = 3; int Y = 3; int N = 5; // Function Call printVector(randPoint(R, X, Y, N)); return 0;} // Java program for the above approachimport java.util.*; class GFG{ static final double PI = 3.141592653589;static class pair{ double first, second; public pair(double first, double second) { super(); this.first = first; this.second = second; }} // Return a random double between 0 & 1static double uniform(){return Math.random();} // Function to find the N random points on// the given circlestatic Vector<pair> randPoint(int r, int x, int y, int n){ // Result vector Vector<pair> res = new Vector<pair>(); for(int i = 0; i < n; i++) { // Get Angle in radians double theta = 2 * PI * uniform(); // Get length from center double len = Math.sqrt(uniform()) * r; // Add point to results. res.add(new pair(x + len * Math.cos(theta), y + len * Math.sin(theta))); } // Return the N points return res;} // Function to display the content of// the vector Astatic void printVector(Vector<pair> A){ // Iterate over A for(pair P : A) { // Print the N random points stored System.out.printf("(%.2f, %.2f)\n", P.first, P.second); }} // Driver Codepublic static void main(String[] args){ // Given dimensions int R = 12; int X = 3; int Y = 3; int N = 5; // Function call printVector(randPoint(R, X, Y, N));}} // This code is contributed by Rajput-Ji # Python program for the above approachimport mathimport randomPI = 3.141592653589; class pair: def __init__(self, first, second): self.first = first; self.second = second; # Return a random between 0 & 1def uniform(): return random.random(); # Function to find the N random points on# the given circledef randPoint(r, x, y, n): # Result vector res = list(); for i in range(n): # Get Angle in radians theta = 2 * PI * uniform(); # Get length from center len = math.sqrt(uniform()) * r; # Add point to results. res.append(pair((x + len * math.cos(theta)), (y + len * math.sin(theta)))); # Return the N points return res; # Function to display the content of# the vector Adef printVector(A): # Iterate over A for P in A: # Print the N random points stored print("({0:.2f}".format(P.first),", ","{0:.2f})".format(P.second)); # Driver Codeif __name__ == '__main__': # Given dimensions R = 12; X = 3; Y = 3; N = 5; # Function call printVector(randPoint(R, X, Y, N)); # This code is contributed by 29AjayKumar // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ static readonly double PI = 3.141592653589;class pair{ public double first, second; public pair(double first, double second) { this.first = first; this.second = second; }} // Return a random double between 0 & 1static double uniform(){ return new Random().NextDouble();} // Function to find the N random points on// the given circlestatic List<pair> randPoint(int r, int x, int y, int n){ // Result vector List<pair> res = new List<pair>(); for(int i = 0; i < n; i++) { // Get Angle in radians double theta = 2 * PI * uniform(); // Get length from center double len = Math.Sqrt(uniform()) * r; // Add point to results. res.Add(new pair(x + len * Math.Cos(theta), y + len * Math.Sin(theta))); } // Return the N points return res;} // Function to display the content of// the vector Astatic void printList(List<pair> A){ // Iterate over A foreach(pair P in A) { // Print the N random points stored Console.Write("({0:F2}, {1:F2})\n", P.first, P.second); }} // Driver Codepublic static void Main(String[] args){ // Given dimensions int R = 12; int X = 3; int Y = 3; int N = 5; // Function call printList(randPoint(R, X, Y, N));}} // This code is contributed by 29AjayKumar (7.05, -3.36) (5.21, -7.49) (7.53, 0.19) (-2.37, 12.05) (1.45, 11.80) Time Complexity: O(N) Space Complexity: O(N) Rajput-Ji 29AjayKumar saurabh1990aror surinderdawra388 circle school-programming Geometric Randomized Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull using Divide and Conquer Algorithm Equation of circle when three points on the circle are given Circle and Lattice Points Orientation of 3 ordered points Program to find slope of a line QuickSort using Random Pivoting Shuffle a given array using Fisher–Yates shuffle Algorithm K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) Reservoir Sampling Estimating the value of Pi using Monte Carlo
[ { "code": null, "e": 25354, "s": 25326, "text": "\n07 Feb, 2022" }, { "code": null, "e": 25547, "s": 25354, "text": "Given four integers N, R, X, and Y such that it represents a circle of radius R with [X, Y] as coordinates of the center. The task is to find N random points inside or on the circle. Examples:" }, { "code": null, "e": 25742, "s": 25547, "text": "Input: R = 12, X = 3, Y = 3, N = 5 Output: (7.05, -3.36) (5.21, -7.49) (7.53, 0.19) (-2.37, 12.05) (1.45, 11.80)Input: R = 5, X = 1, Y = 1, N = 3 Output: (4.75, 1.03) (2.57, 5.21) (-1.98, -0.76)" }, { "code": null, "e": 25922, "s": 25742, "text": "Approach: To find a random point in or on a circle we need two components, an angle(theta) and distance(D) from the center. After that Now, the point (xi, yi) can be expressed as:" }, { "code": null, "e": 25970, "s": 25922, "text": "xi = X + D * cos(theta)\nyi = Y + D * sin(theta)" }, { "code": null, "e": 26021, "s": 25970, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26025, "s": 26021, "text": "C++" }, { "code": null, "e": 26030, "s": 26025, "text": "Java" }, { "code": null, "e": 26038, "s": 26030, "text": "Python3" }, { "code": null, "e": 26041, "s": 26038, "text": "C#" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define PI 3.141592653589 // Return a random double between 0 & 1double uniform(){ return (double)rand() / RAND_MAX;} // Function to find the N random points on// the given circlevector<pair<double, double> > randPoint( int r, int x, int y, int n){ // Result vector vector<pair<double, double> > res; for (int i = 0; i < n; i++) { // Get Angle in radians double theta = 2 * PI * uniform(); // Get length from center double len = sqrt(uniform()) * r; // Add point to results. res.push_back({ x + len * cos(theta), y + len * sin(theta) }); } // Return the N points return res;} // Function to display the content of// the vector Avoid printVector( vector<pair<double, double> > A){ // Iterate over A for (pair<double, double> P : A) { // Print the N random points stored printf(\"(%.2lf, %.2lf)\\n\", P.first, P.second); }} // Driver Codeint main(){ // Given dimensions int R = 12; int X = 3; int Y = 3; int N = 5; // Function Call printVector(randPoint(R, X, Y, N)); return 0;}", "e": 27257, "s": 26041, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ static final double PI = 3.141592653589;static class pair{ double first, second; public pair(double first, double second) { super(); this.first = first; this.second = second; }} // Return a random double between 0 & 1static double uniform(){return Math.random();} // Function to find the N random points on// the given circlestatic Vector<pair> randPoint(int r, int x, int y, int n){ // Result vector Vector<pair> res = new Vector<pair>(); for(int i = 0; i < n; i++) { // Get Angle in radians double theta = 2 * PI * uniform(); // Get length from center double len = Math.sqrt(uniform()) * r; // Add point to results. res.add(new pair(x + len * Math.cos(theta), y + len * Math.sin(theta))); } // Return the N points return res;} // Function to display the content of// the vector Astatic void printVector(Vector<pair> A){ // Iterate over A for(pair P : A) { // Print the N random points stored System.out.printf(\"(%.2f, %.2f)\\n\", P.first, P.second); }} // Driver Codepublic static void main(String[] args){ // Given dimensions int R = 12; int X = 3; int Y = 3; int N = 5; // Function call printVector(randPoint(R, X, Y, N));}} // This code is contributed by Rajput-Ji", "e": 28773, "s": 27257, "text": null }, { "code": "# Python program for the above approachimport mathimport randomPI = 3.141592653589; class pair: def __init__(self, first, second): self.first = first; self.second = second; # Return a random between 0 & 1def uniform(): return random.random(); # Function to find the N random points on# the given circledef randPoint(r, x, y, n): # Result vector res = list(); for i in range(n): # Get Angle in radians theta = 2 * PI * uniform(); # Get length from center len = math.sqrt(uniform()) * r; # Add point to results. res.append(pair((x + len * math.cos(theta)), (y + len * math.sin(theta)))); # Return the N points return res; # Function to display the content of# the vector Adef printVector(A): # Iterate over A for P in A: # Print the N random points stored print(\"({0:.2f}\".format(P.first),\", \",\"{0:.2f})\".format(P.second)); # Driver Codeif __name__ == '__main__': # Given dimensions R = 12; X = 3; Y = 3; N = 5; # Function call printVector(randPoint(R, X, Y, N)); # This code is contributed by 29AjayKumar", "e": 29905, "s": 28773, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ static readonly double PI = 3.141592653589;class pair{ public double first, second; public pair(double first, double second) { this.first = first; this.second = second; }} // Return a random double between 0 & 1static double uniform(){ return new Random().NextDouble();} // Function to find the N random points on// the given circlestatic List<pair> randPoint(int r, int x, int y, int n){ // Result vector List<pair> res = new List<pair>(); for(int i = 0; i < n; i++) { // Get Angle in radians double theta = 2 * PI * uniform(); // Get length from center double len = Math.Sqrt(uniform()) * r; // Add point to results. res.Add(new pair(x + len * Math.Cos(theta), y + len * Math.Sin(theta))); } // Return the N points return res;} // Function to display the content of// the vector Astatic void printList(List<pair> A){ // Iterate over A foreach(pair P in A) { // Print the N random points stored Console.Write(\"({0:F2}, {1:F2})\\n\", P.first, P.second); }} // Driver Codepublic static void Main(String[] args){ // Given dimensions int R = 12; int X = 3; int Y = 3; int N = 5; // Function call printList(randPoint(R, X, Y, N));}} // This code is contributed by 29AjayKumar", "e": 31442, "s": 29905, "text": null }, { "code": null, "e": 31512, "s": 31442, "text": "(7.05, -3.36)\n(5.21, -7.49)\n(7.53, 0.19)\n(-2.37, 12.05)\n(1.45, 11.80)" }, { "code": null, "e": 31558, "s": 31512, "text": "Time Complexity: O(N) Space Complexity: O(N) " }, { "code": null, "e": 31568, "s": 31558, "text": "Rajput-Ji" }, { "code": null, "e": 31580, "s": 31568, "text": "29AjayKumar" }, { "code": null, "e": 31596, "s": 31580, "text": "saurabh1990aror" }, { "code": null, "e": 31613, "s": 31596, "text": "surinderdawra388" }, { "code": null, "e": 31620, "s": 31613, "text": "circle" }, { "code": null, "e": 31639, "s": 31620, "text": "school-programming" }, { "code": null, "e": 31649, "s": 31639, "text": "Geometric" }, { "code": null, "e": 31660, "s": 31649, "text": "Randomized" }, { "code": null, "e": 31670, "s": 31660, "text": "Geometric" }, { "code": null, "e": 31768, "s": 31670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31777, "s": 31768, "text": "Comments" }, { "code": null, "e": 31790, "s": 31777, "text": "Old Comments" }, { "code": null, "e": 31837, "s": 31790, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 31898, "s": 31837, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 31924, "s": 31898, "text": "Circle and Lattice Points" }, { "code": null, "e": 31956, "s": 31924, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 31988, "s": 31956, "text": "Program to find slope of a line" }, { "code": null, "e": 32020, "s": 31988, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 32079, "s": 32020, "text": "Shuffle a given array using Fisher–Yates shuffle Algorithm" }, { "code": null, "e": 32158, "s": 32079, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 32177, "s": 32158, "text": "Reservoir Sampling" } ]
JupyterLab - Installing R Kernel
Project Jupyter now supports kernels of programming environments. We shall now see how to install R kernel in anaconda distribution. In Anaconda prompt window enter following command − conda install -c r r-essentials Now, from the launcher tab, choose R kernel to start a new notebook. The following is a screenshot of Jupyter notebook having R kernel − 22 Lectures 49 mins Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2793, "s": 2660, "text": "Project Jupyter now supports kernels of programming environments. We shall now see how to install R kernel in anaconda distribution." }, { "code": null, "e": 2845, "s": 2793, "text": "In Anaconda prompt window enter following command −" }, { "code": null, "e": 2878, "s": 2845, "text": "conda install -c r r-essentials\n" }, { "code": null, "e": 2947, "s": 2878, "text": "Now, from the launcher tab, choose R kernel to start a new notebook." }, { "code": null, "e": 3015, "s": 2947, "text": "The following is a screenshot of Jupyter notebook having R kernel −" }, { "code": null, "e": 3047, "s": 3015, "text": "\n 22 Lectures \n 49 mins\n" }, { "code": null, "e": 3065, "s": 3047, "text": " Bigdata Engineer" }, { "code": null, "e": 3072, "s": 3065, "text": " Print" }, { "code": null, "e": 3083, "s": 3072, "text": " Add Notes" } ]
Spring Boot Kafka Consume JSON Messages Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws This tutorial helps you to understand how to consume Kafka JSON messages from spring boot application. As part of this example, I am going to create a Kafka integrated spring boot application and publish JSON messages from Kafka producer console and read these messages from the application using Spring Boot Kakfka Listener. Spring Boot 2.1.3 RELEASE Spring Kafka Kafka 2.11 Java 8 Maven To run the application, you have to have Apache Kafka installed on your operating system. I provided a couple of articles which helps you to install Kafka on Windows and Ubuntu operating systems. Install Apache Kafka on Windows 10 Operating System Install Apache Kafka On Ubuntu Operating System After successful installation, you should have to start the zookeeper, Kafka servers to connect from spring boot application. root@work:/usr/local/kafka/bin# ./zookeeper-server-start.sh ../config/zookeeper.properties [2019-03-30 01:55:58,567] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig) [2019-03-30 01:55:58,584] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-30 01:55:58,585] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-30 01:55:58,585] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager) [2019-03-30 01:55:58,585] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain) [2019-03-30 01:55:58,640] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig) [2019-03-30 01:55:58,641] INFO Starting server (org.apache.zookeeper.server.ZooKeeperServerMain) [2019-03-30 01:55:58,725] INFO Server environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.server.ZooKeeperServer) ..... ..... root@work:/usr/local/kafka/bin# ./kafka-server-start.sh ../config/server.properties [2019-03-30 01:56:19,474] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$) [2019-03-30 01:56:20,461] INFO starting (kafka.server.KafkaServer) [2019-03-30 01:56:20,462] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer) [2019-03-30 01:56:20,523] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient) [2019-03-30 01:56:20,556] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper) [2019-03-30 01:56:20,556] INFO Client environment:host.name=work (org.apache.zookeeper.ZooKeeper) [2019-03-30 01:56:20,556] INFO Client environment:java.version=11.0.2 (org.apache.zookeeper.ZooKeeper) [2019-03-30 01:56:20,557] INFO Client environment:java.vendor=Oracle Corporation (org.apache.zookeeper.ZooKeeper) [2019-03-30 01:56:20,557] INFO Client environment:java.home=/usr/lib/jvm/java-11-oracle (org.apache.zookeeper.ZooKeeper) root@work:/usr/local/kafka/bin# ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic items-topic Created topic "items-topic". It is used to publish messages to a Kafka topic. root@work:/usr/local/kafka/bin# ./kafka-console-producer.sh --broker-list localhost:9092 --topic items-topic On the above we have created an items-topic from Kafka cli, now we are going to send some JSON messages from Kafka producer console and listen the items-topic from Spring boot application to read messages as soon as producer publishes the messages. <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> </dependencies> Representing the JSON message structure. package com.onlinetutorialspoint.model; public class Item { private int id; private String name; private String category; public Item(int id, String name, String category) { this.id = id; this.name = name; this.category = category; } public Item() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @Override public String toString() { return "Item{" + "id=" + id + ", name='" + name + '\'' + ", category='" + category + '\'' + '}'; } } @EnableKafka annotation makes the application to listen on given Kafka topic. package com.onlinetutorialspoint.config; import com.onlinetutorialspoint.model.Item; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.*; import org.springframework.kafka.support.serializer.JsonDeserializer; import org.springframework.kafka.support.serializer.JsonSerializer; import java.util.HashMap; import java.util.Map; @EnableKafka @Configuration public class KafkaConfig { @Bean public ConsumerFactory<String,Item> consumerFactory(){ Map<String,Object> config = new HashMap<>(); config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"127.0.0.1:9092"); config.put(ConsumerConfig.GROUP_ID_CONFIG,"sample-group"); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaConsumerFactory<>(config,new StringDeserializer(), new JsonDeserializer<>(Item.class)); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Item> kafkaListener(){ ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory(); factory.setConsumerFactory(consumerFactory()); return factory; } } ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG – “127.0.0.1:9092” – Registering Kafka consumer with Kafka server. Currently, I am running my Kafka server in my local machine so that it is 127.0.0.1. ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG – StringSerializer.class – tells the type of key which we are going to receive messages from a Kafka topic StringSerializer.class. ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG – JsonSerializer.class – tells the type of value which we are going to read messages from a Kafka topic JsonSerializer.class A typical service class is acting as a KafkaListener which listens on items-topic. package com.onlinetutorialspoint.service; import com.onlinetutorialspoint.model.Item; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Service; @Service public class KafkaConsumerService { @KafkaListener(topics = "items-topic", groupId = "sample-group",containerFactory = "kafkaListener") public void consume(Item item){ System.out.println("Consumed Message :"+item); } } package com.onlinetutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; @SpringBootApplication(exclude = KafkaAutoConfiguration.class) public class SpringBootKafkaConsumerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootKafkaConsumerApplication.class, args); } } . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.3.RELEASE) 2019-03-30 02:39:10.760 INFO 31760 --- [ main] c.o.SpringBootKafkaConsumerApplication : Starting SpringBootKafkaConsumerApplication on work with PID 31760 (/home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-Consumer/target/classes started by cgoka in /home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-Consumer) 2019-03-30 02:39:10.770 INFO 31760 --- [ main] c.o.SpringBootKafkaConsumerApplication : No active profile set, falling back to default profiles: default 2019-03-30 02:39:12.675 INFO 31760 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.kafka.annotation.KafkaBootstrapConfiguration' of type [org.springframework.kafka.annotation.KafkaBootstrapConfiguration$$EnhancerBySpringCGLIB$$98cbb433] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-03-30 02:39:13.870 INFO 31760 --- [ main] o.a.k.clients.consumer.ConsumerConfig : ConsumerConfig values: auto.commit.interval.ms = 5000 auto.offset.reset = latest bootstrap.servers = [127.0.0.1:9092] check.crcs = true client.id = .... .... Now you can see the published Kafka JSON message consumed by the Spring Boot application. Reading Messages from Kafka Publish JSON Messages to Kafka Topic (Spring Boot Application) Happy Learning 🙂 Sending Spring Boot Kafka JSON Message to Kafka Topic Spring Boot How to change the Tomcat to Jetty Server Spring Boot RabbitMQ Message Publishing Example How to use Spring Boot Random Port External Apache ActiveMQ Spring Boot Example Spring Boot Redis Cache Example – Redis Server How to set Spring Boot SetTimeZone Spring Boot Apache ActiveMq In Memory Example Spring Boot Hazelcast Cache Example MicroServices Spring Boot Eureka Server Example Spring Boot Kafka Producer Example Spring Boot RabbitMQ Consumer Messages Example Install Apache Kafka on Windows 10 How to install Apache Kafka on Ubuntu 18.04 Spring Boot MongoDB + Spring Data Example Sending Spring Boot Kafka JSON Message to Kafka Topic Spring Boot How to change the Tomcat to Jetty Server Spring Boot RabbitMQ Message Publishing Example How to use Spring Boot Random Port External Apache ActiveMQ Spring Boot Example Spring Boot Redis Cache Example – Redis Server How to set Spring Boot SetTimeZone Spring Boot Apache ActiveMq In Memory Example Spring Boot Hazelcast Cache Example MicroServices Spring Boot Eureka Server Example Spring Boot Kafka Producer Example Spring Boot RabbitMQ Consumer Messages Example Install Apache Kafka on Windows 10 How to install Apache Kafka on Ubuntu 18.04 Spring Boot MongoDB + Spring Data Example savita July 11, 2019 at 10:49 am - Reply Thank u so much This helped a lot Clark October 29, 2019 at 7:24 pm - Reply The code provided gives a compile error. JsonDeserializer is abstract and can not be instantiated. So the line : return new DefaultKafkaConsumerFactory(config,new StringDeserializer(), new JsonDeserializer(Item.class)); just won’t work. When I go to documentation it looks like a lot of the related classes are abstract. This makes me wonder how anybody is supposed to create a working deserializer. It’s very frustrating. Amruta June 16, 2021 at 4:42 pm - Reply this information very useful but i want insert that message into mongo db what is the next step chandrashekhar June 21, 2021 at 6:28 pm - Reply Hi Amruta, you can follow the MongoDB-spring-data article for this. Shivam March 22, 2022 at 10:31 pm - Reply Hii I tried alot but got some error ca you please share the code savita July 11, 2019 at 10:49 am - Reply Thank u so much This helped a lot Thank u so much This helped a lot Clark October 29, 2019 at 7:24 pm - Reply The code provided gives a compile error. JsonDeserializer is abstract and can not be instantiated. So the line : return new DefaultKafkaConsumerFactory(config,new StringDeserializer(), new JsonDeserializer(Item.class)); just won’t work. When I go to documentation it looks like a lot of the related classes are abstract. This makes me wonder how anybody is supposed to create a working deserializer. It’s very frustrating. The code provided gives a compile error. JsonDeserializer is abstract and can not be instantiated. So the line : return new DefaultKafkaConsumerFactory(config,new StringDeserializer(), new JsonDeserializer(Item.class)); just won’t work. When I go to documentation it looks like a lot of the related classes are abstract. This makes me wonder how anybody is supposed to create a working deserializer. It’s very frustrating. Amruta June 16, 2021 at 4:42 pm - Reply this information very useful but i want insert that message into mongo db what is the next step chandrashekhar June 21, 2021 at 6:28 pm - Reply Hi Amruta, you can follow the MongoDB-spring-data article for this. this information very useful but i want insert that message into mongo db what is the next step chandrashekhar June 21, 2021 at 6:28 pm - Reply Hi Amruta, you can follow the MongoDB-spring-data article for this. Hi Amruta, you can follow the MongoDB-spring-data article for this. Shivam March 22, 2022 at 10:31 pm - Reply Hii I tried alot but got some error ca you please share the code Hii I tried alot but got some error ca you please share the code Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 501, "s": 398, "text": "This tutorial helps you to understand how to consume Kafka JSON messages from spring boot application." }, { "code": null, "e": 724, "s": 501, "text": "As part of this example, I am going to create a Kafka integrated spring boot application and publish JSON messages from Kafka producer console and read these messages from the application using Spring Boot Kakfka Listener." }, { "code": null, "e": 750, "s": 724, "text": "Spring Boot 2.1.3 RELEASE" }, { "code": null, "e": 763, "s": 750, "text": "Spring Kafka" }, { "code": null, "e": 774, "s": 763, "text": "Kafka 2.11" }, { "code": null, "e": 781, "s": 774, "text": "Java 8" }, { "code": null, "e": 787, "s": 781, "text": "Maven" }, { "code": null, "e": 983, "s": 787, "text": "To run the application, you have to have Apache Kafka installed on your operating system. I provided a couple of articles which helps you to install Kafka on Windows and Ubuntu operating systems." }, { "code": null, "e": 1035, "s": 983, "text": "Install Apache Kafka on Windows 10 Operating System" }, { "code": null, "e": 1083, "s": 1035, "text": "Install Apache Kafka On Ubuntu Operating System" }, { "code": null, "e": 1209, "s": 1083, "text": "After successful installation, you should have to start the zookeeper, Kafka servers to connect from spring boot application." }, { "code": null, "e": 2396, "s": 1209, "text": "root@work:/usr/local/kafka/bin# ./zookeeper-server-start.sh ../config/zookeeper.properties\n[2019-03-30 01:55:58,567] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)\n[2019-03-30 01:55:58,584] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-30 01:55:58,585] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-30 01:55:58,585] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager)\n[2019-03-30 01:55:58,585] WARN Either no config or no quorum defined in config, running in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain)\n[2019-03-30 01:55:58,640] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)\n[2019-03-30 01:55:58,641] INFO Starting server (org.apache.zookeeper.server.ZooKeeperServerMain)\n[2019-03-30 01:55:58,725] INFO Server environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.server.ZooKeeperServer)\n.....\n....." }, { "code": null, "e": 3517, "s": 2396, "text": "root@work:/usr/local/kafka/bin# ./kafka-server-start.sh ../config/server.properties\n[2019-03-30 01:56:19,474] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$)\n[2019-03-30 01:56:20,461] INFO starting (kafka.server.KafkaServer)\n[2019-03-30 01:56:20,462] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer)\n[2019-03-30 01:56:20,523] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient)\n[2019-03-30 01:56:20,556] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper)\n[2019-03-30 01:56:20,556] INFO Client environment:host.name=work (org.apache.zookeeper.ZooKeeper)\n[2019-03-30 01:56:20,556] INFO Client environment:java.version=11.0.2 (org.apache.zookeeper.ZooKeeper)\n[2019-03-30 01:56:20,557] INFO Client environment:java.vendor=Oracle Corporation (org.apache.zookeeper.ZooKeeper)\n[2019-03-30 01:56:20,557] INFO Client environment:java.home=/usr/lib/jvm/java-11-oracle (org.apache.zookeeper.ZooKeeper)\n" }, { "code": null, "e": 3690, "s": 3517, "text": "root@work:/usr/local/kafka/bin# ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic items-topic\nCreated topic \"items-topic\"." }, { "code": null, "e": 3739, "s": 3690, "text": "It is used to publish messages to a Kafka topic." }, { "code": null, "e": 3849, "s": 3739, "text": "root@work:/usr/local/kafka/bin# ./kafka-console-producer.sh --broker-list localhost:9092 --topic items-topic\n" }, { "code": null, "e": 4098, "s": 3849, "text": "On the above we have created an items-topic from Kafka cli, now we are going to send some JSON messages from Kafka producer console and listen the items-topic from Spring boot application to read messages as soon as producer publishes the messages." }, { "code": null, "e": 4561, "s": 4098, "text": "<dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.kafka</groupId>\n <artifactId>spring-kafka</artifactId>\n </dependency>\n <dependency>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n <version>2.9.8</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 4602, "s": 4561, "text": "Representing the JSON message structure." }, { "code": null, "e": 5529, "s": 4602, "text": "package com.onlinetutorialspoint.model;\n\npublic class Item {\n private int id;\n private String name;\n private String category;\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public Item() {\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n\n @Override\n public String toString() {\n return \"Item{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", category='\" + category + '\\'' +\n '}';\n }\n}\n" }, { "code": null, "e": 5607, "s": 5529, "text": "@EnableKafka annotation makes the application to listen on given Kafka topic." }, { "code": null, "e": 7288, "s": 5607, "text": "package com.onlinetutorialspoint.config;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.apache.kafka.clients.consumer.ConsumerConfig;\nimport org.apache.kafka.common.serialization.StringDeserializer;\nimport org.apache.kafka.common.serialization.StringSerializer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.kafka.annotation.EnableKafka;\nimport org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;\nimport org.springframework.kafka.core.*;\nimport org.springframework.kafka.support.serializer.JsonDeserializer;\nimport org.springframework.kafka.support.serializer.JsonSerializer;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n@EnableKafka\n@Configuration\npublic class KafkaConfig {\n\n @Bean\n public ConsumerFactory<String,Item> consumerFactory(){\n Map<String,Object> config = new HashMap<>();\n config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,\"127.0.0.1:9092\");\n config.put(ConsumerConfig.GROUP_ID_CONFIG,\"sample-group\");\n config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringSerializer.class);\n config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonSerializer.class);\n return new DefaultKafkaConsumerFactory<>(config,new StringDeserializer(),\n new JsonDeserializer<>(Item.class));\n }\n\n @Bean\n public ConcurrentKafkaListenerContainerFactory<String, Item> kafkaListener(){\n ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory();\n factory.setConsumerFactory(consumerFactory());\n return factory;\n }\n}\n" }, { "code": null, "e": 7480, "s": 7288, "text": "ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG – “127.0.0.1:9092” – Registering Kafka consumer with Kafka server. Currently, I am running my Kafka server in my local machine so that it is 127.0.0.1." }, { "code": null, "e": 7656, "s": 7480, "text": "ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG – StringSerializer.class – tells the type of key which we are going to receive messages from a Kafka topic StringSerializer.class." }, { "code": null, "e": 7828, "s": 7656, "text": "ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG – JsonSerializer.class – tells the type of value which we are going to read messages from a Kafka topic JsonSerializer.class" }, { "code": null, "e": 7911, "s": 7828, "text": "A typical service class is acting as a KafkaListener which listens on items-topic." }, { "code": null, "e": 8355, "s": 7911, "text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.kafka.annotation.KafkaListener;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class KafkaConsumerService {\n\n @KafkaListener(topics = \"items-topic\", groupId = \"sample-group\",containerFactory = \"kafkaListener\")\n public void consume(Item item){\n System.out.println(\"Consumed Message :\"+item);\n }\n}\n" }, { "code": null, "e": 8827, "s": 8355, "text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;\n\n@SpringBootApplication(exclude = KafkaAutoConfiguration.class)\npublic class SpringBootKafkaConsumerApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootKafkaConsumerApplication.class, args);\n }\n\n}\n" }, { "code": null, "e": 10291, "s": 8827, "text": " . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.1.3.RELEASE)\n\n2019-03-30 02:39:10.760 INFO 31760 --- [ main] c.o.SpringBootKafkaConsumerApplication : Starting SpringBootKafkaConsumerApplication on work with PID 31760 (/home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-Consumer/target/classes started by cgoka in /home/cgoka/Documents/Work/Spring_Examples/SpringBoot-Kafka-Consumer)\n2019-03-30 02:39:10.770 INFO 31760 --- [ main] c.o.SpringBootKafkaConsumerApplication : No active profile set, falling back to default profiles: default\n2019-03-30 02:39:12.675 INFO 31760 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.kafka.annotation.KafkaBootstrapConfiguration' of type [org.springframework.kafka.annotation.KafkaBootstrapConfiguration$$EnhancerBySpringCGLIB$$98cbb433] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)\n2019-03-30 02:39:13.870 INFO 31760 --- [ main] o.a.k.clients.consumer.ConsumerConfig : ConsumerConfig values: \n auto.commit.interval.ms = 5000\n auto.offset.reset = latest\n bootstrap.servers = [127.0.0.1:9092]\n check.crcs = true\n client.id = \n....\n...." }, { "code": null, "e": 10381, "s": 10291, "text": "Now you can see the published Kafka JSON message consumed by the Spring Boot application." }, { "code": null, "e": 10409, "s": 10381, "text": "Reading Messages from Kafka" }, { "code": null, "e": 10472, "s": 10409, "text": "Publish JSON Messages to Kafka Topic (Spring Boot Application)" }, { "code": null, "e": 10489, "s": 10472, "text": "Happy Learning 🙂" }, { "code": null, "e": 11141, "s": 10489, "text": "\nSending Spring Boot Kafka JSON Message to Kafka Topic\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot RabbitMQ Message Publishing Example\nHow to use Spring Boot Random Port\nExternal Apache ActiveMQ Spring Boot Example\nSpring Boot Redis Cache Example – Redis Server\nHow to set Spring Boot SetTimeZone\nSpring Boot Apache ActiveMq In Memory Example\nSpring Boot Hazelcast Cache Example\nMicroServices Spring Boot Eureka Server Example\nSpring Boot Kafka Producer Example\nSpring Boot RabbitMQ Consumer Messages Example\nInstall Apache Kafka on Windows 10\nHow to install Apache Kafka on Ubuntu 18.04\nSpring Boot MongoDB + Spring Data Example\n" }, { "code": null, "e": 11195, "s": 11141, "text": "Sending Spring Boot Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 11248, "s": 11195, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 11296, "s": 11248, "text": "Spring Boot RabbitMQ Message Publishing Example" }, { "code": null, "e": 11331, "s": 11296, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 11376, "s": 11331, "text": "External Apache ActiveMQ Spring Boot Example" }, { "code": null, "e": 11423, "s": 11376, "text": "Spring Boot Redis Cache Example – Redis Server" }, { "code": null, "e": 11458, "s": 11423, "text": "How to set Spring Boot SetTimeZone" }, { "code": null, "e": 11504, "s": 11458, "text": "Spring Boot Apache ActiveMq In Memory Example" }, { "code": null, "e": 11540, "s": 11504, "text": "Spring Boot Hazelcast Cache Example" }, { "code": null, "e": 11588, "s": 11540, "text": "MicroServices Spring Boot Eureka Server Example" }, { "code": null, "e": 11623, "s": 11588, "text": "Spring Boot Kafka Producer Example" }, { "code": null, "e": 11670, "s": 11623, "text": "Spring Boot RabbitMQ Consumer Messages Example" }, { "code": null, "e": 11705, "s": 11670, "text": "Install Apache Kafka on Windows 10" }, { "code": null, "e": 11749, "s": 11705, "text": "How to install Apache Kafka on Ubuntu 18.04" }, { "code": null, "e": 11791, "s": 11749, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 12757, "s": 11791, "text": "\n\n\n\n\n\nsavita\nJuly 11, 2019 at 10:49 am - Reply \n\nThank u so much This helped a lot\n\n\n\n\n\n\n\n\n\nClark\nOctober 29, 2019 at 7:24 pm - Reply \n\nThe code provided gives a compile error. JsonDeserializer is abstract and can not be instantiated. So the line : \nreturn new DefaultKafkaConsumerFactory(config,new StringDeserializer(),\nnew JsonDeserializer(Item.class));\njust won’t work. \nWhen I go to documentation it looks like a lot of the related classes are abstract. This makes me wonder how anybody is supposed to create a working deserializer. It’s very frustrating.\n\n\n\n\n\n\n\n\n\nAmruta\nJune 16, 2021 at 4:42 pm - Reply \n\nthis information very useful but i want insert that message into mongo db what is the next step\n\n\n\n\n\n\n\n\n\nchandrashekhar\nJune 21, 2021 at 6:28 pm - Reply \n\nHi Amruta,\nyou can follow the MongoDB-spring-data article for this.\n\n\n\n\n\n\n\n\n\n\n\nShivam\nMarch 22, 2022 at 10:31 pm - Reply \n\nHii I tried alot but got some error ca you please share the code\n\n\n\n\n" }, { "code": null, "e": 12843, "s": 12757, "text": "\n\n\n\n\nsavita\nJuly 11, 2019 at 10:49 am - Reply \n\nThank u so much This helped a lot\n\n\n\n" }, { "code": null, "e": 12877, "s": 12843, "text": "Thank u so much This helped a lot" }, { "code": null, "e": 13361, "s": 12877, "text": "\n\n\n\n\nClark\nOctober 29, 2019 at 7:24 pm - Reply \n\nThe code provided gives a compile error. JsonDeserializer is abstract and can not be instantiated. So the line : \nreturn new DefaultKafkaConsumerFactory(config,new StringDeserializer(),\nnew JsonDeserializer(Item.class));\njust won’t work. \nWhen I go to documentation it looks like a lot of the related classes are abstract. This makes me wonder how anybody is supposed to create a working deserializer. It’s very frustrating.\n\n\n\n" }, { "code": null, "e": 13478, "s": 13361, "text": "The code provided gives a compile error. JsonDeserializer is abstract and can not be instantiated. So the line : " }, { "code": null, "e": 13585, "s": 13478, "text": "return new DefaultKafkaConsumerFactory(config,new StringDeserializer(),\nnew JsonDeserializer(Item.class));" }, { "code": null, "e": 13604, "s": 13585, "text": "just won’t work. " }, { "code": null, "e": 13792, "s": 13604, "text": "When I go to documentation it looks like a lot of the related classes are abstract. This makes me wonder how anybody is supposed to create a working deserializer. It’s very frustrating." }, { "code": null, "e": 14068, "s": 13792, "text": "\n\n\n\n\nAmruta\nJune 16, 2021 at 4:42 pm - Reply \n\nthis information very useful but i want insert that message into mongo db what is the next step\n\n\n\n\n\n\n\n\n\nchandrashekhar\nJune 21, 2021 at 6:28 pm - Reply \n\nHi Amruta,\nyou can follow the MongoDB-spring-data article for this.\n\n\n\n\n\n" }, { "code": null, "e": 14164, "s": 14068, "text": "this information very useful but i want insert that message into mongo db what is the next step" }, { "code": null, "e": 14291, "s": 14164, "text": "\n\n\n\n\nchandrashekhar\nJune 21, 2021 at 6:28 pm - Reply \n\nHi Amruta,\nyou can follow the MongoDB-spring-data article for this.\n\n\n\n" }, { "code": null, "e": 14302, "s": 14291, "text": "Hi Amruta," }, { "code": null, "e": 14359, "s": 14302, "text": "you can follow the MongoDB-spring-data article for this." }, { "code": null, "e": 14477, "s": 14359, "text": "\n\n\n\n\nShivam\nMarch 22, 2022 at 10:31 pm - Reply \n\nHii I tried alot but got some error ca you please share the code\n\n\n\n" }, { "code": null, "e": 14542, "s": 14477, "text": "Hii I tried alot but got some error ca you please share the code" }, { "code": null, "e": 14548, "s": 14546, "text": "Δ" }, { "code": null, "e": 14575, "s": 14548, "text": " Spring Boot – Hello World" }, { "code": null, "e": 14602, "s": 14575, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 14636, "s": 14602, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 14677, "s": 14636, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 14722, "s": 14677, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 14760, "s": 14722, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 14794, "s": 14760, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 14825, "s": 14794, "text": " Spring Boot – Properties File" }, { "code": null, "e": 14859, "s": 14825, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 14892, "s": 14859, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 14925, "s": 14892, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 14965, "s": 14925, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 14990, "s": 14965, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 15021, "s": 14990, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 15045, "s": 15021, "text": " Spring Boot – Actuator" }, { "code": null, "e": 15091, "s": 15045, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 15114, "s": 15091, "text": " Spring Boot – Swagger" }, { "code": null, "e": 15141, "s": 15114, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 15187, "s": 15141, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 15227, "s": 15187, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 15256, "s": 15227, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 15290, "s": 15256, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 15320, "s": 15290, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 15356, "s": 15320, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 15389, "s": 15356, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 15422, "s": 15389, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 15466, "s": 15422, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 15500, "s": 15466, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 15532, "s": 15500, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 15560, "s": 15532, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 15591, "s": 15560, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 15632, "s": 15591, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 15666, "s": 15632, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 15691, "s": 15666, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 15725, "s": 15691, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 15761, "s": 15725, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 15807, "s": 15761, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 15858, "s": 15807, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 15900, "s": 15858, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 15931, "s": 15900, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 15954, "s": 15931, "text": " Spring Boot – EhCache" }, { "code": null, "e": 15984, "s": 15954, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 16014, "s": 15984, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 16063, "s": 16014, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 16097, "s": 16063, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 16130, "s": 16097, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 16159, "s": 16130, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 16191, "s": 16159, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 16228, "s": 16191, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 16257, "s": 16228, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 16286, "s": 16257, "text": " Spring Boot – MockMvc JUnit" } ]
ANOVA and the Bonferroni Correction | by Michael Grogan | Towards Data Science
Performing a hypothesis test comes with the risk of obtaining either a Type 1 or Type 2 error. Type 1 error: Rejecting a true null hypothesis Type 2 error: Accepting a false null hypothesis When analysing different groups, a one-way ANOVA can tell us if there is a statistically significant difference between those groups. However, it cannot tell us which group is different from another. Moreover, when performing multiple hypothesis tests at once, the probability of obtaining a Type 1 error increases. In statistics, this is known as the family-wise error rate, which measures the probability that a Type 1 error will be made across any particular hypothesis test. It is calculated as follows: 1 — (1-α)^n where: α = the significance level for a given hypothesis test n = total number of tests For instance, if we are using a significance level of 0.05 and we conduct three hypothesis tests, the probability of making a Type 1 error increases to 14.26%, i.e. 1-(1–0.05)3 = 0.1426. To guard against such a Type 1 error (and also to concurrently conduct pairwise t-tests between each group), a Bonferroni correction is used whereby the significance level is adjusted to reduce the probability of committing a Type 1 error. However, a downside of this test is that the probability of committing a Type 2 error also increases. For this example, let us consider a hotel that has collected data on the average daily rate for each of its customers, i.e. the average price that the customer pays per day to stay at the hotel. The hotel also has information on the distribution channel pertaining to each customer, i.e. Corporate, Direct, and TA/TO. The goal of the analysis is to determine the differences across means in ADR for each of these three groups. The original data was sourced from Antonio, Almeida and Nunes (2019) as referenced below, and 100 samples from each distribution channel were randomly selected. Let’s start by conducting a one-way ANOVA in R. > model <- aov(ADR ~ DistributionChannel, data = data)> summary(model) Df Sum Sq Mean Sq F value Pr(>F) DistributionChannel 2 236636 118318 33.33 8.76e-14 ***Residuals 297 1054469 3550 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 When analysing the results, we can see that the p-value is highly significant and virtually zero. This means we reject the null hypothesis that no significant differences exist between each group. However, we can see that the ANOVA test merely indicates that a difference exists between the three distribution channels — it does not tell us anything about the nature of that difference. Before performing the pairwise p-test, here is a boxplot illustrating the differences across the three groups: From a visual glance, we can see that the mean ADR across the Direct and TA/TO distribution channels is higher than that of Corporate, and the dispersion across ADR is significantly greater. However, we would like to analyse this in more detail using a pairwise t-test with a Bonferroni correction. > pairwise.t.test(data$ADR, data$DistributionChannel, p.adjust.method="bonferroni")Pairwise comparisons using t tests with pooled SDdata: data$ADR and data$DistributionChannel Corporate DirectDirect 4.6e-11 - TA/TO 2.4e-11 1P value adjustment method: bonferroni When looking at the adjusted p-values, we can see that the differences between Corporate and Direct, and Corporate and TA/TO are highly significant as the p-values are near zero. Given that the Bonferroni correction has been used to guard against Type 1 errors, we can be more confident in rejecting the null hypothesis of no significant differences across groups. That said, we can see that there exists a p-value of 1 between the Direct and TA/TO groups, implying that we cannot reject the null hypothesis of no significant differences between these two groups. This has been a short introduction to pairwise t-tests and specifically, the use of the Bonferroni correction to guard against Type 1 errors. You have seen: The limitations of using a one-way ANOVA How to calculate the family-wise error rate How to conduct a pairwise t-test using a Bonferroni correction and interpret the results Many thanks for your time, and any questions or feedback are greatly appreciated. Antonio, Almeida, Nunes (2019). Hotel Booking Demand Dataset Statology: How to Perform a Bonferroni Correction in R Statology: What is the Family-wise Error Rate? Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice. The findings and interpretations in this article are those of the author and are not endorsed by or affiliated with any third-party mentioned in this article. The author has no relationship with any third parties mentioned in this article.
[ { "code": null, "e": 267, "s": 172, "text": "Performing a hypothesis test comes with the risk of obtaining either a Type 1 or Type 2 error." }, { "code": null, "e": 314, "s": 267, "text": "Type 1 error: Rejecting a true null hypothesis" }, { "code": null, "e": 362, "s": 314, "text": "Type 2 error: Accepting a false null hypothesis" }, { "code": null, "e": 496, "s": 362, "text": "When analysing different groups, a one-way ANOVA can tell us if there is a statistically significant difference between those groups." }, { "code": null, "e": 678, "s": 496, "text": "However, it cannot tell us which group is different from another. Moreover, when performing multiple hypothesis tests at once, the probability of obtaining a Type 1 error increases." }, { "code": null, "e": 841, "s": 678, "text": "In statistics, this is known as the family-wise error rate, which measures the probability that a Type 1 error will be made across any particular hypothesis test." }, { "code": null, "e": 870, "s": 841, "text": "It is calculated as follows:" }, { "code": null, "e": 882, "s": 870, "text": "1 — (1-α)^n" }, { "code": null, "e": 889, "s": 882, "text": "where:" }, { "code": null, "e": 944, "s": 889, "text": "α = the significance level for a given hypothesis test" }, { "code": null, "e": 970, "s": 944, "text": "n = total number of tests" }, { "code": null, "e": 1157, "s": 970, "text": "For instance, if we are using a significance level of 0.05 and we conduct three hypothesis tests, the probability of making a Type 1 error increases to 14.26%, i.e. 1-(1–0.05)3 = 0.1426." }, { "code": null, "e": 1499, "s": 1157, "text": "To guard against such a Type 1 error (and also to concurrently conduct pairwise t-tests between each group), a Bonferroni correction is used whereby the significance level is adjusted to reduce the probability of committing a Type 1 error. However, a downside of this test is that the probability of committing a Type 2 error also increases." }, { "code": null, "e": 1694, "s": 1499, "text": "For this example, let us consider a hotel that has collected data on the average daily rate for each of its customers, i.e. the average price that the customer pays per day to stay at the hotel." }, { "code": null, "e": 2087, "s": 1694, "text": "The hotel also has information on the distribution channel pertaining to each customer, i.e. Corporate, Direct, and TA/TO. The goal of the analysis is to determine the differences across means in ADR for each of these three groups. The original data was sourced from Antonio, Almeida and Nunes (2019) as referenced below, and 100 samples from each distribution channel were randomly selected." }, { "code": null, "e": 2135, "s": 2087, "text": "Let’s start by conducting a one-way ANOVA in R." }, { "code": null, "e": 2451, "s": 2135, "text": "> model <- aov(ADR ~ DistributionChannel, data = data)> summary(model) Df Sum Sq Mean Sq F value Pr(>F) DistributionChannel 2 236636 118318 33.33 8.76e-14 ***Residuals 297 1054469 3550 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1" }, { "code": null, "e": 2648, "s": 2451, "text": "When analysing the results, we can see that the p-value is highly significant and virtually zero. This means we reject the null hypothesis that no significant differences exist between each group." }, { "code": null, "e": 2838, "s": 2648, "text": "However, we can see that the ANOVA test merely indicates that a difference exists between the three distribution channels — it does not tell us anything about the nature of that difference." }, { "code": null, "e": 2949, "s": 2838, "text": "Before performing the pairwise p-test, here is a boxplot illustrating the differences across the three groups:" }, { "code": null, "e": 3140, "s": 2949, "text": "From a visual glance, we can see that the mean ADR across the Direct and TA/TO distribution channels is higher than that of Corporate, and the dispersion across ADR is significantly greater." }, { "code": null, "e": 3248, "s": 3140, "text": "However, we would like to analyse this in more detail using a pairwise t-test with a Bonferroni correction." }, { "code": null, "e": 3526, "s": 3248, "text": "> pairwise.t.test(data$ADR, data$DistributionChannel, p.adjust.method=\"bonferroni\")Pairwise comparisons using t tests with pooled SDdata: data$ADR and data$DistributionChannel Corporate DirectDirect 4.6e-11 - TA/TO 2.4e-11 1P value adjustment method: bonferroni" }, { "code": null, "e": 3891, "s": 3526, "text": "When looking at the adjusted p-values, we can see that the differences between Corporate and Direct, and Corporate and TA/TO are highly significant as the p-values are near zero. Given that the Bonferroni correction has been used to guard against Type 1 errors, we can be more confident in rejecting the null hypothesis of no significant differences across groups." }, { "code": null, "e": 4090, "s": 3891, "text": "That said, we can see that there exists a p-value of 1 between the Direct and TA/TO groups, implying that we cannot reject the null hypothesis of no significant differences between these two groups." }, { "code": null, "e": 4247, "s": 4090, "text": "This has been a short introduction to pairwise t-tests and specifically, the use of the Bonferroni correction to guard against Type 1 errors. You have seen:" }, { "code": null, "e": 4288, "s": 4247, "text": "The limitations of using a one-way ANOVA" }, { "code": null, "e": 4332, "s": 4288, "text": "How to calculate the family-wise error rate" }, { "code": null, "e": 4421, "s": 4332, "text": "How to conduct a pairwise t-test using a Bonferroni correction and interpret the results" }, { "code": null, "e": 4503, "s": 4421, "text": "Many thanks for your time, and any questions or feedback are greatly appreciated." }, { "code": null, "e": 4564, "s": 4503, "text": "Antonio, Almeida, Nunes (2019). Hotel Booking Demand Dataset" }, { "code": null, "e": 4619, "s": 4564, "text": "Statology: How to Perform a Bonferroni Correction in R" }, { "code": null, "e": 4666, "s": 4619, "text": "Statology: What is the Family-wise Error Rate?" } ]
Java sql.Timestamp valueOf() method with example
The valueOf() method of the java.sql.Timestamp class accepts a String value representing a time stamp in JDBC escape format and converts the given String value into Timestamp object. Timestamp timeStamp = Time.valueOf("timeStamp_string"); Let us create a table with name dispatches_data in MySQL database using CREATE statement as shown below: CREATE TABLE dispatches_data( ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchTimeStamp timestamp, Price INT, Location VARCHAR(255)); Now, we will insert 5 records in dispatches_data table using INSERT statements: insert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad'); insert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam'); insert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada'); insert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai'); insert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa'); Following JDBC program establishes connection with the database and inserts a new record in to the dispatches_data table. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; public class Timestamp_valueOf { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values to a table String query = "INSERT INTO dispatches_data VALUES (?, ?, ?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Watch"); pstmt.setString(2, "Rajan"); Timestamp timestamp = Timestamp.valueOf("2019-04-21 14:17:02.0"); pstmt.setTimestamp(3, timestamp); pstmt.setInt(4, 4000); pstmt.setString(5, "Chennai"); pstmt.execute(); //Retrieving data Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from dispatches_data"); while(rs.next()) { System.out.print("Name: "+rs.getString("ProductName")+", "); System.out.print("Customer Name: "+rs.getString("CustomerName")+", "); System.out.print("Dispatch Time Stamp: "+rs.getDate("DispatchTimeStamp")+", "); System.out.print("Price: "+rs.getInt("Price")+", "); System.out.print("Location: "+rs.getString("Location")); System.out.println(); } } } Here, in this program we are taking the time stamp value in String format and converting it into the java.util.Time object using the valueOf() method. Connection established...... Name: Key-Board, Customer Name: Raja, Dispatch Time Stamp: 2019-05-04, Price: 7000, Location: Hyderabad Name: Earphones, Customer Name: Roja, Dispatch Time Stamp: 2019-06-26, Price: 2000, Location: Vishakhapatnam Name: Mouse, Customer Name: Puja, Dispatch Time Stamp: 2019-12-07, Price: 3000, Location: Vijayawada Name: Mobile, Customer Name: Vanaja, Dispatch Time Stamp: 2018-03-21, Price: 9000, Location: Chennai Name: Headset, Customer Name: Jalaja, Dispatch Time Stamp: 2018-12-30, Price: 6000, Location: Goa Name: Watch, Customer Name: Rajan, Dispatch Time Stamp: 2019-04-21, Price: 4000, Location: Chennai
[ { "code": null, "e": 1245, "s": 1062, "text": "The valueOf() method of the java.sql.Timestamp class accepts a String value representing a time stamp in JDBC escape format and converts the given String value into Timestamp object." }, { "code": null, "e": 1301, "s": 1245, "text": "Timestamp timeStamp = Time.valueOf(\"timeStamp_string\");" }, { "code": null, "e": 1406, "s": 1301, "text": "Let us create a table with name dispatches_data in MySQL database using CREATE statement as shown below:" }, { "code": null, "e": 1568, "s": 1406, "text": "CREATE TABLE dispatches_data(\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchTimeStamp timestamp,\n Price INT,\n Location VARCHAR(255));" }, { "code": null, "e": 1648, "s": 1568, "text": "Now, we will insert 5 records in dispatches_data table using INSERT statements:" }, { "code": null, "e": 2209, "s": 1648, "text": "insert into dispatches_data values('Key-Board', 'Raja', TIMESTAMP('2019-05-04', '15:02:45'), 7000, 'Hyderabad');\ninsert into dispatches_data values('Earphones', 'Roja', TIMESTAMP('2019-06-26', '14:13:12'), 2000, 'Vishakhapatnam');\ninsert into dispatches_data values('Mouse', 'Puja', TIMESTAMP('2019-12-07', '07:50:37'), 3000, 'Vijayawada');\ninsert into dispatches_data values('Mobile', 'Vanaja' , TIMESTAMP ('2018-03-21', '16:00:45'), 9000, 'Chennai');\ninsert into dispatches_data values('Headset', 'Jalaja' , TIMESTAMP('2018-12-30', '10:49:27'), 6000, 'Goa');" }, { "code": null, "e": 2331, "s": 2209, "text": "Following JDBC program establishes connection with the database and inserts a new record in to the dispatches_data table." }, { "code": null, "e": 3985, "s": 2331, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.sql.Timestamp;\npublic class Timestamp_valueOf {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Inserting values to a table\n String query = \"INSERT INTO dispatches_data VALUES (?, ?, ?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Watch\");\n pstmt.setString(2, \"Rajan\");\n Timestamp timestamp = Timestamp.valueOf(\"2019-04-21 14:17:02.0\");\n pstmt.setTimestamp(3, timestamp);\n pstmt.setInt(4, 4000);\n pstmt.setString(5, \"Chennai\");\n pstmt.execute();\n //Retrieving data\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from dispatches_data\");\n while(rs.next()) {\n System.out.print(\"Name: \"+rs.getString(\"ProductName\")+\", \");\n System.out.print(\"Customer Name: \"+rs.getString(\"CustomerName\")+\", \");\n System.out.print(\"Dispatch Time Stamp: \"+rs.getDate(\"DispatchTimeStamp\")+\", \");\n System.out.print(\"Price: \"+rs.getInt(\"Price\")+\", \");\n System.out.print(\"Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 4136, "s": 3985, "text": "Here, in this program we are taking the time stamp value in String format and converting it into the java.util.Time object using the valueOf() method." }, { "code": null, "e": 4777, "s": 4136, "text": "Connection established......\nName: Key-Board, Customer Name: Raja, Dispatch Time Stamp: 2019-05-04, Price: 7000, Location: Hyderabad\nName: Earphones, Customer Name: Roja, Dispatch Time Stamp: 2019-06-26, Price: 2000, Location: Vishakhapatnam\nName: Mouse, Customer Name: Puja, Dispatch Time Stamp: 2019-12-07, Price: 3000, Location: Vijayawada\nName: Mobile, Customer Name: Vanaja, Dispatch Time Stamp: 2018-03-21, Price: 9000, Location: Chennai\nName: Headset, Customer Name: Jalaja, Dispatch Time Stamp: 2018-12-30, Price: 6000, Location: Goa\nName: Watch, Customer Name: Rajan, Dispatch Time Stamp: 2019-04-21, Price: 4000, Location: Chennai" } ]
A Single Line of Python Code Scraping Dataset from Webpages | by Christopher Tao | Towards Data Science
No matter what level of data science/analytics skills we have, you cannot do anything without datasets. Indeed, there are many open-source datasets such as Kaggle and Data.world. However, they are more suitable to be used for exercises and learning purposes, but may not satisfy our general needs. Usually, data scientists/analysts may have more or less web scraping skills, so it will be much easier to get datasets whenever you saw on the websites. After scraping the content from the websites, a series of transforming, extracting and cleansing manipulations will help us to get the clean dataset for the next step. This is one of the typical usages of Python because there are many excellent web scraping libraries available in Python such as Scrapy and Beautiful Soup. However, learning these web scraping libraries is not going to be that easy. Also, for those who do not have web development backgrounds, which is probably not a common skill for data scientists/analysts, it might be even more difficult to understand and nail the concepts such as HTML DOM and XPath. However, in this article, I will introduce a much easier way of downloading datasets from websites. You will find that you can even use Pandas to do all the work! The first example is the COVID-19 New Cases dataset. It turns out there are many publicly available data sources such as the government websites which will publish this. However, I just want to use this as an example, as I found that this is a very good and typical example. Today, when I scan news from “The Age” (A popular media of Australia) website, I found that there is a bar chart showing daily new confirmed cases in Australia (see screenshot below). What if I want to get their data? Let’s find its API endpoint! Most of the popular web browsers provide their developer consoles now. We will use the console to do this job. Here are some shortcuts to call out the console from your browsers: Google Chrome: Ctrl + Shift + I Firefox: Ctrl + Shift + K Microsoft Edge: F12 Here I will use Google Chrome for demonstration. But don’t worry, most of the browsers have very similar developer consoles. I believe you will be able to figure out where are the features. Once the console appears, go to the “Network” tab. We are looking for an API endpoint, so it would be caught as an “XHR” request if it is available. So, let’s select the XHR filter. XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser’s JavaScript environment. Particularly, retrieval of data from XHR for the purpose of continually modifying a loaded web page is the underlying concept of Ajax design. Despite the name, XHR can be used with protocols other than HTTP and data can be in the form of not only XML, but also JSON, HTML or plain text. [1] Sometimes, the webpage may have some JavaScripts running in the background to do some scheduled jobs and the browser will catch them all. If you want to have a cleaner list of caught requests, the best approach is to Make sure the “recording” button is enabled Refresh the webpage Stop “recording” when you see the data related content has already been fully rendered on the webpage Now, you will have a list of requests in the developer console. OK. This one is very obvious. We can see that there is a request to have its name called “covid-19-new-cases-json.json...”. That must be it! Go to the “Headers” tab, you will see the detail of this request. The most important thing is the URL. Now, let’s just open that URL as another browser tab to see what happen. Cool! This is the API endpoint we’re looking for. How to consume it? Extremely easy! I believe you must use Pandas Dataframe if you are a data scientist or data analyst. Just one line of Python code, you got everything directly into Pandas Dataframe. df = pd.read_json('https://www.theage.com.au/interactive/2020/coronavirus/data-feeder/covid-19-new-cases-json.json?v=3') Not all websites are using REST API endpoints so that I wouldn’t say this is a universal approach. However, you’ll find that there are a considerable number of websites using that. Let’s just take one more example, the IKEA website. Let’s say you want to get all the beds from IKEA together with the product details to perform some analysis. Here is the request that my browser caught from the URL (https://www.ikea.com/au/en/cat/beds-bm003/). This one is more interesting. Please note that it says that the “product count” is 220, but the “product window” only give 24 of them. If you pay attention to the page, it turns out only 24 products will be listed on the page, and a “load more” button is provided if you want to keep browsing more. Well, this is very common in Web Development to save bandwidth and server resources. But does that mean we have to give it up? Absolutely no. Let’s have a look at the request URL: Have you seen that there is a property called “size”? It exactly equals 24, which is the page size. Let’s try to change that to size=220, and send the request using the Python built-in library requests. import requestsjson = requests.get( 'https://sik.search.blue.cdtapps.com/au/en/product-list-page?category=bm003&sort=RELEVANCE&size=220&c=plp&v=20200430').json()['productListPage']['productWindow'] The reason why we cannot directly use Pandas this time is that the product list is not at the root level of the JSON object. Instead, it is at root.productListPage.productWindow. After that, the request will convert the JSON object to a Python dictionary, so we can read it using Pandas now. df = pd.DataFrame.from_dict(json) Isn’t that quick and easy? You don’t have to learn those web scraping libraries. But, of course, this approach is not going to be effective for all the websites, and that is why the web scraping libraries are still necessary. However, when there is an available API endpoint on the website, why not just find it and directly use it? medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above) [1] Wikipedia. XMLHttpRequest. https://en.wikipedia.org/wiki/XMLHttpRequest
[ { "code": null, "e": 276, "s": 172, "text": "No matter what level of data science/analytics skills we have, you cannot do anything without datasets." }, { "code": null, "e": 470, "s": 276, "text": "Indeed, there are many open-source datasets such as Kaggle and Data.world. However, they are more suitable to be used for exercises and learning purposes, but may not satisfy our general needs." }, { "code": null, "e": 946, "s": 470, "text": "Usually, data scientists/analysts may have more or less web scraping skills, so it will be much easier to get datasets whenever you saw on the websites. After scraping the content from the websites, a series of transforming, extracting and cleansing manipulations will help us to get the clean dataset for the next step. This is one of the typical usages of Python because there are many excellent web scraping libraries available in Python such as Scrapy and Beautiful Soup." }, { "code": null, "e": 1247, "s": 946, "text": "However, learning these web scraping libraries is not going to be that easy. Also, for those who do not have web development backgrounds, which is probably not a common skill for data scientists/analysts, it might be even more difficult to understand and nail the concepts such as HTML DOM and XPath." }, { "code": null, "e": 1410, "s": 1247, "text": "However, in this article, I will introduce a much easier way of downloading datasets from websites. You will find that you can even use Pandas to do all the work!" }, { "code": null, "e": 1685, "s": 1410, "text": "The first example is the COVID-19 New Cases dataset. It turns out there are many publicly available data sources such as the government websites which will publish this. However, I just want to use this as an example, as I found that this is a very good and typical example." }, { "code": null, "e": 1869, "s": 1685, "text": "Today, when I scan news from “The Age” (A popular media of Australia) website, I found that there is a bar chart showing daily new confirmed cases in Australia (see screenshot below)." }, { "code": null, "e": 1932, "s": 1869, "text": "What if I want to get their data? Let’s find its API endpoint!" }, { "code": null, "e": 2111, "s": 1932, "text": "Most of the popular web browsers provide their developer consoles now. We will use the console to do this job. Here are some shortcuts to call out the console from your browsers:" }, { "code": null, "e": 2143, "s": 2111, "text": "Google Chrome: Ctrl + Shift + I" }, { "code": null, "e": 2169, "s": 2143, "text": "Firefox: Ctrl + Shift + K" }, { "code": null, "e": 2189, "s": 2169, "text": "Microsoft Edge: F12" }, { "code": null, "e": 2379, "s": 2189, "text": "Here I will use Google Chrome for demonstration. But don’t worry, most of the browsers have very similar developer consoles. I believe you will be able to figure out where are the features." }, { "code": null, "e": 2561, "s": 2379, "text": "Once the console appears, go to the “Network” tab. We are looking for an API endpoint, so it would be caught as an “XHR” request if it is available. So, let’s select the XHR filter." }, { "code": null, "e": 3040, "s": 2561, "text": "XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser’s JavaScript environment. Particularly, retrieval of data from XHR for the purpose of continually modifying a loaded web page is the underlying concept of Ajax design. Despite the name, XHR can be used with protocols other than HTTP and data can be in the form of not only XML, but also JSON, HTML or plain text. [1]" }, { "code": null, "e": 3257, "s": 3040, "text": "Sometimes, the webpage may have some JavaScripts running in the background to do some scheduled jobs and the browser will catch them all. If you want to have a cleaner list of caught requests, the best approach is to" }, { "code": null, "e": 3301, "s": 3257, "text": "Make sure the “recording” button is enabled" }, { "code": null, "e": 3321, "s": 3301, "text": "Refresh the webpage" }, { "code": null, "e": 3423, "s": 3321, "text": "Stop “recording” when you see the data related content has already been fully rendered on the webpage" }, { "code": null, "e": 3487, "s": 3423, "text": "Now, you will have a list of requests in the developer console." }, { "code": null, "e": 3628, "s": 3487, "text": "OK. This one is very obvious. We can see that there is a request to have its name called “covid-19-new-cases-json.json...”. That must be it!" }, { "code": null, "e": 3731, "s": 3628, "text": "Go to the “Headers” tab, you will see the detail of this request. The most important thing is the URL." }, { "code": null, "e": 3804, "s": 3731, "text": "Now, let’s just open that URL as another browser tab to see what happen." }, { "code": null, "e": 3854, "s": 3804, "text": "Cool! This is the API endpoint we’re looking for." }, { "code": null, "e": 3889, "s": 3854, "text": "How to consume it? Extremely easy!" }, { "code": null, "e": 4055, "s": 3889, "text": "I believe you must use Pandas Dataframe if you are a data scientist or data analyst. Just one line of Python code, you got everything directly into Pandas Dataframe." }, { "code": null, "e": 4176, "s": 4055, "text": "df = pd.read_json('https://www.theage.com.au/interactive/2020/coronavirus/data-feeder/covid-19-new-cases-json.json?v=3')" }, { "code": null, "e": 4409, "s": 4176, "text": "Not all websites are using REST API endpoints so that I wouldn’t say this is a universal approach. However, you’ll find that there are a considerable number of websites using that. Let’s just take one more example, the IKEA website." }, { "code": null, "e": 4620, "s": 4409, "text": "Let’s say you want to get all the beds from IKEA together with the product details to perform some analysis. Here is the request that my browser caught from the URL (https://www.ikea.com/au/en/cat/beds-bm003/)." }, { "code": null, "e": 5004, "s": 4620, "text": "This one is more interesting. Please note that it says that the “product count” is 220, but the “product window” only give 24 of them. If you pay attention to the page, it turns out only 24 products will be listed on the page, and a “load more” button is provided if you want to keep browsing more. Well, this is very common in Web Development to save bandwidth and server resources." }, { "code": null, "e": 5099, "s": 5004, "text": "But does that mean we have to give it up? Absolutely no. Let’s have a look at the request URL:" }, { "code": null, "e": 5302, "s": 5099, "text": "Have you seen that there is a property called “size”? It exactly equals 24, which is the page size. Let’s try to change that to size=220, and send the request using the Python built-in library requests." }, { "code": null, "e": 5503, "s": 5302, "text": "import requestsjson = requests.get( 'https://sik.search.blue.cdtapps.com/au/en/product-list-page?category=bm003&sort=RELEVANCE&size=220&c=plp&v=20200430').json()['productListPage']['productWindow']" }, { "code": null, "e": 5682, "s": 5503, "text": "The reason why we cannot directly use Pandas this time is that the product list is not at the root level of the JSON object. Instead, it is at root.productListPage.productWindow." }, { "code": null, "e": 5795, "s": 5682, "text": "After that, the request will convert the JSON object to a Python dictionary, so we can read it using Pandas now." }, { "code": null, "e": 5829, "s": 5795, "text": "df = pd.DataFrame.from_dict(json)" }, { "code": null, "e": 6162, "s": 5829, "text": "Isn’t that quick and easy? You don’t have to learn those web scraping libraries. But, of course, this approach is not going to be effective for all the websites, and that is why the web scraping libraries are still necessary. However, when there is an available API endpoint on the website, why not just find it and directly use it?" }, { "code": null, "e": 6173, "s": 6162, "text": "medium.com" }, { "code": null, "e": 6321, "s": 6173, "text": "If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)" } ]
Find element in a sorted array whose frequency is greater than or equal to n/2. - GeeksforGeeks
15 Apr, 2021 Given a sorted array of length n, find the number in array that appears more than or equal to n/2 times. It is given that such element always exists.Examples: Input : 2 3 3 4 Output : 3 Input : 3 4 5 5 5 Output : 5 Input : 1 1 1 2 3 Output : 1 To find that number, we traverse the array and check the frequency of every element in array if it is greater than or equals to n/2 but it requires extra space and time complexity will be O(n). But we can see that the if there is number that comes more than or equal to n/2 times in a sorted array, then that number must be present at the position n/2 i.e. a[n/2]. C++ Java Python 3 C# PHP Javascript // C++ code to find majority element in a// sorted array#include <iostream>using namespace std; int findMajority(int arr[], int n){ return arr[n / 2];} int main(){ int arr[] = { 1, 2, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMajority(arr, n); return 0;} // Java code to find majority element in a// sorted arraypublic class Test { public static int findMajority(int arr[], int n) { return arr[n / 2]; } public static void main(String args[]) { int arr[] = { 1, 2, 2, 3 }; int n = arr.length; System.out.println(findMajority(arr, n)); }} # Python 3 code to find# majority element in a# sorted array def findMajority(arr, n): return arr[int(n / 2)] # Driver Codearr = [1, 2, 2, 3]n = len(arr)print(findMajority(arr, n)) # This code is contributed by Smitha. // C# code to find majority element in a// sorted arrayusing System; public class GFG { public static int findMajority(int []arr, int n) { return arr[n / 2]; } // Driver code public static void Main() { int []arr = { 1, 2, 2, 3 }; int n = arr.Length; Console.WriteLine(findMajority(arr, n)); }} // This code is contributed by vt_m. <?php// PHP code to find majority// element in a sorted array function findMajority($arr, $n){ return $arr[intval($n / 2)];} // Driver Code $arr = array(1, 2, 2, 3); $n = count($arr); echo findMajority($arr, $n); // This code is contributed by Sam007?> <script> // Javascript code to find majority element in a// sorted array function findMajority(arr, n){ return arr[Math.floor(n / 2)];} // driver code let arr = [ 1, 2, 2, 3 ]; let n = arr.length; document.write(findMajority(arr, n)); </script> Output: 2 Time Complexity : O(1)Related Articles : Majority element in an unsorted array Check for majority element in a sorted arrayThis article is contributed by Amit Kumar. 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 Smitha Dinesh Semwal Sam007 jana_sayantan Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java 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": 26569, "s": 26541, "text": "\n15 Apr, 2021" }, { "code": null, "e": 26730, "s": 26569, "text": "Given a sorted array of length n, find the number in array that appears more than or equal to n/2 times. It is given that such element always exists.Examples: " }, { "code": null, "e": 26820, "s": 26730, "text": "Input : 2 3 3 4\nOutput : 3\n\nInput : 3 4 5 5 5 \nOutput : 5\n\nInput : 1 1 1 2 3\nOutput : 1" }, { "code": null, "e": 27188, "s": 26822, "text": "To find that number, we traverse the array and check the frequency of every element in array if it is greater than or equals to n/2 but it requires extra space and time complexity will be O(n). But we can see that the if there is number that comes more than or equal to n/2 times in a sorted array, then that number must be present at the position n/2 i.e. a[n/2]. " }, { "code": null, "e": 27192, "s": 27188, "text": "C++" }, { "code": null, "e": 27197, "s": 27192, "text": "Java" }, { "code": null, "e": 27206, "s": 27197, "text": "Python 3" }, { "code": null, "e": 27209, "s": 27206, "text": "C#" }, { "code": null, "e": 27213, "s": 27209, "text": "PHP" }, { "code": null, "e": 27224, "s": 27213, "text": "Javascript" }, { "code": "// C++ code to find majority element in a// sorted array#include <iostream>using namespace std; int findMajority(int arr[], int n){ return arr[n / 2];} int main(){ int arr[] = { 1, 2, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMajority(arr, n); return 0;}", "e": 27510, "s": 27224, "text": null }, { "code": "// Java code to find majority element in a// sorted arraypublic class Test { public static int findMajority(int arr[], int n) { return arr[n / 2]; } public static void main(String args[]) { int arr[] = { 1, 2, 2, 3 }; int n = arr.length; System.out.println(findMajority(arr, n)); }}", "e": 27840, "s": 27510, "text": null }, { "code": "# Python 3 code to find# majority element in a# sorted array def findMajority(arr, n): return arr[int(n / 2)] # Driver Codearr = [1, 2, 2, 3]n = len(arr)print(findMajority(arr, n)) # This code is contributed by Smitha.", "e": 28063, "s": 27840, "text": null }, { "code": "// C# code to find majority element in a// sorted arrayusing System; public class GFG { public static int findMajority(int []arr, int n) { return arr[n / 2]; } // Driver code public static void Main() { int []arr = { 1, 2, 2, 3 }; int n = arr.Length; Console.WriteLine(findMajority(arr, n)); }} // This code is contributed by vt_m.", "e": 28468, "s": 28063, "text": null }, { "code": "<?php// PHP code to find majority// element in a sorted array function findMajority($arr, $n){ return $arr[intval($n / 2)];} // Driver Code $arr = array(1, 2, 2, 3); $n = count($arr); echo findMajority($arr, $n); // This code is contributed by Sam007?>", "e": 28745, "s": 28468, "text": null }, { "code": "<script> // Javascript code to find majority element in a// sorted array function findMajority(arr, n){ return arr[Math.floor(n / 2)];} // driver code let arr = [ 1, 2, 2, 3 ]; let n = arr.length; document.write(findMajority(arr, n)); </script>", "e": 29004, "s": 28745, "text": null }, { "code": null, "e": 29013, "s": 29004, "text": "Output: " }, { "code": null, "e": 29015, "s": 29013, "text": "2" }, { "code": null, "e": 29561, "s": 29015, "text": "Time Complexity : O(1)Related Articles : Majority element in an unsorted array Check for majority element in a sorted arrayThis article is contributed by Amit Kumar. 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": 29566, "s": 29561, "text": "vt_m" }, { "code": null, "e": 29587, "s": 29566, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 29594, "s": 29587, "text": "Sam007" }, { "code": null, "e": 29608, "s": 29594, "text": "jana_sayantan" }, { "code": null, "e": 29615, "s": 29608, "text": "Arrays" }, { "code": null, "e": 29625, "s": 29615, "text": "Searching" }, { "code": null, "e": 29632, "s": 29625, "text": "Arrays" }, { "code": null, "e": 29642, "s": 29632, "text": "Searching" }, { "code": null, "e": 29740, "s": 29642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29808, "s": 29740, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 29852, "s": 29808, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 29900, "s": 29852, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 29923, "s": 29900, "text": "Introduction to Arrays" }, { "code": null, "e": 29955, "s": 29923, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29969, "s": 29955, "text": "Binary Search" }, { "code": null, "e": 30037, "s": 29969, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30051, "s": 30037, "text": "Linear Search" }, { "code": null, "e": 30099, "s": 30051, "text": "Search an element in a sorted and rotated array" } ]
How to perform Merge Sort using C#?
Merge Sort is a sorting algorithm that uses the divide and conquer method. It divides the array into two parts and then calls itself for each of these two parts. This process is continued until the array is sorted. A program that demonstrates merge sort in C# is given as follows − Live Demo using System; namespace QuickSortDemo { class Example { static public void merge(int[] arr, int p, int q, int r) { int i, j, k; int n1 = q - p + 1; int n2 = r - q; int[] L = new int[n1]; int[] R = new int[n2]; for (i = 0; i < n1; i++) { L[i] = arr[p + i]; } for (j = 0; j < n2; j++) { R[j] = arr[q + 1 + j]; } i = 0; j = 0; k = p; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static public void mergeSort(int[] arr, int p, int r) { if (p < r) { int q = (p + r) / 2; mergeSort(arr, p, q); mergeSort(arr, q + 1, r); merge(arr, p, q, r); } } static void Main(string[] args) { int[] arr = {76, 89, 23, 1, 55, 78, 99, 12, 65, 100}; int n = 10, i; Console.WriteLine("Merge Sort"); Console.Write("Initial array is: "); for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } mergeSort(arr, 0, n-1); Console.Write("\nSorted Array is: "); for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } } } } The output of the above program is as follows. Merge Sort Initial array is: 76 89 23 1 55 78 99 12 65 100 Sorted Array is: 1 12 23 55 65 76 78 89 99 100 Now let us understand the above program. In the main() function, first the initial array is displayed. Then, the function mergeSort() is called to perform merge sort on the array. The code snippet for this is given as follows. int[] arr = {76, 89, 23, 1, 55, 78, 99, 12, 65, 100}; int n = 10, i; Console.WriteLine("Merge Sort"); Console.Write("Initial array is: "); for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } mergeSort(arr, 0, n-1); In the function mergeSort(), q is calculated as the mid point of the array. Then mergeSort() is called on both the sub-arrays created. Finally, merge() is called that merges these sub-arrays. The code snippet for this is given as follows. if (p < r) { int q = (p + r) / 2; mergeSort(arr, p, q); mergeSort(arr, q + 1, r); merge(arr, p, q, r); } In the function merge(), two sorted subarrays are provided. This function basically merges these subarrays into a single array in such a manner that the resultant array is also sorted. The code snippet for this is given as follows. int i, j, k; int n1 = q - p + 1; int n2 = r - q; int[] L = new int[n1]; int[] R = new int[n2]; for (i = 0; i < n1; i++) { L[i] = arr[p + i]; } for (j = 0; j < n2; j++) { R[j] = arr[q + 1 + j]; } i = 0; j = 0; k = p; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; }
[ { "code": null, "e": 1277, "s": 1062, "text": "Merge Sort is a sorting algorithm that uses the divide and conquer method. It divides the array into two parts and then calls itself for each of these two parts. This process is continued until the array is sorted." }, { "code": null, "e": 1344, "s": 1277, "text": "A program that demonstrates merge sort in C# is given as follows −" }, { "code": null, "e": 1355, "s": 1344, "text": " Live Demo" }, { "code": null, "e": 2987, "s": 1355, "text": "using System;\nnamespace QuickSortDemo {\n class Example {\n static public void merge(int[] arr, int p, int q, int r) {\n int i, j, k;\n int n1 = q - p + 1;\n int n2 = r - q;\n int[] L = new int[n1];\n int[] R = new int[n2];\n for (i = 0; i < n1; i++) {\n L[i] = arr[p + i];\n }\n for (j = 0; j < n2; j++) {\n R[j] = arr[q + 1 + j];\n }\n i = 0;\n j = 0;\n k = p;\n while (i < n1 && j < n2) {\n if (L[i] <= R[j]) {\n arr[k] = L[i];\n i++;\n } else {\n arr[k] = R[j];\n j++;\n }\n k++;\n }\n while (i < n1) {\n arr[k] = L[i];\n i++;\n k++;\n }\n while (j < n2) {\n arr[k] = R[j];\n j++;\n k++;\n }\n }\n static public void mergeSort(int[] arr, int p, int r) {\n if (p < r) {\n int q = (p + r) / 2;\n mergeSort(arr, p, q);\n mergeSort(arr, q + 1, r);\n merge(arr, p, q, r);\n }\n }\n static void Main(string[] args) {\n int[] arr = {76, 89, 23, 1, 55, 78, 99, 12, 65, 100};\n int n = 10, i;\n Console.WriteLine(\"Merge Sort\");\n Console.Write(\"Initial array is: \");\n for (i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n }\n mergeSort(arr, 0, n-1);\n Console.Write(\"\\nSorted Array is: \");\n for (i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n }\n }\n }\n}" }, { "code": null, "e": 3034, "s": 2987, "text": "The output of the above program is as follows." }, { "code": null, "e": 3140, "s": 3034, "text": "Merge Sort\nInitial array is: 76 89 23 1 55 78 99 12 65 100\nSorted Array is: 1 12 23 55 65 76 78 89 99 100" }, { "code": null, "e": 3181, "s": 3140, "text": "Now let us understand the above program." }, { "code": null, "e": 3367, "s": 3181, "text": "In the main() function, first the initial array is displayed. Then, the function mergeSort() is called to perform merge sort on the array. The code snippet for this is given as follows." }, { "code": null, "e": 3590, "s": 3367, "text": "int[] arr = {76, 89, 23, 1, 55, 78, 99, 12, 65, 100};\nint n = 10, i;\nConsole.WriteLine(\"Merge Sort\");\nConsole.Write(\"Initial array is: \");\nfor (i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n}\nmergeSort(arr, 0, n-1);" }, { "code": null, "e": 3829, "s": 3590, "text": "In the function mergeSort(), q is calculated as the mid point of the array. Then mergeSort() is called on both the sub-arrays created. Finally, merge() is called that merges these sub-arrays. The code snippet for this is given as follows." }, { "code": null, "e": 3946, "s": 3829, "text": "if (p < r) {\n int q = (p + r) / 2;\n mergeSort(arr, p, q);\n mergeSort(arr, q + 1, r);\n merge(arr, p, q, r);\n}" }, { "code": null, "e": 4178, "s": 3946, "text": "In the function merge(), two sorted subarrays are provided. This function basically merges these subarrays into a single array in such a manner that the resultant array is also sorted. The code snippet for this is given as follows." }, { "code": null, "e": 4700, "s": 4178, "text": "int i, j, k;\nint n1 = q - p + 1;\nint n2 = r - q;\nint[] L = new int[n1];\nint[] R = new int[n2];\nfor (i = 0; i < n1; i++) {\n L[i] = arr[p + i];\n}\nfor (j = 0; j < n2; j++) {\n R[j] = arr[q + 1 + j];\n}\ni = 0;\nj = 0;\nk = p;\nwhile (i < n1 && j < n2) {\n if (L[i] <= R[j]) {\n arr[k] = L[i];\n i++;\n } else {\n arr[k] = R[j];\n j++;\n }\n k++;\n}\nwhile (i < n1) {\n arr[k] = L[i];\n i++;\n k++;\n}\nwhile (j < n2) {\n arr[k] = R[j];\n j++;\n k++;\n}\nwhile (j < n2) {\n arr[k] = R[j];\n j++;\n k++;\n}" } ]
Palindrome | Practice | GeeksforGeeks
Given an integer, check whether it is a palindrome or not. Example 1: Input: n = 55555 Output: Yes Example 2: Input: n = 123 Output: No Your Task: You don't need to read or print anything. Your task is to complete the function is_palindrome() which takes the number as input parameter and returns "Yes" if it is palindrome otherwise returns "No"(Without quotes). Expected Time Complexity: O(x) Expected Space Complexity: O(x) where x is number of digits in n. Constraints: 1 <= n <= 1000 0 adeshs11111 week ago Ok 0 ekansh25sanskar2 weeks ago class Solution{public: string is_palindrome(int n) { // Code here. int x=0,temp=n; while(n!=0){ x=(x*10)+(n%10); n/=10; } if(x==temp) cout<<"Yes"; else cout<<"No";}}; 0 shivanshm20013 weeks ago RECURSIVE SOLUTION class Solution{public: string check(string &str,int N,int M) { if(N==0 && M==str.size()) { return "Yes"; } if(str[N-1]==str[M]) { check(str,N-1,M+1); return "Yes"; } else return "No"; } string is_palindrome(int n) { // Code here. string str=to_string(n); string ans=check(str,str.size(),0); return ans; } 0 shwetarpatil233 weeks ago string is_palindrome(int n) { int temp = n; int reverse = 0; while(temp !=0){ int r = temp %10; reverse = (reverse * 10) + r; temp = temp / 10; } return (n == reverse)?"Yes":"No"; } 0 avicode4241 month ago class Solution { // function to return sum of 1, 2, ... n long seriesSum(int n){ // code here if(n<=0) { return 0; } long sum = n+seriesSum(n-1); return sum; }} 0 meetsangani6338meet2 months ago class Solution { public: string is_palindrome(int n) { // Code here. string s1=to_string(n); string s2=s1; reverse(s2.begin(),s2.end()); if(s1==s2) { return "Yes"; } else return "No"; } }; 0 sdmrf2 months ago Python Soln: def is_palindrome(self, n): if str(n)==str(n)[::-1]: return "Yes" else: return "No" 0 imranmbhd24122 months ago ###CPP string is_palindrome(int b) { int c = b, x{}; while (b) { x = x*10 + b%10; b/=10; } return c == x? "Yes":"No"; } 0 0niharika22 months ago int rev=0, original = n; while(n){ rev = rev*10 + n%10; n/=10; } if(rev==original) return "Yes"; else return "No"; 0 madhurimasantra19992 months ago class Solution{ public String is_palindrome(int n) { int rev=0,rem,original,i; original=n; while(n!=0) { rem=n%10; n=n/10; rev=(rev*10)+rem; } if(original==rev) return "Yes"; else return "No"; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 309, "s": 238, "text": "Given an integer, check whether it is a palindrome or not.\n\nExample 1:" }, { "code": null, "e": 339, "s": 309, "text": "Input: n = 55555\nOutput: Yes\n" }, { "code": null, "e": 351, "s": 339, "text": "\nExample 2:" }, { "code": null, "e": 378, "s": 351, "text": "Input: n = 123\nOutput: No\n" }, { "code": null, "e": 609, "s": 380, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function is_palindrome() which takes the number as input parameter and returns \"Yes\" if it is palindrome otherwise returns \"No\"(Without quotes).\n " }, { "code": null, "e": 708, "s": 609, "text": "Expected Time Complexity: O(x)\nExpected Space Complexity: O(x) where x is number of digits in n.\n " }, { "code": null, "e": 736, "s": 708, "text": "Constraints:\n1 <= n <= 1000" }, { "code": null, "e": 738, "s": 736, "text": "0" }, { "code": null, "e": 759, "s": 738, "text": "adeshs11111 week ago" }, { "code": null, "e": 762, "s": 759, "text": "Ok" }, { "code": null, "e": 764, "s": 762, "text": "0" }, { "code": null, "e": 791, "s": 764, "text": "ekansh25sanskar2 weeks ago" }, { "code": null, "e": 1001, "s": 791, "text": "class Solution{public: string is_palindrome(int n) { // Code here. int x=0,temp=n; while(n!=0){ x=(x*10)+(n%10); n/=10; } if(x==temp) cout<<\"Yes\"; else cout<<\"No\";}};" }, { "code": null, "e": 1003, "s": 1001, "text": "0" }, { "code": null, "e": 1028, "s": 1003, "text": "shivanshm20013 weeks ago" }, { "code": null, "e": 1047, "s": 1028, "text": "RECURSIVE SOLUTION" }, { "code": null, "e": 1474, "s": 1047, "text": "class Solution{public: string check(string &str,int N,int M) { if(N==0 && M==str.size()) { return \"Yes\"; } if(str[N-1]==str[M]) { check(str,N-1,M+1); return \"Yes\"; } else return \"No\"; } string is_palindrome(int n) { // Code here. string str=to_string(n); string ans=check(str,str.size(),0); return ans; }" }, { "code": null, "e": 1476, "s": 1474, "text": "0" }, { "code": null, "e": 1502, "s": 1476, "text": "shwetarpatil233 weeks ago" }, { "code": null, "e": 1758, "s": 1502, "text": " string is_palindrome(int n) { int temp = n; int reverse = 0; while(temp !=0){ int r = temp %10; reverse = (reverse * 10) + r; temp = temp / 10; } return (n == reverse)?\"Yes\":\"No\"; }" }, { "code": null, "e": 1760, "s": 1758, "text": "0" }, { "code": null, "e": 1782, "s": 1760, "text": "avicode4241 month ago" }, { "code": null, "e": 2010, "s": 1782, "text": "class Solution { // function to return sum of 1, 2, ... n long seriesSum(int n){ // code here if(n<=0) { return 0; } long sum = n+seriesSum(n-1); return sum; }}" }, { "code": null, "e": 2012, "s": 2010, "text": "0" }, { "code": null, "e": 2044, "s": 2012, "text": "meetsangani6338meet2 months ago" }, { "code": null, "e": 2328, "s": 2044, "text": "class Solution\n{\n\tpublic:\n\t\tstring is_palindrome(int n)\n\t\t{\n\t\t // Code here.\n\t\t \n\t\t string s1=to_string(n);\n\t\t string s2=s1;\n\t\t \n\t\t reverse(s2.begin(),s2.end());\n\t\t if(s1==s2)\n\t\t {\n\t\t return \"Yes\";\n\t\t }\n\t\t \n\t\t else\n\t\t return \"No\";\n\t\t}\n};" }, { "code": null, "e": 2330, "s": 2328, "text": "0" }, { "code": null, "e": 2348, "s": 2330, "text": "sdmrf2 months ago" }, { "code": null, "e": 2362, "s": 2348, "text": " Python Soln:" }, { "code": null, "e": 2452, "s": 2362, "text": "def is_palindrome(self, n): if str(n)==str(n)[::-1]: return \"Yes\" else: return \"No\"" }, { "code": null, "e": 2454, "s": 2452, "text": "0" }, { "code": null, "e": 2480, "s": 2454, "text": "imranmbhd24122 months ago" }, { "code": null, "e": 2487, "s": 2480, "text": "###CPP" }, { "code": null, "e": 2632, "s": 2487, "text": "string is_palindrome(int b) { int c = b, x{}; while (b) { x = x*10 + b%10; b/=10; } return c == x? \"Yes\":\"No\"; }" }, { "code": null, "e": 2634, "s": 2632, "text": "0" }, { "code": null, "e": 2657, "s": 2634, "text": "0niharika22 months ago" }, { "code": null, "e": 2820, "s": 2657, "text": "int rev=0, original = n; while(n){ rev = rev*10 + n%10; n/=10; } if(rev==original) return \"Yes\"; else return \"No\";" }, { "code": null, "e": 2822, "s": 2820, "text": "0" }, { "code": null, "e": 2854, "s": 2822, "text": "madhurimasantra19992 months ago" }, { "code": null, "e": 3148, "s": 2854, "text": "class Solution{ public String is_palindrome(int n) { int rev=0,rem,original,i; original=n; while(n!=0) { rem=n%10; n=n/10; rev=(rev*10)+rem; } if(original==rev) return \"Yes\"; else return \"No\"; }}" }, { "code": null, "e": 3294, "s": 3148, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3330, "s": 3294, "text": " Login to access your submissions. " }, { "code": null, "e": 3340, "s": 3330, "text": "\nProblem\n" }, { "code": null, "e": 3350, "s": 3340, "text": "\nContest\n" }, { "code": null, "e": 3413, "s": 3350, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3561, "s": 3413, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3769, "s": 3561, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3875, "s": 3769, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Circular Queue
Theory of Computation In Circular queue, elements in a queue are arranged in a circular way. In this front and rear ends are joined together, which solves the dequeue re buffering problem and prevents excessive use of memory. It also follows the FIFO principle. Suppose we have a linear queue. Now if we want to insert in the queue, then it is not possible because the queue is completely full. Now delete the two successors from the queue, but the overflow condition still exists because REAR = MAX - 1. This is the major drawback of a linear queue. This can be fixed if we shift the elements to the left, but this can be a time-consuming process. As you can also see through this image. The queue is full and we can insert any element. Here, we have deleted four elements from the queue. But we cannot insert any element because the REAR is still at the last position. This is the major problem in the queue. It has empty positions, but we cannot use them. Circular Queue is introduced to fix this problem. The circular queue shows overloaded only when FRONT = 0 and REAR = MAX - 1. To insert values in a circular queue, we have to check the following conditions. If FRONT = 0 and REAR = MAX - 1 , then the circular queue is full. If REAR != MAX - 1, then REAR can be increased. If FRONT != 0 and REAR = MAX - 1, then it means queue is not full. Step 1: IF FRONT = 0 and Rear = MAX - 1 Write OVERFLOW Exit Step 2: IF FRONT = -1 and REAR = -1 SET FRONT = REAR = 0 ELSE IF REAR = MAX - 1 and FRONT != 0 SET REAR = 0 ELSE SET REAR = REAR + 1 [END OF IF] Step 3: SET QUEUE[REAR] = VAL Step 4: EXIT To delete values in a circular queue, we have to check the following conditions. If FRONT = -1, then there is no element in the queue. If FRONT = REAR and the queue are not empty, then after deleting the element from the front, the queue becomes empty, so the FRONT and REAR are set to -1. If FRONT = MAX - 1, and the queue is not empty, then after deleting the element from the front the queue becomes empty. Step 1: IF FRONT = -1 Write UNDERFLOW Goto Step 4 [END of IF] Step 2: SET VAL = QUEUE[FRONT] Step 3: IF FRONT = REAR SET FRONT = REAR = -1 ELSE IF FRONT = MAX -1 SET FRONT = 0 ELSE SET FRONT = FRONT + 1 [END of IF] Step 4: EXIT #include<stdio.h> #define max 30 int q[10],front=0,rear=-1; void main() { int che; void insert_element(); void delete_element(); void display_element(); printf("\nCircular Queue operations"); printf("\n Enter 1 to insert into queue"); printf("\n Enter 2 to delete element"); printf("\n Enter 3 to display element"); printf("\n Enter 4 to exit"); do { printf("\n Enter your choice: "); scanf("%d",&che); switch(che) { case 1: insert_element(); break; case 2: delete_element(); break; case 3: display_element(); break; case 4: exit(0); default: printf("Invalid input \n"); } }while(1); return 0; } void insert_element() { int x; if((front==0&&rear==max-1)||(front>0&&rear==front-1)) printf("Circular Queue Overflow\n"); else { printf("\n Enter a value to insert: "); scanf("%d",&x); if(rear==max-1&&front>0) { rear=0; q[rear]=x; } else { if((front==0&&rear==-1)||(rear!=front-1)) q[++rear]=x; } } } void delete_element() { int a; if((front==0)&&(rear==-1)) { printf("Circular Queue Underflow \n"); } if(front==rear) { a=q[front]; rear=-1; front=0; } else if(front==max-1) { a=q[front]; front=0; } else a=q[front++]; printf("\n Element deleted from the queue :%d\n",a); } void display_element() { int i,j; if(front==0&&rear==-1) { printf("Circular Queue Underflow \n"); } if(front>rear) { for(i=0;i<=rear;i++) printf("\t%d",q[i]); for(j=front;j<=max-1;j++) printf("\t%d",q[j]); printf("\nREAR: %d\n",q[rear]); printf("\nFRONT: %d\n",q[front]); } else { for(i=front;i<=rear;i++) { printf("\t%d",q[i]); } printf("\nREAR: %d\n",q[rear]); printf("\nFRONT: %d\n",q[front]); } printf("\n"); } Circular Queue operations Enter 1 to insert into queue Enter 2 to delete element Enter 3 to display element Enter 4 to exit Enter your choice: 1 Enter a value to insert: 10 Enter your choice: 1 Enter a value to insert: 39 Enter your choice: 1 Enter a value to insert: 89 Enter your choice: 3 10 39 89 REAR: 89 FRONT: 10 Enter your choice: 2 Element deleted from the queue :10 Enter your choice: 3 39 89 REAR: 89 FRONT: 39 Enter your choice:
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 355, "s": 112, "text": "In Circular queue, elements in a queue are arranged in a circular way. In this front and rear ends are joined \ntogether, which solves the dequeue re buffering problem and prevents excessive use of memory. It also follows the FIFO principle. \n" }, { "code": null, "e": 745, "s": 355, "text": "Suppose we have a linear queue. Now if we want to insert in the queue, then it is not possible because the \nqueue is completely full. Now delete the two successors from the queue, but the overflow condition still exists because \nREAR = MAX - 1. This is the major drawback of a linear queue. This can be fixed if we shift the elements to the left, but \nthis can be a time-consuming process." }, { "code": null, "e": 834, "s": 745, "text": "As you can also see through this image. The queue is full and we can insert any element." }, { "code": null, "e": 1057, "s": 834, "text": "Here, we have deleted four elements from the queue.\n But we cannot insert any element because the REAR is still at the last position. \nThis is the major problem in the queue. It has empty positions, but we cannot use them." }, { "code": null, "e": 1184, "s": 1057, "text": "Circular Queue is introduced to fix this problem. The circular queue shows overloaded only when \nFRONT = 0 and REAR = MAX - 1." }, { "code": null, "e": 1265, "s": 1184, "text": "To insert values in a circular queue, we have to check the following conditions." }, { "code": null, "e": 1332, "s": 1265, "text": "If FRONT = 0 and REAR = MAX - 1 , then the circular queue is full." }, { "code": null, "e": 1380, "s": 1332, "text": "If REAR != MAX - 1, then REAR can be increased." }, { "code": null, "e": 1447, "s": 1380, "text": "If FRONT != 0 and REAR = MAX - 1, then it means queue is not full." }, { "code": null, "e": 1704, "s": 1447, "text": "Step 1: IF FRONT = 0 and Rear = MAX - 1\nWrite OVERFLOW\nExit\nStep 2: IF FRONT = -1 and REAR = -1\n\t\tSET FRONT = REAR = 0\n\tELSE IF REAR = MAX - 1 and FRONT != 0\n\t\tSET REAR = 0\n\tELSE\n\t\tSET REAR = REAR + 1\n\t[END OF IF]\nStep 3: SET QUEUE[REAR] = VAL\nStep 4: EXIT" }, { "code": null, "e": 1785, "s": 1704, "text": "To delete values in a circular queue, we have to check the following conditions." }, { "code": null, "e": 1839, "s": 1785, "text": "If FRONT = -1, then there is no element in the queue." }, { "code": null, "e": 1995, "s": 1839, "text": "If FRONT = REAR and the queue are not empty, then after deleting the element from the front, the queue \nbecomes empty, so the FRONT and REAR are set to -1." }, { "code": null, "e": 2115, "s": 1995, "text": "If FRONT = MAX - 1, and the queue is not empty, then after deleting the element from the front the queue becomes empty." }, { "code": null, "e": 2343, "s": 2115, "text": "Step 1: IF FRONT = -1\nWrite UNDERFLOW\nGoto Step 4\n[END of IF]\nStep 2: SET VAL = QUEUE[FRONT]\nStep 3: IF FRONT = REAR\nSET FRONT = REAR = -1\nELSE\nIF FRONT = MAX -1\nSET FRONT = 0\nELSE\nSET FRONT = FRONT + 1\n[END of IF]\nStep 4: EXIT" }, { "code": null, "e": 4534, "s": 2343, "text": "#include<stdio.h>\n#define max 30\nint q[10],front=0,rear=-1;\nvoid main()\n{\n int che;\n void insert_element();\n void delete_element();\n void display_element();\n printf(\"\\nCircular Queue operations\");\n\tprintf(\"\\n Enter 1 to insert into queue\");\n\tprintf(\"\\n Enter 2 to delete element\");\n\tprintf(\"\\n Enter 3 to display element\");\n\tprintf(\"\\n Enter 4 to exit\");\n\n do\n\t{\n printf(\"\\n Enter your choice: \");\n scanf(\"%d\",&che);\n switch(che)\n {\n case 1: insert_element();\n break;\n case 2: delete_element();\n break;\n case 3: display_element();\n break;\n case 4:\n\t\texit(0);\n default:\n printf(\"Invalid input \\n\");\n }\n }while(1);\n return 0;\n}\n \nvoid insert_element()\n{\n int x;\n if((front==0&&rear==max-1)||(front>0&&rear==front-1))\n printf(\"Circular Queue Overflow\\n\");\n else\n {\n printf(\"\\n Enter a value to insert: \");\n scanf(\"%d\",&x);\n if(rear==max-1&&front>0)\n {\n rear=0;\n q[rear]=x;\n }\n else\n {\n if((front==0&&rear==-1)||(rear!=front-1))\n q[++rear]=x;\n }\n }\n}\nvoid delete_element()\n{\n int a;\n if((front==0)&&(rear==-1))\n {\n printf(\"Circular Queue Underflow \\n\");\n }\n if(front==rear)\n {\n a=q[front];\n rear=-1;\n front=0;\n }\n else\n if(front==max-1)\n {\n a=q[front];\n front=0;\n }\n else a=q[front++];\n printf(\"\\n Element deleted from the queue :%d\\n\",a);\n}\n \nvoid display_element()\n{\n int i,j;\n if(front==0&&rear==-1)\n {\n printf(\"Circular Queue Underflow \\n\");\n }\n if(front>rear)\n {\n for(i=0;i<=rear;i++)\n printf(\"\\t%d\",q[i]);\n for(j=front;j<=max-1;j++)\n printf(\"\\t%d\",q[j]);\n printf(\"\\nREAR: %d\\n\",q[rear]);\n printf(\"\\nFRONT: %d\\n\",q[front]);\n }\n else\n {\n for(i=front;i<=rear;i++)\n {\n printf(\"\\t%d\",q[i]);\n }\n printf(\"\\nREAR: %d\\n\",q[rear]);\n printf(\"\\nFRONT: %d\\n\",q[front]);\n }\n printf(\"\\n\");\n}" } ]
The easiest and fastest way to make GIFs and math videos with Python | by Bruno Rodrigues | Towards Data Science
“Celluloid, Easy Matplotlib Animations” I really enjoy working with data visualization and I always wonder what’s the best way to provide more direct and intuitive visual interactions when I have to explain some result or complex model. Lately, I’ve been growing to use GIFs and quick videos. Even if this makes the coding part harder and more complex, the result generally is much more efficient in communicating my findings and process. But in Python, there’s always an easier and simpler way and to simplify the animating process, Celluloid was born. Using only 50 lines of code to deal with Matplotlib Artists and ArtistAnimations Celluloid creates an animation from the series of images you want to plot into the Camera abstraction. Let’s start by installing the library with $ pip install celluloid Now let’s get to it! The simplest oneEvolution plotWorking with imagesUsing dynamic labels and titles The simplest one Evolution plot Working with images Using dynamic labels and titles Let’s create a simple plot just to demonstrate the basic usage of how to run the code in a Jupyter notebook, but we could also use the method save(‘filename.gif_or_mp4’) from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npfrom IPython.display import HTML # to show the animation in Jupyterfig, ax = plt.subplots() # creating my figcamera = Camera(fig)# the camera gets the fig we'll plotfor i in range(10): ax.plot([i] * 5, c='black') # 5 element array from 0 to 9 camera.snap() # the camera takes a snapshot of the plotanimation = camera.animate() # animation readyHTML(animation.to_html5_video()) # displaying the animation This is a fun kind of plot, but not a very useful one. The idea is to plot the dataset evolving little by little. from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npfrom IPython.display import HTMLfig, ax = plt.subplots(figsize=(10, 6)) # let's make it biggercamera = Camera(fig)# the camera gets our figurex = np.linspace(0, np.pi*2, 60) # a sine circley = np.sin(x) # sinefor i in range(len(x)): x_t = x[:i] # current dataset y_t = y[:i] # current sine ax.plot(x_t, y_t, c='blue') camera.snap()animation = camera.animate()HTML(animation.to_html5_video()) A fun little trick that makes the plot look like hand drawn x_t = x[:i] + 1.3*np.random.random(size=i) Images may help a lot to present ideas, and algorithms that use images are mainly well explained by videos In this example, I animated a Neural Style Transfer between an image of my cat and Munch’s The Scream. I trained the model for 200 epochs and saved the result each 10 epochs (I’ll explain more about the algorithm in another article) In my case, I saved the 20 photos during training to make the GIF using the pattern “./NST/epochs/epoch_k.jpg” from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npfrom IPython.display import HTMLimport osfig, ax = plt.subplots() # make it biggercamera = Camera(fig)# the camera gets our figurefor img in os.listdir("NST/epochs"): img_obj = plt.imread(os.path.join("NST/epochs"), img) # reading ax.imshow(img_obj) # plotting camera.snap()animation = camera.animate()HTML(animation.to_html5_video()) This is one of the most interesting aspects of celluloid, here we have the capacity to make the plot very dynamic. In this example I plotted two normal distributions with distinct means but the same standard deviation and then I changed this standard deviation to evaluate the impact it has on each curve. I put the current standard deviation on the title and the real mean as the label of each curve. I had to pass the calculated label as a tuple because I used two curves, if it was only one I could’ve used just a like plt.legend([calculated_label]), which is simple from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npimport seaborn as snsfrom IPython.display import HTMLstd = 3 # start std Am = 15. # mean of first normalBm = 12.5 # mean of second normalfig, ax = plt.subplots(figsize=(9,6)) # empty figcamera = Camera(fig)for j in range(10): plt.ylim((0, 0.2)) # setting up the limits (or else it will auto ajust plt.xlim((-50, 50)) A = np.random.normal(Am, std, size=(1000)) # creating the 1000-sized normals B = np.random.normal(Bm, std, size=(1000)) A_plot = sns.distplot(A, color='red') B_plot = sns.distplot(B, color='blue') plt.legend(( 'Real Mean A: {:.2f}'.format(np.mean(A)), 'Real Mean B: {:.2f}'.format(np.mean(B)) )) ax.text(0.5, 1.01, "Standard Deviation = "+str(std), transform=ax.transAxes) # making the dynamic title camera.snap() # camera snapshot std += 1 # incrementing the stdanim = camera.animate() # animating the plotsHTML(anim.to_html5_video()) This were just my basic ideas of how to use celluloid, but truth be told the possibilities are infinite and I’ve used in several applications, even to demonstrate how some Machine Learning Algorithms learn check it out. If you liked this tutorial, used and it worked (or if it didn’t) please contact me using the links in my profile
[ { "code": null, "e": 87, "s": 47, "text": "“Celluloid, Easy Matplotlib Animations”" }, { "code": null, "e": 284, "s": 87, "text": "I really enjoy working with data visualization and I always wonder what’s the best way to provide more direct and intuitive visual interactions when I have to explain some result or complex model." }, { "code": null, "e": 486, "s": 284, "text": "Lately, I’ve been growing to use GIFs and quick videos. Even if this makes the coding part harder and more complex, the result generally is much more efficient in communicating my findings and process." }, { "code": null, "e": 601, "s": 486, "text": "But in Python, there’s always an easier and simpler way and to simplify the animating process, Celluloid was born." }, { "code": null, "e": 785, "s": 601, "text": "Using only 50 lines of code to deal with Matplotlib Artists and ArtistAnimations Celluloid creates an animation from the series of images you want to plot into the Camera abstraction." }, { "code": null, "e": 828, "s": 785, "text": "Let’s start by installing the library with" }, { "code": null, "e": 852, "s": 828, "text": "$ pip install celluloid" }, { "code": null, "e": 873, "s": 852, "text": "Now let’s get to it!" }, { "code": null, "e": 954, "s": 873, "text": "The simplest oneEvolution plotWorking with imagesUsing dynamic labels and titles" }, { "code": null, "e": 971, "s": 954, "text": "The simplest one" }, { "code": null, "e": 986, "s": 971, "text": "Evolution plot" }, { "code": null, "e": 1006, "s": 986, "text": "Working with images" }, { "code": null, "e": 1038, "s": 1006, "text": "Using dynamic labels and titles" }, { "code": null, "e": 1208, "s": 1038, "text": "Let’s create a simple plot just to demonstrate the basic usage of how to run the code in a Jupyter notebook, but we could also use the method save(‘filename.gif_or_mp4’)" }, { "code": null, "e": 1716, "s": 1208, "text": "from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npfrom IPython.display import HTML # to show the animation in Jupyterfig, ax = plt.subplots() # creating my figcamera = Camera(fig)# the camera gets the fig we'll plotfor i in range(10): ax.plot([i] * 5, c='black') # 5 element array from 0 to 9 camera.snap() # the camera takes a snapshot of the plotanimation = camera.animate() # animation readyHTML(animation.to_html5_video()) # displaying the animation" }, { "code": null, "e": 1830, "s": 1716, "text": "This is a fun kind of plot, but not a very useful one. The idea is to plot the dataset evolving little by little." }, { "code": null, "e": 2332, "s": 1830, "text": "from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npfrom IPython.display import HTMLfig, ax = plt.subplots(figsize=(10, 6)) # let's make it biggercamera = Camera(fig)# the camera gets our figurex = np.linspace(0, np.pi*2, 60) # a sine circley = np.sin(x) # sinefor i in range(len(x)): x_t = x[:i] # current dataset y_t = y[:i] # current sine ax.plot(x_t, y_t, c='blue') camera.snap()animation = camera.animate()HTML(animation.to_html5_video())" }, { "code": null, "e": 2392, "s": 2332, "text": "A fun little trick that makes the plot look like hand drawn" }, { "code": null, "e": 2435, "s": 2392, "text": "x_t = x[:i] + 1.3*np.random.random(size=i)" }, { "code": null, "e": 2542, "s": 2435, "text": "Images may help a lot to present ideas, and algorithms that use images are mainly well explained by videos" }, { "code": null, "e": 2775, "s": 2542, "text": "In this example, I animated a Neural Style Transfer between an image of my cat and Munch’s The Scream. I trained the model for 200 epochs and saved the result each 10 epochs (I’ll explain more about the algorithm in another article)" }, { "code": null, "e": 2886, "s": 2775, "text": "In my case, I saved the 20 photos during training to make the GIF using the pattern “./NST/epochs/epoch_k.jpg”" }, { "code": null, "e": 3328, "s": 2886, "text": "from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npfrom IPython.display import HTMLimport osfig, ax = plt.subplots() # make it biggercamera = Camera(fig)# the camera gets our figurefor img in os.listdir(\"NST/epochs\"): img_obj = plt.imread(os.path.join(\"NST/epochs\"), img) # reading ax.imshow(img_obj) # plotting camera.snap()animation = camera.animate()HTML(animation.to_html5_video())" }, { "code": null, "e": 3443, "s": 3328, "text": "This is one of the most interesting aspects of celluloid, here we have the capacity to make the plot very dynamic." }, { "code": null, "e": 3634, "s": 3443, "text": "In this example I plotted two normal distributions with distinct means but the same standard deviation and then I changed this standard deviation to evaluate the impact it has on each curve." }, { "code": null, "e": 3898, "s": 3634, "text": "I put the current standard deviation on the title and the real mean as the label of each curve. I had to pass the calculated label as a tuple because I used two curves, if it was only one I could’ve used just a like plt.legend([calculated_label]), which is simple" }, { "code": null, "e": 4918, "s": 3898, "text": "from celluloid import Camera # getting the cameraimport matplotlib.pyplot as pltimport numpy as npimport seaborn as snsfrom IPython.display import HTMLstd = 3 # start std Am = 15. # mean of first normalBm = 12.5 # mean of second normalfig, ax = plt.subplots(figsize=(9,6)) # empty figcamera = Camera(fig)for j in range(10): plt.ylim((0, 0.2)) # setting up the limits (or else it will auto ajust plt.xlim((-50, 50)) A = np.random.normal(Am, std, size=(1000)) # creating the 1000-sized normals B = np.random.normal(Bm, std, size=(1000)) A_plot = sns.distplot(A, color='red') B_plot = sns.distplot(B, color='blue') plt.legend(( 'Real Mean A: {:.2f}'.format(np.mean(A)), 'Real Mean B: {:.2f}'.format(np.mean(B)) )) ax.text(0.5, 1.01, \"Standard Deviation = \"+str(std), transform=ax.transAxes) # making the dynamic title camera.snap() # camera snapshot std += 1 # incrementing the stdanim = camera.animate() # animating the plotsHTML(anim.to_html5_video())" }, { "code": null, "e": 5138, "s": 4918, "text": "This were just my basic ideas of how to use celluloid, but truth be told the possibilities are infinite and I’ve used in several applications, even to demonstrate how some Machine Learning Algorithms learn check it out." } ]
Adding two polynomials using Linked List - GeeksforGeeks
07 Apr, 2022 Given two polynomial numbers represented by a linked list. Write a function that add these lists means add the coefficients who have same variable powers.Example: Input: 1st number = 5x2 + 4x1 + 2x0 2nd number = -5x1 - 5x0 Output: 5x2-1x1-3x0 Input: 1st number = 5x3 + 4x2 + 2x0 2nd number = 5x^1 - 5x^0 Output: 5x3 + 4x2 + 5x1 - 3x0 CPP Java // C++ program for addition of two polynomials// using Linked Lists#include <bits/stdc++.h>using namespace std; // Node structure containing power and coefficient of// variablestruct Node { int coeff; int pow; struct Node* next;}; // Function to create new nodevoid create_node(int x, int y, struct Node** temp){ struct Node *r, *z; z = *temp; if (z == NULL) { r = (struct Node*)malloc(sizeof(struct Node)); r->coeff = x; r->pow = y; *temp = r; r->next = (struct Node*)malloc(sizeof(struct Node)); r = r->next; r->next = NULL; } else { r->coeff = x; r->pow = y; r->next = (struct Node*)malloc(sizeof(struct Node)); r = r->next; r->next = NULL; }} // Function Adding two polynomial numbersvoid polyadd(struct Node* poly1, struct Node* poly2, struct Node* poly){ while (poly1->next && poly2->next) { // If power of 1st polynomial is greater then 2nd, // then store 1st as it is and move its pointer if (poly1->pow > poly2->pow) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } // If power of 2nd polynomial is greater then 1st, // then store 2nd as it is and move its pointer else if (poly1->pow < poly2->pow) { poly->pow = poly2->pow; poly->coeff = poly2->coeff; poly2 = poly2->next; } // If power of both polynomial numbers is same then // add their coefficients else { poly->pow = poly1->pow; poly->coeff = poly1->coeff + poly2->coeff; poly1 = poly1->next; poly2 = poly2->next; } // Dynamically create new node poly->next = (struct Node*)malloc(sizeof(struct Node)); poly = poly->next; poly->next = NULL; } while (poly1->next || poly2->next) { if (poly1->next) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } if (poly2->next) { poly->pow = poly2->pow; poly->coeff = poly2->coeff; poly2 = poly2->next; } poly->next = (struct Node*)malloc(sizeof(struct Node)); poly = poly->next; poly->next = NULL; }} // Display Linked listvoid show(struct Node* node){ while (node->next != NULL) { printf("%dx^%d", node->coeff, node->pow); node = node->next; if (node->coeff >= 0) { if (node->next != NULL) printf("+"); } }} // Driver codeint main(){ struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL; // Create first list of 5x^2 + 4x^1 + 2x^0 create_node(5, 2, &poly1); create_node(4, 1, &poly1); create_node(2, 0, &poly1); // Create second list of -5x^1 - 5x^0 create_node(-5, 1, &poly2); create_node(-5, 0, &poly2); printf("1st Number: "); show(poly1); printf("\n2nd Number: "); show(poly2); poly = (struct Node*)malloc(sizeof(struct Node)); // Function add two polynomial numbers polyadd(poly1, poly2, poly); // Display resultant List printf("\nAdded polynomial: "); show(poly); return 0;} import java.io.*;import java.util.Scanner; class Polynomial { public static Node addPolynomial(Node p1, Node p2) { Node a = p1, b = p2, newHead = new Node(0, 0), c = newHead; while (a != null || b != null) { if (a == null) { c.next = b; break; } else if (b == null) { c.next = a; break; } else if (a.pow == b.pow) { c.next = new Node(a.coeff + b.coeff, a.pow); a = a.next; b = b.next; } else if (a.pow > b.pow) { c.next = new Node(a.coeff, a.pow); a = a.next; } else if (a.pow < b.pow) { c.next = new Node(b.coeff, b.pow); b = b.next; } c = c.next; } return newHead.next; }} // Utilities for Linked List Nodesclass Node { int coeff; int pow; Node next; Node(int a, int b) { coeff = a; pow = b; next = null; }} //Linked List main classclass LinkedList { public static void main(String args[]) { Node start1 = null, cur1 = null, start2 = null, cur2 = null; int[] list1_coeff = { 5, 4, 2 }; int[] list1_pow = { 2, 1, 0 }; int n = list1_coeff.length; int i = 0; while (n-- > 0) { int a = list1_coeff[i]; int b = list1_pow[i]; Node ptr = new Node(a, b); if (start1 == null) { start1 = ptr; cur1 = ptr; } else { cur1.next = ptr; cur1 = ptr; } i++; } int[] list2_coeff = { -5, -5 }; int[] list2_pow = { 1, 0 }; n = list2_coeff.length; i = 0; while (n-- > 0) { int a = list2_coeff[i]; int b = list2_pow[i]; Node ptr = new Node(a, b); if (start2 == null) { start2 = ptr; cur2 = ptr; } else { cur2.next = ptr; cur2 = ptr; } i++; } Polynomial obj = new Polynomial(); Node sum = obj.addPolynomial(start1, start2); Node trav = sum; while (trav != null) { System.out.print(trav.coeff + "x^" + trav.pow); if (trav.next != null) System.out.print(" + "); trav = trav.next; } System.out.println(); }} 1st Number: 5x^2+4x^1+2x^0 2nd Number: -5x^1-5x^0 Added polynomial: 5x^2-1x^1-3x^0 Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively. Recursive Method : Algorithm : If both the numbers are null then returnelse if compare the power, if same then add the coefficients and recursively call addPolynomials on the next elements of both the numbers.else if the power of first number is greater then print the current element of first number and recursively call addPolynomial on the next element of the first number and current element of the second number.else print the current element of the second number and recursively call addPolynomial on the current element of first number and next element of second number. If both the numbers are null then return else if compare the power, if same then add the coefficients and recursively call addPolynomials on the next elements of both the numbers. else if the power of first number is greater then print the current element of first number and recursively call addPolynomial on the next element of the first number and current element of the second number. else print the current element of the second number and recursively call addPolynomial on the current element of first number and next element of second number. C++ Javascript //Program to add two polynomials represented in linkedlist using recursion#include<iostream>using namespace std; class Node{public: int coeff,power; Node *next; Node(int coeff, int power){ this->coeff = coeff; this->power = power; this->next = NULL; }}; void addPolynomials(Node *head1, Node *head2){ if(head1==NULL && head2==NULL) return; else if(head1->power == head2->power){ cout<<" "<<head1->coeff + head2->coeff<<"x^"<<head1->power<<" "; addPolynomials(head1->next,head2->next); } else if(head1->power > head2->power){ cout<<" "<<head1->coeff<<"x^"<<head1->power<<" "; addPolynomials(head1->next,head2); } else{ cout<<" "<<head2->coeff<<"x^"<<head2->power<<" "; addPolynomials(head1,head2->next); }} void insert(Node *head, int coeff, int power){ Node *new_node = new Node(coeff,power); while(head->next!=NULL){ head = head->next; } head->next = new_node;} void printList(Node *head){ cout<<"Linked List"<<endl; while(head!=NULL){ cout<<" "<<head->coeff<<"x"<<"^"<<head->power; head = head->next; }} int main(){ Node *head=new Node(5,2); insert(head,4,1); Node *head2 = new Node(6,2); insert(head2,4,1); printList(head); cout<<endl; printList(head2); cout<<endl<<"Addition:"<<endl; addPolynomials(head,head2); return 0;} //This code is contributed by Akshita Patel <script> // JavaScript Program to add two polynomials// represented in linkedlist using recursion class Node{ constructor(coeff, power){ this.coeff = coeff; this.power = power; this.next = null; }} function addPolynomials(head1, head2){ document.write(head1.power, head2.power) if(head1==null && head2==null) return; else if(head1.power == head2.power){ document.write(` ${head1.coeff + head2.coeff}x^${head1.power} `); addPolynomials(head1.next, head2.next); } else if(head1.power > head2.power){ document.write(` ${head1.coeff}x^${head1.power} `); addPolynomials(head1.next, head2); } else{ document.write(` ${head2.coeff}x^${head2.power} `); addPolynomials(head1, head2.next); }} function insert(head, coeff, power){ let new_node = new Node(coeff,power); while(head.next!=null){ head = head.next; } head.next = new_node;} function printList(head){ document.write("Linked List","</br>"); while(head != null){ document.write(` ${head.coeff}x^${head.power}`); head = head.next; }} // driver codelet head = new Node(5,2);insert(head,4,1);let head2 = new Node(6,2);insert(head2,4,1);printList(head);document.write("</br>");printList(head2);document.write("</br>");document.write("Addition:");document.write("</br>");addPolynomials(head,head2); // This code is contributed by shinjanpatra </script> Linked List 5x^2 4x^1 Linked List 6x^2 4x^1 Addition: 11x^2 8x^1 Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively. Related Article: Add two polynomial numbers using Arrays This article is contributed by Akash Gupta and Akshita Patel. 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. aniket173000 rexj8 akshitapatel02 shinjanpatra Amazon Linked-List-Polynomial maths-polynomial Linked List Mathematical Amazon Linked List Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Linked List vs Array Doubly Linked List | Set 1 (Introduction and Insertion) Detect loop in a linked list Merge two sorted linked lists Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string Coin Change | DP-7
[ { "code": null, "e": 25324, "s": 25296, "text": "\n07 Apr, 2022" }, { "code": null, "e": 25489, "s": 25324, "text": "Given two polynomial numbers represented by a linked list. Write a function that add these lists means add the coefficients who have same variable powers.Example: " }, { "code": null, "e": 25696, "s": 25489, "text": "Input:\n 1st number = 5x2 + 4x1 + 2x0\n 2nd number = -5x1 - 5x0\nOutput:\n 5x2-1x1-3x0\nInput:\n 1st number = 5x3 + 4x2 + 2x0\n 2nd number = 5x^1 - 5x^0\nOutput:\n 5x3 + 4x2 + 5x1 - 3x0" }, { "code": null, "e": 25704, "s": 25700, "text": "CPP" }, { "code": null, "e": 25709, "s": 25704, "text": "Java" }, { "code": "// C++ program for addition of two polynomials// using Linked Lists#include <bits/stdc++.h>using namespace std; // Node structure containing power and coefficient of// variablestruct Node { int coeff; int pow; struct Node* next;}; // Function to create new nodevoid create_node(int x, int y, struct Node** temp){ struct Node *r, *z; z = *temp; if (z == NULL) { r = (struct Node*)malloc(sizeof(struct Node)); r->coeff = x; r->pow = y; *temp = r; r->next = (struct Node*)malloc(sizeof(struct Node)); r = r->next; r->next = NULL; } else { r->coeff = x; r->pow = y; r->next = (struct Node*)malloc(sizeof(struct Node)); r = r->next; r->next = NULL; }} // Function Adding two polynomial numbersvoid polyadd(struct Node* poly1, struct Node* poly2, struct Node* poly){ while (poly1->next && poly2->next) { // If power of 1st polynomial is greater then 2nd, // then store 1st as it is and move its pointer if (poly1->pow > poly2->pow) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } // If power of 2nd polynomial is greater then 1st, // then store 2nd as it is and move its pointer else if (poly1->pow < poly2->pow) { poly->pow = poly2->pow; poly->coeff = poly2->coeff; poly2 = poly2->next; } // If power of both polynomial numbers is same then // add their coefficients else { poly->pow = poly1->pow; poly->coeff = poly1->coeff + poly2->coeff; poly1 = poly1->next; poly2 = poly2->next; } // Dynamically create new node poly->next = (struct Node*)malloc(sizeof(struct Node)); poly = poly->next; poly->next = NULL; } while (poly1->next || poly2->next) { if (poly1->next) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } if (poly2->next) { poly->pow = poly2->pow; poly->coeff = poly2->coeff; poly2 = poly2->next; } poly->next = (struct Node*)malloc(sizeof(struct Node)); poly = poly->next; poly->next = NULL; }} // Display Linked listvoid show(struct Node* node){ while (node->next != NULL) { printf(\"%dx^%d\", node->coeff, node->pow); node = node->next; if (node->coeff >= 0) { if (node->next != NULL) printf(\"+\"); } }} // Driver codeint main(){ struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL; // Create first list of 5x^2 + 4x^1 + 2x^0 create_node(5, 2, &poly1); create_node(4, 1, &poly1); create_node(2, 0, &poly1); // Create second list of -5x^1 - 5x^0 create_node(-5, 1, &poly2); create_node(-5, 0, &poly2); printf(\"1st Number: \"); show(poly1); printf(\"\\n2nd Number: \"); show(poly2); poly = (struct Node*)malloc(sizeof(struct Node)); // Function add two polynomial numbers polyadd(poly1, poly2, poly); // Display resultant List printf(\"\\nAdded polynomial: \"); show(poly); return 0;}", "e": 28972, "s": 25709, "text": null }, { "code": "import java.io.*;import java.util.Scanner; class Polynomial { public static Node addPolynomial(Node p1, Node p2) { Node a = p1, b = p2, newHead = new Node(0, 0), c = newHead; while (a != null || b != null) { if (a == null) { c.next = b; break; } else if (b == null) { c.next = a; break; } else if (a.pow == b.pow) { c.next = new Node(a.coeff + b.coeff, a.pow); a = a.next; b = b.next; } else if (a.pow > b.pow) { c.next = new Node(a.coeff, a.pow); a = a.next; } else if (a.pow < b.pow) { c.next = new Node(b.coeff, b.pow); b = b.next; } c = c.next; } return newHead.next; }} // Utilities for Linked List Nodesclass Node { int coeff; int pow; Node next; Node(int a, int b) { coeff = a; pow = b; next = null; }} //Linked List main classclass LinkedList { public static void main(String args[]) { Node start1 = null, cur1 = null, start2 = null, cur2 = null; int[] list1_coeff = { 5, 4, 2 }; int[] list1_pow = { 2, 1, 0 }; int n = list1_coeff.length; int i = 0; while (n-- > 0) { int a = list1_coeff[i]; int b = list1_pow[i]; Node ptr = new Node(a, b); if (start1 == null) { start1 = ptr; cur1 = ptr; } else { cur1.next = ptr; cur1 = ptr; } i++; } int[] list2_coeff = { -5, -5 }; int[] list2_pow = { 1, 0 }; n = list2_coeff.length; i = 0; while (n-- > 0) { int a = list2_coeff[i]; int b = list2_pow[i]; Node ptr = new Node(a, b); if (start2 == null) { start2 = ptr; cur2 = ptr; } else { cur2.next = ptr; cur2 = ptr; } i++; } Polynomial obj = new Polynomial(); Node sum = obj.addPolynomial(start1, start2); Node trav = sum; while (trav != null) { System.out.print(trav.coeff + \"x^\" + trav.pow); if (trav.next != null) System.out.print(\" + \"); trav = trav.next; } System.out.println(); }}", "e": 31557, "s": 28972, "text": null }, { "code": null, "e": 31640, "s": 31557, "text": "1st Number: 5x^2+4x^1+2x^0\n2nd Number: -5x^1-5x^0\nAdded polynomial: 5x^2-1x^1-3x^0" }, { "code": null, "e": 31741, "s": 31640, "text": "Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively. " }, { "code": null, "e": 31760, "s": 31741, "text": "Recursive Method :" }, { "code": null, "e": 31772, "s": 31760, "text": "Algorithm :" }, { "code": null, "e": 32321, "s": 31772, "text": "If both the numbers are null then returnelse if compare the power, if same then add the coefficients and recursively call addPolynomials on the next elements of both the numbers.else if the power of first number is greater then print the current element of first number and recursively call addPolynomial on the next element of the first number and current element of the second number.else print the current element of the second number and recursively call addPolynomial on the current element of first number and next element of second number." }, { "code": null, "e": 32362, "s": 32321, "text": "If both the numbers are null then return" }, { "code": null, "e": 32503, "s": 32362, "text": "else if compare the power, if same then add the coefficients and recursively call addPolynomials on the next elements of both the numbers." }, { "code": null, "e": 32712, "s": 32503, "text": "else if the power of first number is greater then print the current element of first number and recursively call addPolynomial on the next element of the first number and current element of the second number." }, { "code": null, "e": 32873, "s": 32712, "text": "else print the current element of the second number and recursively call addPolynomial on the current element of first number and next element of second number." }, { "code": null, "e": 32877, "s": 32873, "text": "C++" }, { "code": null, "e": 32888, "s": 32877, "text": "Javascript" }, { "code": "//Program to add two polynomials represented in linkedlist using recursion#include<iostream>using namespace std; class Node{public: int coeff,power; Node *next; Node(int coeff, int power){ this->coeff = coeff; this->power = power; this->next = NULL; }}; void addPolynomials(Node *head1, Node *head2){ if(head1==NULL && head2==NULL) return; else if(head1->power == head2->power){ cout<<\" \"<<head1->coeff + head2->coeff<<\"x^\"<<head1->power<<\" \"; addPolynomials(head1->next,head2->next); } else if(head1->power > head2->power){ cout<<\" \"<<head1->coeff<<\"x^\"<<head1->power<<\" \"; addPolynomials(head1->next,head2); } else{ cout<<\" \"<<head2->coeff<<\"x^\"<<head2->power<<\" \"; addPolynomials(head1,head2->next); }} void insert(Node *head, int coeff, int power){ Node *new_node = new Node(coeff,power); while(head->next!=NULL){ head = head->next; } head->next = new_node;} void printList(Node *head){ cout<<\"Linked List\"<<endl; while(head!=NULL){ cout<<\" \"<<head->coeff<<\"x\"<<\"^\"<<head->power; head = head->next; }} int main(){ Node *head=new Node(5,2); insert(head,4,1); Node *head2 = new Node(6,2); insert(head2,4,1); printList(head); cout<<endl; printList(head2); cout<<endl<<\"Addition:\"<<endl; addPolynomials(head,head2); return 0;} //This code is contributed by Akshita Patel", "e": 34231, "s": 32888, "text": null }, { "code": "<script> // JavaScript Program to add two polynomials// represented in linkedlist using recursion class Node{ constructor(coeff, power){ this.coeff = coeff; this.power = power; this.next = null; }} function addPolynomials(head1, head2){ document.write(head1.power, head2.power) if(head1==null && head2==null) return; else if(head1.power == head2.power){ document.write(` ${head1.coeff + head2.coeff}x^${head1.power} `); addPolynomials(head1.next, head2.next); } else if(head1.power > head2.power){ document.write(` ${head1.coeff}x^${head1.power} `); addPolynomials(head1.next, head2); } else{ document.write(` ${head2.coeff}x^${head2.power} `); addPolynomials(head1, head2.next); }} function insert(head, coeff, power){ let new_node = new Node(coeff,power); while(head.next!=null){ head = head.next; } head.next = new_node;} function printList(head){ document.write(\"Linked List\",\"</br>\"); while(head != null){ document.write(` ${head.coeff}x^${head.power}`); head = head.next; }} // driver codelet head = new Node(5,2);insert(head,4,1);let head2 = new Node(6,2);insert(head2,4,1);printList(head);document.write(\"</br>\");printList(head2);document.write(\"</br>\");document.write(\"Addition:\");document.write(\"</br>\");addPolynomials(head,head2); // This code is contributed by shinjanpatra </script>", "e": 35596, "s": 34231, "text": null }, { "code": null, "e": 35666, "s": 35596, "text": "Linked List\n 5x^2 4x^1\nLinked List\n 6x^2 4x^1\nAddition:\n 11x^2 8x^1 " }, { "code": null, "e": 35766, "s": 35666, "text": "Time Complexity: O(m + n) where m and n are number of nodes in first and second lists respectively." }, { "code": null, "e": 36261, "s": 35766, "text": "Related Article: Add two polynomial numbers using Arrays This article is contributed by Akash Gupta and Akshita Patel. 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": 36274, "s": 36261, "text": "aniket173000" }, { "code": null, "e": 36280, "s": 36274, "text": "rexj8" }, { "code": null, "e": 36295, "s": 36280, "text": "akshitapatel02" }, { "code": null, "e": 36308, "s": 36295, "text": "shinjanpatra" }, { "code": null, "e": 36315, "s": 36308, "text": "Amazon" }, { "code": null, "e": 36338, "s": 36315, "text": "Linked-List-Polynomial" }, { "code": null, "e": 36355, "s": 36338, "text": "maths-polynomial" }, { "code": null, "e": 36367, "s": 36355, "text": "Linked List" }, { "code": null, "e": 36380, "s": 36367, "text": "Mathematical" }, { "code": null, "e": 36387, "s": 36380, "text": "Amazon" }, { "code": null, "e": 36399, "s": 36387, "text": "Linked List" }, { "code": null, "e": 36412, "s": 36399, "text": "Mathematical" }, { "code": null, "e": 36510, "s": 36412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36529, "s": 36510, "text": "LinkedList in Java" }, { "code": null, "e": 36550, "s": 36529, "text": "Linked List vs Array" }, { "code": null, "e": 36606, "s": 36550, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 36635, "s": 36606, "text": "Detect loop in a linked list" }, { "code": null, "e": 36665, "s": 36635, "text": "Merge two sorted linked lists" }, { "code": null, "e": 36695, "s": 36665, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36710, "s": 36695, "text": "C++ Data Types" }, { "code": null, "e": 36753, "s": 36710, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 36813, "s": 36753, "text": "Write a program to print all permutations of a given string" } ]
Securing API Keys with Environment Variables Using Anaconda | by Raymond Willey | Towards Data Science
If you are reading this, I assume you are already familiar with APIs, tokens, private keys, and public keys. Your private and public keys serve as a form of authentication to identify you and track your activity with a developer’s API. What this means is that, if someone got ahold of your keys, they could access data in the API while impersonating you, which can have some dire consequences. The challenge faced by most up-and-coming data scientists is that they want to promote their project work in a public forum. If any of those projects use APIs, the individual will have to load their keys into their notebooks. In other words, making the notebook public means jeopardizing the security of the API key. There are a few common solutions to this problem: the first is to replace the key with something like ****** or YOUR_PRIVATE_KEY_HERE. This works to a certain extent, but the methodology is fallible to human error. With multiple commits on a single project, the token must be removed and re-added each time. The second you push a commit and forget to clear the key, it is compromised. It’s not a matter of if this will happen, but when. Another option is to save API keys to a separate JSON file, read the private key, and exclude the file when pushing to GitHub. While this is a little better, the problem here is that others wanting to explore your work must make edits to the forked repository to run the code. Moreover, this does not fully eliminate the potential for human error. Wouldn’t it be great if there was a way to save keys and tokens to our system files to be called when desired? And wouldn’t it be even better if others can use the same code to call their own keys and tokens from their own systems? As it turns out, there is a way: environment variables! Environment variables are precisely what their name implies: variables saved in the local environment that can be called into any project. Because they are not part of the repository itself, there is no need to restrict the information that is pushed to GitHub. In the example below, a private API key is already saved as an environment variable called PRIVATE_API_KEY. We will look at how to create the variable itself a bit later. import osapi_key = os.environ.get("PRIVATE_API_KEY") As we can see, this looks pretty clean and simple. Whenever we need to use the key, all we have to do is call the api_key variable. More seasoned data scientists reviewing this code should immediately recognize the need to use their own private keys, saving them in their own environments. Once completed, the program should run as-is without any hiccups. The one caveat here is that the reviewer will need to save the API key using the same variable name. If the person already has the relevant key saved to their environment using a different variable name, they will likely opt to modify the code rather than their environment. What would make this process even more elegant is if API developers provided recommended naming conventions for these keys in their documentation. But that’s a topic for another day. In this post, we are not going to get into the best practices for managing environments across projects. Instead, I am assuming you are already working in the proper environment and know how to switch between them using Anaconda. If you are not familiar with this, I would recommend checking out this video as a primer for the rest of this post. The overall process for creating these variables is as follows: Navigate to the environment path for storing packages and details.Create files and directories for activating variables when called and deactivating them when done using them.Add the variables into the relevant files. Navigate to the environment path for storing packages and details. Create files and directories for activating variables when called and deactivating them when done using them. Add the variables into the relevant files. I will show you how to handle all three of these steps in macOS, Linux, and Windows. All instructions are adapted directly from the Anaconda documentation. The following commands can be used to handle steps 1 and 2 using the terminal: cd $CONDA_PREFIXmkdir -p ./etc/conda/activate.dmkdir -p ./etc/conda/deactivate.dtouch ./etc/conda/activate.d/env_vars.shtouch ./etc/conda/deactivate.d/env_vars.sh So, we now have two files called env_vars.sh that are each stored in separate directories. We need to open these files in a text editor of your choice to create the variables. For the file in the activate.d directory, we will add the following: #!/bin/shexport PRIVATE_API_KEY='YOUR_PRIVATE_KEY_HERE' For the file in the deactivate.d directory, we add this: #!/bin/shunset MY_KEY The first line #!/bin/sh lets the operating system know that the files are shell scripts to ensure the export and unset commands are properly executed. Once these files are saved and closed, enter conda activate analytics into the terminal to save YOUR_PRIATE_KEY_HERE to the environment variable PRIVATE_API_KEY. When done using these variables, they can be erased from the environment using the conda deactivate. The following commands can be used to handle steps 1 and 2 using the command shell: cd %CONDA_PREFIX%mkdir .\etc\conda\activate.dmkdir .\etc\conda\deactivate.dtype NUL > .\etc\conda\activate.d\env_vars.battype NUL > .\etc\conda\deactivate.d\env_vars.bat So, we now have two files called env_vars.bat that are each stored in separate directories. We need to open these files in a text editor of your choice to create the variables. For the file in the activate.d directory, we will add the following: set PRIVATE_API_KEY='YOUR_PRIVATE_KEY_HERE' For the file in the deactivate.d directory, we add this: unset PRIVATE_API_KEY= Once these files are saved and closed, enter conda activate analytics into the terminal to save YOUR_PRIATE_KEY_HERE to the environment variable PRIVATE_API_KEY. When done using these variables, they can be erased from the environment using the conda deactivate. As you can see, though there are a few steps to saving your API keys as environment variables, there is nothing inherently difficult or complicated about it. Once in place, the variables are quick and easy to access, and they can be deactivated with a single command when you are done with them. It is much more efficient than adding and removing keys every time you want to make an update or push a new commit to GitHub. And it gives you more safety and security when showcasing your projects to the outside world.
[ { "code": null, "e": 566, "s": 172, "text": "If you are reading this, I assume you are already familiar with APIs, tokens, private keys, and public keys. Your private and public keys serve as a form of authentication to identify you and track your activity with a developer’s API. What this means is that, if someone got ahold of your keys, they could access data in the API while impersonating you, which can have some dire consequences." }, { "code": null, "e": 883, "s": 566, "text": "The challenge faced by most up-and-coming data scientists is that they want to promote their project work in a public forum. If any of those projects use APIs, the individual will have to load their keys into their notebooks. In other words, making the notebook public means jeopardizing the security of the API key." }, { "code": null, "e": 1668, "s": 883, "text": "There are a few common solutions to this problem: the first is to replace the key with something like ****** or YOUR_PRIVATE_KEY_HERE. This works to a certain extent, but the methodology is fallible to human error. With multiple commits on a single project, the token must be removed and re-added each time. The second you push a commit and forget to clear the key, it is compromised. It’s not a matter of if this will happen, but when. Another option is to save API keys to a separate JSON file, read the private key, and exclude the file when pushing to GitHub. While this is a little better, the problem here is that others wanting to explore your work must make edits to the forked repository to run the code. Moreover, this does not fully eliminate the potential for human error." }, { "code": null, "e": 1956, "s": 1668, "text": "Wouldn’t it be great if there was a way to save keys and tokens to our system files to be called when desired? And wouldn’t it be even better if others can use the same code to call their own keys and tokens from their own systems? As it turns out, there is a way: environment variables!" }, { "code": null, "e": 2389, "s": 1956, "text": "Environment variables are precisely what their name implies: variables saved in the local environment that can be called into any project. Because they are not part of the repository itself, there is no need to restrict the information that is pushed to GitHub. In the example below, a private API key is already saved as an environment variable called PRIVATE_API_KEY. We will look at how to create the variable itself a bit later." }, { "code": null, "e": 2442, "s": 2389, "text": "import osapi_key = os.environ.get(\"PRIVATE_API_KEY\")" }, { "code": null, "e": 2798, "s": 2442, "text": "As we can see, this looks pretty clean and simple. Whenever we need to use the key, all we have to do is call the api_key variable. More seasoned data scientists reviewing this code should immediately recognize the need to use their own private keys, saving them in their own environments. Once completed, the program should run as-is without any hiccups." }, { "code": null, "e": 3256, "s": 2798, "text": "The one caveat here is that the reviewer will need to save the API key using the same variable name. If the person already has the relevant key saved to their environment using a different variable name, they will likely opt to modify the code rather than their environment. What would make this process even more elegant is if API developers provided recommended naming conventions for these keys in their documentation. But that’s a topic for another day." }, { "code": null, "e": 3602, "s": 3256, "text": "In this post, we are not going to get into the best practices for managing environments across projects. Instead, I am assuming you are already working in the proper environment and know how to switch between them using Anaconda. If you are not familiar with this, I would recommend checking out this video as a primer for the rest of this post." }, { "code": null, "e": 3666, "s": 3602, "text": "The overall process for creating these variables is as follows:" }, { "code": null, "e": 3884, "s": 3666, "text": "Navigate to the environment path for storing packages and details.Create files and directories for activating variables when called and deactivating them when done using them.Add the variables into the relevant files." }, { "code": null, "e": 3951, "s": 3884, "text": "Navigate to the environment path for storing packages and details." }, { "code": null, "e": 4061, "s": 3951, "text": "Create files and directories for activating variables when called and deactivating them when done using them." }, { "code": null, "e": 4104, "s": 4061, "text": "Add the variables into the relevant files." }, { "code": null, "e": 4260, "s": 4104, "text": "I will show you how to handle all three of these steps in macOS, Linux, and Windows. All instructions are adapted directly from the Anaconda documentation." }, { "code": null, "e": 4339, "s": 4260, "text": "The following commands can be used to handle steps 1 and 2 using the terminal:" }, { "code": null, "e": 4502, "s": 4339, "text": "cd $CONDA_PREFIXmkdir -p ./etc/conda/activate.dmkdir -p ./etc/conda/deactivate.dtouch ./etc/conda/activate.d/env_vars.shtouch ./etc/conda/deactivate.d/env_vars.sh" }, { "code": null, "e": 4747, "s": 4502, "text": "So, we now have two files called env_vars.sh that are each stored in separate directories. We need to open these files in a text editor of your choice to create the variables. For the file in the activate.d directory, we will add the following:" }, { "code": null, "e": 4803, "s": 4747, "text": "#!/bin/shexport PRIVATE_API_KEY='YOUR_PRIVATE_KEY_HERE'" }, { "code": null, "e": 4860, "s": 4803, "text": "For the file in the deactivate.d directory, we add this:" }, { "code": null, "e": 4882, "s": 4860, "text": "#!/bin/shunset MY_KEY" }, { "code": null, "e": 5034, "s": 4882, "text": "The first line #!/bin/sh lets the operating system know that the files are shell scripts to ensure the export and unset commands are properly executed." }, { "code": null, "e": 5297, "s": 5034, "text": "Once these files are saved and closed, enter conda activate analytics into the terminal to save YOUR_PRIATE_KEY_HERE to the environment variable PRIVATE_API_KEY. When done using these variables, they can be erased from the environment using the conda deactivate." }, { "code": null, "e": 5381, "s": 5297, "text": "The following commands can be used to handle steps 1 and 2 using the command shell:" }, { "code": null, "e": 5551, "s": 5381, "text": "cd %CONDA_PREFIX%mkdir .\\etc\\conda\\activate.dmkdir .\\etc\\conda\\deactivate.dtype NUL > .\\etc\\conda\\activate.d\\env_vars.battype NUL > .\\etc\\conda\\deactivate.d\\env_vars.bat" }, { "code": null, "e": 5797, "s": 5551, "text": "So, we now have two files called env_vars.bat that are each stored in separate directories. We need to open these files in a text editor of your choice to create the variables. For the file in the activate.d directory, we will add the following:" }, { "code": null, "e": 5841, "s": 5797, "text": "set PRIVATE_API_KEY='YOUR_PRIVATE_KEY_HERE'" }, { "code": null, "e": 5898, "s": 5841, "text": "For the file in the deactivate.d directory, we add this:" }, { "code": null, "e": 5921, "s": 5898, "text": "unset PRIVATE_API_KEY=" }, { "code": null, "e": 6184, "s": 5921, "text": "Once these files are saved and closed, enter conda activate analytics into the terminal to save YOUR_PRIATE_KEY_HERE to the environment variable PRIVATE_API_KEY. When done using these variables, they can be erased from the environment using the conda deactivate." } ]
Difference between super and super() in Java with Examples - GeeksforGeeks
14 Sep, 2021 In java it is predefined that the ‘super’ word is somewhere related to the parent class. If we need to brief and justify the title in one go then the super keyword in java refers to dealing with parent class object while super() deals with parent class constructor. We will be covering the article first discussing the concept of a super keyword followed by super() later onwards. Concept: super keyword The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came into the picture with the concept of Inheritance. Basically this form of super is used to initialize superclass variables when there is no constructor present in superclass. On the other hand, it is generally used to access the specific variable of a superclass. Example Java // Java Program to Illustrate super keyword // Class 1// Base class// Here it is vehicle classclass Vehicle { // Attribute int maxSpeed = 120;} // Class 2// sub class Car extending vehicleclass Car extends Vehicle { int maxSpeed = 180; // Method void display() { // Printing maxSpeed of parent class (vehicle) as // super keyword refers to parent class System.out.println("Maximum Speed: " + super.maxSpeed); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of child class Car small = new Car(); // Calling out method defined inside child class small.display(); }} Maximum Speed: 120 Now we already have seen that super keyword refers to parent class which can be perceived from the output itself. Now let us dwell onto second concept known as super() which more programmers are lesser aware and do not implement same barely knowing it all Concept: super() The super keyword can also be used to access the parent class constructor by adding ‘()’ after it, i.e. super(). Also do remember that ‘super()’ can call both parametric as well as non-parametric constructors depending upon the situation. Example: Java // Java code to demonstrate super() // Class 1// Helper class// Parent class - Superclassclass Person { // Constructor of superclass Person() { // Print statement of this class System.out.println("Person class Constructor"); }} // Class 2// Helper class// Subclass extending the above superclassclass Student extends Person { Student() { // Invoking the parent class constructor // with the usage of super() word super(); // Print styatement whenever subclass constructor is // called System.out.println("Student class Constructor"); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of subclass // inside main() method Student s = new Student(); }} Person class Constructor Student class Constructor Finally after having an adequate understanding of the above topics let us do finally conclude out differences between them which are listed in the tabular format below as follows: ultraint simmytarika5 java-basics Difference Between Java Java 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24882, "s": 24854, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25263, "s": 24882, "text": "In java it is predefined that the ‘super’ word is somewhere related to the parent class. If we need to brief and justify the title in one go then the super keyword in java refers to dealing with parent class object while super() deals with parent class constructor. We will be covering the article first discussing the concept of a super keyword followed by super() later onwards." }, { "code": null, "e": 25286, "s": 25263, "text": "Concept: super keyword" }, { "code": null, "e": 25668, "s": 25286, "text": "The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came into the picture with the concept of Inheritance. Basically this form of super is used to initialize superclass variables when there is no constructor present in superclass. On the other hand, it is generally used to access the specific variable of a superclass." }, { "code": null, "e": 25676, "s": 25668, "text": "Example" }, { "code": null, "e": 25681, "s": 25676, "text": "Java" }, { "code": "// Java Program to Illustrate super keyword // Class 1// Base class// Here it is vehicle classclass Vehicle { // Attribute int maxSpeed = 120;} // Class 2// sub class Car extending vehicleclass Car extends Vehicle { int maxSpeed = 180; // Method void display() { // Printing maxSpeed of parent class (vehicle) as // super keyword refers to parent class System.out.println(\"Maximum Speed: \" + super.maxSpeed); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of child class Car small = new Car(); // Calling out method defined inside child class small.display(); }}", "e": 26432, "s": 25681, "text": null }, { "code": null, "e": 26451, "s": 26432, "text": "Maximum Speed: 120" }, { "code": null, "e": 26710, "s": 26451, "text": "Now we already have seen that super keyword refers to parent class which can be perceived from the output itself. Now let us dwell onto second concept known as super() which more programmers are lesser aware and do not implement same barely knowing it all " }, { "code": null, "e": 26727, "s": 26710, "text": "Concept: super()" }, { "code": null, "e": 26966, "s": 26727, "text": "The super keyword can also be used to access the parent class constructor by adding ‘()’ after it, i.e. super(). Also do remember that ‘super()’ can call both parametric as well as non-parametric constructors depending upon the situation." }, { "code": null, "e": 26976, "s": 26966, "text": "Example: " }, { "code": null, "e": 26981, "s": 26976, "text": "Java" }, { "code": "// Java code to demonstrate super() // Class 1// Helper class// Parent class - Superclassclass Person { // Constructor of superclass Person() { // Print statement of this class System.out.println(\"Person class Constructor\"); }} // Class 2// Helper class// Subclass extending the above superclassclass Student extends Person { Student() { // Invoking the parent class constructor // with the usage of super() word super(); // Print styatement whenever subclass constructor is // called System.out.println(\"Student class Constructor\"); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of subclass // inside main() method Student s = new Student(); }}", "e": 27815, "s": 26981, "text": null }, { "code": null, "e": 27866, "s": 27815, "text": "Person class Constructor\nStudent class Constructor" }, { "code": null, "e": 28048, "s": 27868, "text": "Finally after having an adequate understanding of the above topics let us do finally conclude out differences between them which are listed in the tabular format below as follows:" }, { "code": null, "e": 28059, "s": 28050, "text": "ultraint" }, { "code": null, "e": 28072, "s": 28059, "text": "simmytarika5" }, { "code": null, "e": 28084, "s": 28072, "text": "java-basics" }, { "code": null, "e": 28103, "s": 28084, "text": "Difference Between" }, { "code": null, "e": 28108, "s": 28103, "text": "Java" }, { "code": null, "e": 28113, "s": 28108, "text": "Java" }, { "code": null, "e": 28211, "s": 28113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28272, "s": 28211, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28340, "s": 28272, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28398, "s": 28340, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 28453, "s": 28398, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 28527, "s": 28453, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 28542, "s": 28527, "text": "Arrays in Java" }, { "code": null, "e": 28586, "s": 28542, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28608, "s": 28586, "text": "For-each loop in Java" }, { "code": null, "e": 28644, "s": 28608, "text": "Arrays.sort() in Java with examples" } ]
MySQL Tryit Editor v1.0
Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 88, "s": 25, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 148, "s": 88, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 216, "s": 148, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 254, "s": 216, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 339, "s": 254, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 513, "s": 339, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 564, "s": 513, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 632, "s": 564, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 803, "s": 632, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 903, "s": 803, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 953, "s": 903, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
ML Algorithm to Predict Stock Price | by Sarit Maitra | Towards Data Science
ERROR: type should be string, got "https://sarit-maitra.medium.com/membership\nAlgorithmic trading expected to follow rules, and furthermore, they can form objective, unbiased estimates of risk and represent a revolution in both the art and theory of finance.\nHere, we will see how machine learning can solve the puzzle of forecasting which will be forecasting the difference between today’s price and tomorrow’s price (which is unknown).\nThe data can be loaded through open API provided by world trade data. The financial time-series problem is quite complex from the ML perspective. We need to think about financial data structures more than about particular events like open, high, low and close.\n# Plot the Opening pricesdataset['Open'].plot(grid=True, figsize=(10, 6))plt.title('Nasdaq Composite open price')plt.ylabel('price ($)')# Show the plotplt.show()\nLet’s start preparing the data for the analysis. I will create some features based on short window simple moving average.\nHigh Low % provides some percent volatility in the market.\npercent change reflects the daily percent change\n1 day window open price.\nCurrent day volume increment.\nCurrent day volume rate of change.\nCurrent day open price increment.\nopen price.\nNow, we keep the relevant attributes in the data-frame which are predictor variables here.\nInstead of dropping all NaN values we have replaced NaN with some number which will be treated as outlier in the data-set. We will try gradient boosted trees which in general being robust to outliers.\nLet’s define our target variable. we will have a classification variable because the average price will either go up or down the next day. So, we will target to predict the difference between today’s price and tomorrow’s price.\nFrom the correlation plot below, we have an idea that some of the attributes are correlated with each other and may not be required for the model. However, we will identify this later from gradient boosting feature importance plot.\n# Checking Correlation for easy understandingsns.set(style='darkgrid', context='talk', palette='Dark2')plt.figure(figsize=(14,5))dataset.corr()['Open'].sort_values(ascending = False).plot(kind='bar')plt.show()\nOur data-set has a total of 5158 samples, and 10 features. We have used time-series cross validator which provides train/test indices to split time series data samples that are observed at fixed time intervals. In each split, test indices must be higher than before, and thus shuffling in cross validator is inappropriate.\nprint('Total dataset has {} samples, and {} features.'.format(dataset.shape[0], dataset.shape[1]))X = (dataset.drop(['target'], 1))y = (dataset['target'])print(len(X), len(y))X = np.array(dataset.drop(['target', 'open1'], 1)) # dropping openy = np.array(dataset['target'])#timeseries splittscv = TimeSeriesSplit(max_train_size=None, n_splits=5)for train_samples, test_samples in tscv.split(X): #print(\"TRAIN:\", train_samples, \"TEST:\", test_samples) X_train, X_test = X[train_samples], X[test_samples] y_train, y_test = y[train_samples], y[test_samples]#separating features namesfeature_names = ['ma1','ma2','ma3','HL','pct_change','vol_increment','open_increment','Open']X_train = pd.DataFrame(data=X_train, columns=feature_names)X_test = pd.DataFrame(data=X_test, columns=feature_names)print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)\nLet us convert the target variable to binary classification. A positive change in the value of prices will be classified as 1 and a non-positive change as 0.\ny_train = pd.DataFrame(y_train) # converting to data framey_train.rename(columns = {0: 'target'}, inplace=True)y_test = pd.DataFrame(y_test)y_test.rename(columns = {0: 'target'}, inplace=True)def getBinary(val): if val>0: return 1 else: return 0y_test_binary = pd.DataFrame(y_test[\"target\"].apply(getBinary))\nWe will initiate XGB regressor to test the model. fit the training set\nOur model accuracy score is 78.81% and can predict the daily price change (average) for next 8 trading days .\nIt is relatively easy and straight forward to retrieve importance score for each features once the boosted trees are constructed. This importance is calculated explicitly for each attribute in the data-set, allowing attributes to be ranked and compared to each other.\nWe can see from the feature importance plot that, not all the features are really important for the algorithm to perform; so, we can probably run the algorithm with just 4 features to attain the same accuracy score. The model can be further trained discarding attributes with no correlation.\nThis is a simple model with no big complexities involved and the model attained quite a decent accuracy score. So, we can see that, no longer do we need to rely on descriptive statistics of human outputs as a sort of loose justification of inference.\nI can be reached here."
[ { "code": null, "e": 89, "s": 46, "text": "https://sarit-maitra.medium.com/membership" }, { "code": null, "e": 270, "s": 89, "text": "Algorithmic trading expected to follow rules, and furthermore, they can form objective, unbiased estimates of risk and represent a revolution in both the art and theory of finance." }, { "code": null, "e": 449, "s": 270, "text": "Here, we will see how machine learning can solve the puzzle of forecasting which will be forecasting the difference between today’s price and tomorrow’s price (which is unknown)." }, { "code": null, "e": 710, "s": 449, "text": "The data can be loaded through open API provided by world trade data. The financial time-series problem is quite complex from the ML perspective. We need to think about financial data structures more than about particular events like open, high, low and close." }, { "code": null, "e": 872, "s": 710, "text": "# Plot the Opening pricesdataset['Open'].plot(grid=True, figsize=(10, 6))plt.title('Nasdaq Composite open price')plt.ylabel('price ($)')# Show the plotplt.show()" }, { "code": null, "e": 994, "s": 872, "text": "Let’s start preparing the data for the analysis. I will create some features based on short window simple moving average." }, { "code": null, "e": 1053, "s": 994, "text": "High Low % provides some percent volatility in the market." }, { "code": null, "e": 1102, "s": 1053, "text": "percent change reflects the daily percent change" }, { "code": null, "e": 1127, "s": 1102, "text": "1 day window open price." }, { "code": null, "e": 1157, "s": 1127, "text": "Current day volume increment." }, { "code": null, "e": 1192, "s": 1157, "text": "Current day volume rate of change." }, { "code": null, "e": 1226, "s": 1192, "text": "Current day open price increment." }, { "code": null, "e": 1238, "s": 1226, "text": "open price." }, { "code": null, "e": 1329, "s": 1238, "text": "Now, we keep the relevant attributes in the data-frame which are predictor variables here." }, { "code": null, "e": 1530, "s": 1329, "text": "Instead of dropping all NaN values we have replaced NaN with some number which will be treated as outlier in the data-set. We will try gradient boosted trees which in general being robust to outliers." }, { "code": null, "e": 1758, "s": 1530, "text": "Let’s define our target variable. we will have a classification variable because the average price will either go up or down the next day. So, we will target to predict the difference between today’s price and tomorrow’s price." }, { "code": null, "e": 1990, "s": 1758, "text": "From the correlation plot below, we have an idea that some of the attributes are correlated with each other and may not be required for the model. However, we will identify this later from gradient boosting feature importance plot." }, { "code": null, "e": 2200, "s": 1990, "text": "# Checking Correlation for easy understandingsns.set(style='darkgrid', context='talk', palette='Dark2')plt.figure(figsize=(14,5))dataset.corr()['Open'].sort_values(ascending = False).plot(kind='bar')plt.show()" }, { "code": null, "e": 2523, "s": 2200, "text": "Our data-set has a total of 5158 samples, and 10 features. We have used time-series cross validator which provides train/test indices to split time series data samples that are observed at fixed time intervals. In each split, test indices must be higher than before, and thus shuffling in cross validator is inappropriate." }, { "code": null, "e": 3377, "s": 2523, "text": "print('Total dataset has {} samples, and {} features.'.format(dataset.shape[0], dataset.shape[1]))X = (dataset.drop(['target'], 1))y = (dataset['target'])print(len(X), len(y))X = np.array(dataset.drop(['target', 'open1'], 1)) # dropping openy = np.array(dataset['target'])#timeseries splittscv = TimeSeriesSplit(max_train_size=None, n_splits=5)for train_samples, test_samples in tscv.split(X): #print(\"TRAIN:\", train_samples, \"TEST:\", test_samples) X_train, X_test = X[train_samples], X[test_samples] y_train, y_test = y[train_samples], y[test_samples]#separating features namesfeature_names = ['ma1','ma2','ma3','HL','pct_change','vol_increment','open_increment','Open']X_train = pd.DataFrame(data=X_train, columns=feature_names)X_test = pd.DataFrame(data=X_test, columns=feature_names)print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)" }, { "code": null, "e": 3535, "s": 3377, "text": "Let us convert the target variable to binary classification. A positive change in the value of prices will be classified as 1 and a non-positive change as 0." }, { "code": null, "e": 3852, "s": 3535, "text": "y_train = pd.DataFrame(y_train) # converting to data framey_train.rename(columns = {0: 'target'}, inplace=True)y_test = pd.DataFrame(y_test)y_test.rename(columns = {0: 'target'}, inplace=True)def getBinary(val): if val>0: return 1 else: return 0y_test_binary = pd.DataFrame(y_test[\"target\"].apply(getBinary))" }, { "code": null, "e": 3923, "s": 3852, "text": "We will initiate XGB regressor to test the model. fit the training set" }, { "code": null, "e": 4033, "s": 3923, "text": "Our model accuracy score is 78.81% and can predict the daily price change (average) for next 8 trading days ." }, { "code": null, "e": 4301, "s": 4033, "text": "It is relatively easy and straight forward to retrieve importance score for each features once the boosted trees are constructed. This importance is calculated explicitly for each attribute in the data-set, allowing attributes to be ranked and compared to each other." }, { "code": null, "e": 4593, "s": 4301, "text": "We can see from the feature importance plot that, not all the features are really important for the algorithm to perform; so, we can probably run the algorithm with just 4 features to attain the same accuracy score. The model can be further trained discarding attributes with no correlation." }, { "code": null, "e": 4844, "s": 4593, "text": "This is a simple model with no big complexities involved and the model attained quite a decent accuracy score. So, we can see that, no longer do we need to rely on descriptive statistics of human outputs as a sort of loose justification of inference." } ]
How can we MySQL LOAD DATA INFILE statement with ‘ENCLOSED BY’ option to import data from text file into MySQL table?
Sometimes the input text files have the text fields enclosed by double quotes and to import data from such kind of files we need to use the ‘ENCLOSED BY’ option with LOAD DATA INFILE statement. We are considering the following example to make it understand − Followings are the comma-separated values in A.txt file − 100,”Ram”,”INDIA”,25000 101,”Mohan”,”INDIA”,28000 We want to import this data into the following file named employee2_tbl − mysql> Create table employee2_tbl(Id Int, Name Varchar(20), Country Varchar(20),Salary Int); Query OK, 0 rows affected (0.1 sec) Now, the transfer of data from a file to a database table can be done with the help of the following table − mysql> LOAD DATA LOCAL INFILE 'd:\A.txt' INTO table employee2_tbl FIELDS TERMINATED BY ',' ENCLOSED BY ‘“’; Query OK, 2 rows affected (0.16 sec) Records: 2 Deleted: 0 Skipped: 0 Warnings: 0 mysql> Select * from employee2_tbl; +------+-------+---------+--------+ | Id | Name | Country | Salary | +------+-------+---------+--------+ | 100 | Ram | INDIA | 25000 | | 101 | Mohan | INDIA | 28000 | +------+-------+---------+--------+ 2 rows in set (0.00 sec) The above result set shows that the data from A.txt file has been transferred to the table.
[ { "code": null, "e": 1321, "s": 1062, "text": "Sometimes the input text files have the text fields enclosed by double quotes and to import data from such kind of files we need to use the ‘ENCLOSED BY’ option with LOAD DATA INFILE statement. We are considering the following example to make it understand −" }, { "code": null, "e": 1379, "s": 1321, "text": "Followings are the comma-separated values in A.txt file −" }, { "code": null, "e": 1429, "s": 1379, "text": "100,”Ram”,”INDIA”,25000\n101,”Mohan”,”INDIA”,28000" }, { "code": null, "e": 1503, "s": 1429, "text": "We want to import this data into the following file named employee2_tbl −" }, { "code": null, "e": 1633, "s": 1503, "text": "mysql> Create table employee2_tbl(Id Int, Name Varchar(20), Country Varchar(20),Salary Int);\n\nQuery OK, 0 rows affected (0.1 sec)" }, { "code": null, "e": 1742, "s": 1633, "text": "Now, the transfer of data from a file to a database table can be done with the help of the following table −" }, { "code": null, "e": 2210, "s": 1742, "text": "mysql> LOAD DATA LOCAL INFILE 'd:\\A.txt' INTO table employee2_tbl FIELDS TERMINATED BY ',' ENCLOSED BY ‘“’;\nQuery OK, 2 rows affected (0.16 sec)\nRecords: 2 Deleted: 0 Skipped: 0 Warnings: 0\n\nmysql> Select * from employee2_tbl;\n+------+-------+---------+--------+\n| Id | Name | Country | Salary |\n+------+-------+---------+--------+\n| 100 | Ram | INDIA | 25000 |\n| 101 | Mohan | INDIA | 28000 |\n+------+-------+---------+--------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 2302, "s": 2210, "text": "The above result set shows that the data from A.txt file has been transferred to the table." } ]
AVRO - Environment Setup
Apache software foundation provides Avro with various releases. You can download the required release from Apache mirrors. Let us see, how to set up the environment to work with Avro − To download Apache Avro, proceed with the following − Open the web page Apache.org. You will see the homepage of Apache Avro as shown below − Open the web page Apache.org. You will see the homepage of Apache Avro as shown below − Click on project → releases. You will get a list of releases. Click on project → releases. You will get a list of releases. Select the latest release which leads you to a download link. Select the latest release which leads you to a download link. mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below − mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below − You can select and download the library for any of the languages provided. In this tutorial, we use Java. Hence download the jar files avro-1.7.7.jar and avro-tools-1.7.7.jar. To use Avro in Eclipse environment, you need to follow the steps given below − Step 1. Open eclipse. Step 1. Open eclipse. Step 2. Create a project. Step 2. Create a project. Step 3. Right-click on the project name. You will get a shortcut menu. Step 3. Right-click on the project name. You will get a shortcut menu. Step 4. Click on Build Path. It leads you to another shortcut menu. Step 4. Click on Build Path. It leads you to another shortcut menu. Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below − Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below − Step 6. Under libraries tab, click on ADD EXternal JARs... button. Step 6. Under libraries tab, click on ADD EXternal JARs... button. Step 7. Select the jar file avro-1.77.jar you have downloaded. Step 7. Select the jar file avro-1.77.jar you have downloaded. Step 8. Click on OK. Step 8. Click on OK. You can also get the Avro library into your project using Maven. Given below is the pom.xml file for Avro. <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>Test</groupId> <artifactId>Test</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.avro</groupId> <artifactId>avro</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.apache.avro</groupId> <artifactId>avro-tools</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.0-beta9</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.0-beta9</version> </dependency> </dependencies> </project> To work with Avro in Linux environment, download the following jar files − avro-1.77.jar avro-tools-1.77.jar log4j-api-2.0-beta9.jar og4j-core-2.0.beta9.jar. Copy these files into a folder and set the classpath to the folder, in the ./bashrc file as shown below. #class path for Avro export CLASSPATH=$CLASSPATH://home/Hadoop/Avro_Work/jars/* Print Add Notes Bookmark this page
[ { "code": null, "e": 2046, "s": 1861, "text": "Apache software foundation provides Avro with various releases. You can download the required release from Apache mirrors. Let us see, how to set up the environment to work with Avro −" }, { "code": null, "e": 2100, "s": 2046, "text": "To download Apache Avro, proceed with the following −" }, { "code": null, "e": 2188, "s": 2100, "text": "Open the web page Apache.org. You will see the homepage of Apache Avro as shown below −" }, { "code": null, "e": 2276, "s": 2188, "text": "Open the web page Apache.org. You will see the homepage of Apache Avro as shown below −" }, { "code": null, "e": 2338, "s": 2276, "text": "Click on project → releases. You will get a list of releases." }, { "code": null, "e": 2400, "s": 2338, "text": "Click on project → releases. You will get a list of releases." }, { "code": null, "e": 2462, "s": 2400, "text": "Select the latest release which leads you to a download link." }, { "code": null, "e": 2524, "s": 2462, "text": "Select the latest release which leads you to a download link." }, { "code": null, "e": 2663, "s": 2524, "text": "mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below −" }, { "code": null, "e": 2802, "s": 2663, "text": "mirror.nexcess is one of the links where you can find the list of all libraries of different languages that Avro supports as shown below −" }, { "code": null, "e": 2978, "s": 2802, "text": "You can select and download the library for any of the languages provided. In this tutorial, we use Java. Hence download the jar files avro-1.7.7.jar and avro-tools-1.7.7.jar." }, { "code": null, "e": 3057, "s": 2978, "text": "To use Avro in Eclipse environment, you need to follow the steps given below −" }, { "code": null, "e": 3079, "s": 3057, "text": "Step 1. Open eclipse." }, { "code": null, "e": 3101, "s": 3079, "text": "Step 1. Open eclipse." }, { "code": null, "e": 3127, "s": 3101, "text": "Step 2. Create a project." }, { "code": null, "e": 3153, "s": 3127, "text": "Step 2. Create a project." }, { "code": null, "e": 3224, "s": 3153, "text": "Step 3. Right-click on the project name. You will get a shortcut menu." }, { "code": null, "e": 3295, "s": 3224, "text": "Step 3. Right-click on the project name. You will get a shortcut menu." }, { "code": null, "e": 3363, "s": 3295, "text": "Step 4. Click on Build Path. It leads you to another shortcut menu." }, { "code": null, "e": 3431, "s": 3363, "text": "Step 4. Click on Build Path. It leads you to another shortcut menu." }, { "code": null, "e": 3535, "s": 3431, "text": "Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below −" }, { "code": null, "e": 3639, "s": 3535, "text": "Step 5. Click on Configure Build Path... You can see Properties window of your project as shown below −" }, { "code": null, "e": 3706, "s": 3639, "text": "Step 6. Under libraries tab, click on ADD EXternal JARs... button." }, { "code": null, "e": 3773, "s": 3706, "text": "Step 6. Under libraries tab, click on ADD EXternal JARs... button." }, { "code": null, "e": 3836, "s": 3773, "text": "Step 7. Select the jar file avro-1.77.jar you have downloaded." }, { "code": null, "e": 3899, "s": 3836, "text": "Step 7. Select the jar file avro-1.77.jar you have downloaded." }, { "code": null, "e": 3920, "s": 3899, "text": "Step 8. Click on OK." }, { "code": null, "e": 3941, "s": 3920, "text": "Step 8. Click on OK." }, { "code": null, "e": 4048, "s": 3941, "text": "You can also get the Avro library into your project using Maven. Given below is the pom.xml file for Avro." }, { "code": null, "e": 5485, "s": 4048, "text": "<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\">\n\n <modelVersion>4.0.0</modelVersion>\n <groupId>Test</groupId>\n <artifactId>Test</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n\n <build>\n <sourceDirectory>src</sourceDirectory>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.1</version>\n\t\t\n <configuration>\n <source>1.7</source>\n <target>1.7</target>\n </configuration>\n\t\t\n </plugin>\n </plugins>\n </build>\n\n <dependencies>\n <dependency>\n <groupId>org.apache.avro</groupId>\n <artifactId>avro</artifactId>\n <version>1.7.7</version>\n </dependency>\n\t\n <dependency>\n <groupId>org.apache.avro</groupId>\n <artifactId>avro-tools</artifactId>\n <version>1.7.7</version>\n </dependency>\n\t\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-api</artifactId>\n <version>2.0-beta9</version>\n </dependency>\n\t\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-core</artifactId>\n <version>2.0-beta9</version>\n </dependency>\n\t\n </dependencies>\n\n</project>" }, { "code": null, "e": 5560, "s": 5485, "text": "To work with Avro in Linux environment, download the following jar files −" }, { "code": null, "e": 5574, "s": 5560, "text": "avro-1.77.jar" }, { "code": null, "e": 5594, "s": 5574, "text": "avro-tools-1.77.jar" }, { "code": null, "e": 5618, "s": 5594, "text": "log4j-api-2.0-beta9.jar" }, { "code": null, "e": 5643, "s": 5618, "text": "og4j-core-2.0.beta9.jar." }, { "code": null, "e": 5748, "s": 5643, "text": "Copy these files into a folder and set the classpath to the folder, in the ./bashrc file as shown below." }, { "code": null, "e": 5829, "s": 5748, "text": "#class path for Avro\nexport CLASSPATH=$CLASSPATH://home/Hadoop/Avro_Work/jars/*\n" }, { "code": null, "e": 5836, "s": 5829, "text": " Print" }, { "code": null, "e": 5847, "s": 5836, "text": " Add Notes" } ]
Python Pandas - GroupBy
Any groupby operation involves one of the following operations on the original object. They are − Splitting the Object Splitting the Object Applying a function Applying a function Combining the results Combining the results In many situations, we split the data into sets and we apply some functionality on each subset. In the apply functionality, we can perform the following operations − Aggregation − computing a summary statistic Aggregation − computing a summary statistic Transformation − perform some group-specific operation Transformation − perform some group-specific operation Filtration − discarding the data with some condition Filtration − discarding the data with some condition Let us now create a DataFrame object and perform all the operations on it − #import the pandas library import pandas as pd ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) print df Its output is as follows − Points Rank Team Year 0 876 1 Riders 2014 1 789 2 Riders 2015 2 863 2 Devils 2014 3 673 3 Devils 2015 4 741 3 Kings 2014 5 812 4 kings 2015 6 756 1 Kings 2016 7 788 1 Kings 2017 8 694 2 Riders 2016 9 701 4 Royals 2014 10 804 1 Royals 2015 11 690 2 Riders 2017 Pandas object can be split into any of their objects. There are multiple ways to split an object like − obj.groupby('key') obj.groupby(['key1','key2']) obj.groupby(key,axis=1) Let us now see how the grouping objects can be applied to the DataFrame object # import the pandas library import pandas as pd ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) print df.groupby('Team') Its output is as follows − <pandas.core.groupby.DataFrameGroupBy object at 0x7fa46a977e50> # import the pandas library import pandas as pd ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) print df.groupby('Team').groups Its output is as follows − {'Kings': Int64Index([4, 6, 7], dtype='int64'), 'Devils': Int64Index([2, 3], dtype='int64'), 'Riders': Int64Index([0, 1, 8, 11], dtype='int64'), 'Royals': Int64Index([9, 10], dtype='int64'), 'kings' : Int64Index([5], dtype='int64')} Group by with multiple columns − # import the pandas library import pandas as pd ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) print df.groupby(['Team','Year']).groups Its output is as follows − {('Kings', 2014): Int64Index([4], dtype='int64'), ('Royals', 2014): Int64Index([9], dtype='int64'), ('Riders', 2014): Int64Index([0], dtype='int64'), ('Riders', 2015): Int64Index([1], dtype='int64'), ('Kings', 2016): Int64Index([6], dtype='int64'), ('Riders', 2016): Int64Index([8], dtype='int64'), ('Riders', 2017): Int64Index([11], dtype='int64'), ('Devils', 2014): Int64Index([2], dtype='int64'), ('Devils', 2015): Int64Index([3], dtype='int64'), ('kings', 2015): Int64Index([5], dtype='int64'), ('Royals', 2015): Int64Index([10], dtype='int64'), ('Kings', 2017): Int64Index([7], dtype='int64')} With the groupby object in hand, we can iterate through the object similar to itertools.obj. # import the pandas library import pandas as pd ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) grouped = df.groupby('Year') for name,group in grouped: print name print group Its output is as follows − 2014 Points Rank Team Year 0 876 1 Riders 2014 2 863 2 Devils 2014 4 741 3 Kings 2014 9 701 4 Royals 2014 2015 Points Rank Team Year 1 789 2 Riders 2015 3 673 3 Devils 2015 5 812 4 kings 2015 10 804 1 Royals 2015 2016 Points Rank Team Year 6 756 1 Kings 2016 8 694 2 Riders 2016 2017 Points Rank Team Year 7 788 1 Kings 2017 11 690 2 Riders 2017 By default, the groupby object has the same label name as the group name. Using the get_group() method, we can select a single group. # import the pandas library import pandas as pd ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) grouped = df.groupby('Year') print grouped.get_group(2014) Its output is as follows − Points Rank Team Year 0 876 1 Riders 2014 2 863 2 Devils 2014 4 741 3 Kings 2014 9 701 4 Royals 2014 An aggregated function returns a single aggregated value for each group. Once the group by object is created, several aggregation operations can be performed on the grouped data. An obvious one is aggregation via the aggregate or equivalent agg method − # import the pandas library import pandas as pd import numpy as np ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) grouped = df.groupby('Year') print grouped['Points'].agg(np.mean) Its output is as follows − Year 2014 795.25 2015 769.50 2016 725.00 2017 739.00 Name: Points, dtype: float64 Another way to see the size of each group is by applying the size() function − import pandas as pd import numpy as np ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) Attribute Access in Python Pandas grouped = df.groupby('Team') print grouped.agg(np.size) Its output is as follows − Points Rank Year Team Devils 2 2 2 Kings 3 3 3 Riders 4 4 4 Royals 2 2 2 kings 1 1 1 With grouped Series, you can also pass a list or dict of functions to do aggregation with, and generate DataFrame as output − # import the pandas library import pandas as pd import numpy as np ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) grouped = df.groupby('Team') print grouped['Points'].agg([np.sum, np.mean, np.std]) Its output is as follows − Team sum mean std Devils 1536 768.000000 134.350288 Kings 2285 761.666667 24.006943 Riders 3049 762.250000 88.567771 Royals 1505 752.500000 72.831998 kings 812 812.000000 NaN Transformation on a group or a column returns an object that is indexed the same size of that is being grouped. Thus, the transform should return a result that is the same size as that of a group chunk. # import the pandas library import pandas as pd import numpy as np ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) grouped = df.groupby('Team') score = lambda x: (x - x.mean()) / x.std()*10 print grouped.transform(score) Its output is as follows − Points Rank Year 0 12.843272 -15.000000 -11.618950 1 3.020286 5.000000 -3.872983 2 7.071068 -7.071068 -7.071068 3 -7.071068 7.071068 7.071068 4 -8.608621 11.547005 -10.910895 5 NaN NaN NaN 6 -2.360428 -5.773503 2.182179 7 10.969049 -5.773503 8.728716 8 -7.705963 5.000000 3.872983 9 -7.071068 7.071068 -7.071068 10 7.071068 -7.071068 7.071068 11 -8.157595 5.000000 11.618950 Filtration filters the data on a defined criteria and returns the subset of data. The filter() function is used to filter the data. import pandas as pd import numpy as np ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) print df.groupby('Team').filter(lambda x: len(x) >= 3) Its output is as follows − Points Rank Team Year 0 876 1 Riders 2014 1 789 2 Riders 2015 4 741 3 Kings 2014 6 756 1 Kings 2016 7 788 1 Kings 2017 8 694 2 Riders 2016 11 690 2 Riders 2017 In the above filter condition, we are asking to return the teams which have participated three or more times in IPL. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2541, "s": 2443, "text": "Any groupby operation involves one of the following operations on the original object. They are −" }, { "code": null, "e": 2562, "s": 2541, "text": "Splitting the Object" }, { "code": null, "e": 2583, "s": 2562, "text": "Splitting the Object" }, { "code": null, "e": 2603, "s": 2583, "text": "Applying a function" }, { "code": null, "e": 2623, "s": 2603, "text": "Applying a function" }, { "code": null, "e": 2645, "s": 2623, "text": "Combining the results" }, { "code": null, "e": 2667, "s": 2645, "text": "Combining the results" }, { "code": null, "e": 2833, "s": 2667, "text": "In many situations, we split the data into sets and we apply some functionality on each subset. In the apply functionality, we can perform the following operations −" }, { "code": null, "e": 2877, "s": 2833, "text": "Aggregation − computing a summary statistic" }, { "code": null, "e": 2921, "s": 2877, "text": "Aggregation − computing a summary statistic" }, { "code": null, "e": 2976, "s": 2921, "text": "Transformation − perform some group-specific operation" }, { "code": null, "e": 3031, "s": 2976, "text": "Transformation − perform some group-specific operation" }, { "code": null, "e": 3084, "s": 3031, "text": "Filtration − discarding the data with some condition" }, { "code": null, "e": 3137, "s": 3084, "text": "Filtration − discarding the data with some condition" }, { "code": null, "e": 3213, "s": 3137, "text": "Let us now create a DataFrame object and perform all the operations on it −" }, { "code": null, "e": 3623, "s": 3213, "text": "#import the pandas library\nimport pandas as pd\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\nprint df" }, { "code": null, "e": 3650, "s": 3623, "text": "Its output is as follows −" }, { "code": null, "e": 4093, "s": 3650, "text": " Points Rank Team Year\n0 876 1 Riders 2014\n1 789 2 Riders 2015\n2 863 2 Devils 2014\n3 673 3 Devils 2015\n4 741 3 Kings 2014\n5 812 4 kings 2015\n6 756 1 Kings 2016\n7 788 1 Kings 2017\n8 694 2 Riders 2016\n9 701 4 Royals 2014\n10 804 1 Royals 2015\n11 690 2 Riders 2017\n" }, { "code": null, "e": 4197, "s": 4093, "text": "Pandas object can be split into any of their objects. There are multiple ways to split an\nobject like −" }, { "code": null, "e": 4216, "s": 4197, "text": "obj.groupby('key')" }, { "code": null, "e": 4245, "s": 4216, "text": "obj.groupby(['key1','key2'])" }, { "code": null, "e": 4269, "s": 4245, "text": "obj.groupby(key,axis=1)" }, { "code": null, "e": 4348, "s": 4269, "text": "Let us now see how the grouping objects can be applied to the DataFrame object" }, { "code": null, "e": 4775, "s": 4348, "text": "# import the pandas library\nimport pandas as pd\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\nprint df.groupby('Team')" }, { "code": null, "e": 4802, "s": 4775, "text": "Its output is as follows −" }, { "code": null, "e": 4867, "s": 4802, "text": "<pandas.core.groupby.DataFrameGroupBy object at 0x7fa46a977e50>\n" }, { "code": null, "e": 5301, "s": 4867, "text": "# import the pandas library\nimport pandas as pd\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\nprint df.groupby('Team').groups" }, { "code": null, "e": 5328, "s": 5301, "text": "Its output is as follows −" }, { "code": null, "e": 5594, "s": 5328, "text": "{'Kings': Int64Index([4, 6, 7], dtype='int64'),\n'Devils': Int64Index([2, 3], dtype='int64'),\n'Riders': Int64Index([0, 1, 8, 11], dtype='int64'),\n'Royals': Int64Index([9, 10], dtype='int64'),\n'kings' : Int64Index([5], dtype='int64')}\n" }, { "code": null, "e": 5627, "s": 5594, "text": "Group by with multiple columns −" }, { "code": null, "e": 6070, "s": 5627, "text": "# import the pandas library\nimport pandas as pd\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\nprint df.groupby(['Team','Year']).groups" }, { "code": null, "e": 6097, "s": 6070, "text": "Its output is as follows −" }, { "code": null, "e": 6708, "s": 6097, "text": "{('Kings', 2014): Int64Index([4], dtype='int64'),\n ('Royals', 2014): Int64Index([9], dtype='int64'),\n ('Riders', 2014): Int64Index([0], dtype='int64'),\n ('Riders', 2015): Int64Index([1], dtype='int64'),\n ('Kings', 2016): Int64Index([6], dtype='int64'),\n ('Riders', 2016): Int64Index([8], dtype='int64'),\n ('Riders', 2017): Int64Index([11], dtype='int64'),\n ('Devils', 2014): Int64Index([2], dtype='int64'),\n ('Devils', 2015): Int64Index([3], dtype='int64'),\n ('kings', 2015): Int64Index([5], dtype='int64'),\n ('Royals', 2015): Int64Index([10], dtype='int64'),\n ('Kings', 2017): Int64Index([7], dtype='int64')}\n" }, { "code": null, "e": 6801, "s": 6708, "text": "With the groupby object in hand, we can iterate through the object similar to itertools.obj." }, { "code": null, "e": 7289, "s": 6801, "text": "# import the pandas library\nimport pandas as pd\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\ngrouped = df.groupby('Year')\n\nfor name,group in grouped:\n print name\n print group" }, { "code": null, "e": 7316, "s": 7289, "text": "Its output is as follows −" }, { "code": null, "e": 7849, "s": 7316, "text": "2014\n Points Rank Team Year\n0 876 1 Riders 2014\n2 863 2 Devils 2014\n4 741 3 Kings 2014\n9 701 4 Royals 2014\n\n2015\n Points Rank Team Year\n1 789 2 Riders 2015\n3 673 3 Devils 2015\n5 812 4 kings 2015\n10 804 1 Royals 2015\n\n2016\n Points Rank Team Year\n6 756 1 Kings 2016\n8 694 2 Riders 2016\n\n2017\n Points Rank Team Year\n7 788 1 Kings 2017\n11 690 2 Riders 2017\n" }, { "code": null, "e": 7923, "s": 7849, "text": "By default, the groupby object has the same label name as the group name." }, { "code": null, "e": 7983, "s": 7923, "text": "Using the get_group() method, we can select a single group." }, { "code": null, "e": 8444, "s": 7983, "text": "# import the pandas library\nimport pandas as pd\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\ngrouped = df.groupby('Year')\nprint grouped.get_group(2014)" }, { "code": null, "e": 8471, "s": 8444, "text": "Its output is as follows −" }, { "code": null, "e": 8637, "s": 8471, "text": " Points Rank Team Year\n0 876 1 Riders 2014\n2 863 2 Devils 2014\n4 741 3 Kings 2014\n9 701 4 Royals 2014\n" }, { "code": null, "e": 8816, "s": 8637, "text": "An aggregated function returns a single aggregated value for each group. Once the group by object is created, several aggregation operations can be performed on the grouped data." }, { "code": null, "e": 8891, "s": 8816, "text": "An obvious one is aggregation via the aggregate or equivalent agg method −" }, { "code": null, "e": 9378, "s": 8891, "text": "# import the pandas library\nimport pandas as pd\nimport numpy as np\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\ngrouped = df.groupby('Year')\nprint grouped['Points'].agg(np.mean)" }, { "code": null, "e": 9405, "s": 9378, "text": "Its output is as follows −" }, { "code": null, "e": 9496, "s": 9405, "text": "Year\n2014 795.25\n2015 769.50\n2016 725.00\n2017 739.00\nName: Points, dtype: float64\n" }, { "code": null, "e": 9575, "s": 9496, "text": "Another way to see the size of each group is by applying the size() function −" }, { "code": null, "e": 10058, "s": 9575, "text": "import pandas as pd\nimport numpy as np\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\nAttribute Access in Python Pandas\ngrouped = df.groupby('Team')\nprint grouped.agg(np.size)" }, { "code": null, "e": 10085, "s": 10058, "text": "Its output is as follows −" }, { "code": null, "e": 10271, "s": 10085, "text": " Points Rank Year\nTeam\nDevils 2 2 2\nKings 3 3 3\nRiders 4 4 4\nRoyals 2 2 2\nkings 1 1 1\n" }, { "code": null, "e": 10397, "s": 10271, "text": "With grouped Series, you can also pass a list or dict of functions to do aggregation with, and generate DataFrame as output −" }, { "code": null, "e": 10902, "s": 10397, "text": "# import the pandas library\nimport pandas as pd\nimport numpy as np\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\ngrouped = df.groupby('Team')\nprint grouped['Points'].agg([np.sum, np.mean, np.std])" }, { "code": null, "e": 10929, "s": 10902, "text": "Its output is as follows −" }, { "code": null, "e": 11167, "s": 10929, "text": "Team sum mean std\nDevils 1536 768.000000 134.350288\nKings 2285 761.666667 24.006943\nRiders 3049 762.250000 88.567771\nRoyals 1505 752.500000 72.831998\nkings 812 812.000000 NaN\n" }, { "code": null, "e": 11370, "s": 11167, "text": "Transformation on a group or a column returns an object that is indexed the same size of that is being grouped. Thus, the transform should return a result that is the same size as that of a group chunk." }, { "code": null, "e": 11897, "s": 11370, "text": "# import the pandas library\nimport pandas as pd\nimport numpy as np\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\ngrouped = df.groupby('Team')\nscore = lambda x: (x - x.mean()) / x.std()*10\nprint grouped.transform(score)" }, { "code": null, "e": 11924, "s": 11897, "text": "Its output is as follows −" }, { "code": null, "e": 12419, "s": 11924, "text": " Points Rank Year\n0 12.843272 -15.000000 -11.618950\n1 3.020286 5.000000 -3.872983\n2 7.071068 -7.071068 -7.071068\n3 -7.071068 7.071068 7.071068\n4 -8.608621 11.547005 -10.910895\n5 NaN NaN NaN\n6 -2.360428 -5.773503 2.182179\n7 10.969049 -5.773503 8.728716\n8 -7.705963 5.000000 3.872983\n9 -7.071068 7.071068 -7.071068\n10 7.071068 -7.071068 7.071068\n11 -8.157595 5.000000 11.618950\n" }, { "code": null, "e": 12551, "s": 12419, "text": "Filtration filters the data on a defined criteria and returns the subset of data. The filter() function is used to filter the data." }, { "code": null, "e": 12999, "s": 12551, "text": "import pandas as pd\nimport numpy as np\n\nipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',\n 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],\n 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],\n 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],\n 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}\ndf = pd.DataFrame(ipl_data)\n\nprint df.groupby('Team').filter(lambda x: len(x) >= 3)" }, { "code": null, "e": 13026, "s": 12999, "text": "Its output is as follows −" }, { "code": null, "e": 13291, "s": 13026, "text": " Points Rank Team Year\n0 876 1 Riders 2014\n1 789 2 Riders 2015\n4 741 3 Kings 2014\n6 756 1 Kings 2016\n7 788 1 Kings 2017\n8 694 2 Riders 2016\n11 690 2 Riders 2017\n" }, { "code": null, "e": 13408, "s": 13291, "text": "In the above filter condition, we are asking to return the teams which have participated three or more times in IPL." }, { "code": null, "e": 13445, "s": 13408, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 13461, "s": 13445, "text": " Malhar Lathkar" }, { "code": null, "e": 13494, "s": 13461, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 13513, "s": 13494, "text": " Arnab Chakraborty" }, { "code": null, "e": 13548, "s": 13513, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 13570, "s": 13548, "text": " In28Minutes Official" }, { "code": null, "e": 13604, "s": 13570, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 13632, "s": 13604, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13667, "s": 13632, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 13681, "s": 13667, "text": " Lets Kode It" }, { "code": null, "e": 13714, "s": 13681, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 13731, "s": 13714, "text": " Abhilash Nelson" }, { "code": null, "e": 13738, "s": 13731, "text": " Print" }, { "code": null, "e": 13749, "s": 13738, "text": " Add Notes" } ]
AAA (Authentication, Authorization and Accounting) configuration (locally) - GeeksforGeeks
10 Mar, 2022 Prerequisite – AAA (Authentication, Authorization and Accounting) To provide security to access network resources, AAA is used. AAA is a standard based framework used to control who is permitted to use network resources (through authentication), what they are authorized to do (through authorization) and capture the actions performed while accessing the network (through accounting). AAA can be implemented by using the local database (running configuration of the device) or by using an external ACS server. Here, we will talk about the AAA configuration on the device locally only. AAA configuration – Now, in this example, we are configuring AAA Authentication on router.It includes following steps:- 1. Enable AAA on router router1(config)#aaa new-model AAA is enabled by the command aaa new-model . 2. Create default authentication list – router1(config)#aaa authentication login default local It enabled by the command aaa authentication login default local. In this command, default means we will Use the default method list and local Means we will use the local database. 3. Apply the list to vty lines – router1(config)#line vty 0 4 router1(config)#login authentication default router1(config)#exit After creating the default method list, we have to apply it to the vty lines so that whenever some user try to access the router through SSH or telnet, the user has to provide credentials which are configured. 4. Creating local user on the router – router1(config)#username GeeksforGeeks privilege 15 password saurabh This is the most important step as we have to create a local database in which we provide the username (as geeksforgeeks), privilege level 15 and password (as saurabh). Note – The default method list we have applied on the vty lines will force the user (who wants to access the router) to enter these credentials when he wants to take remote access through telnet or ssh. 5. Debugging aaa authentication – we can see the AAA authentication messages through the command ”debug aaa authentication”. router1#debug aaa authentication router2# telnet 10_1_1_1 Trying 10_1_1_1 .... Open User Access Verification Username: geeksforgeeks Password: router1> Now, we will telnet the router1 (ip address-10.1.1.1/24) from router2 (ip address – 10.1.1.2/24) and it will ask for the credentials as shown in the figure. As soon as the user enters the credentials, we can see the authentication messages. In addition to this, if we want to apply a banner before asking for credentials, we can apply it using the command shown. router1(config)#aaa authentication banner " welcome to our network" If we want to add username and password prompt, we can apply it by using the command shown below. router1(config)#aaa authentication username-prompt "enter your username" router1(config)#aaa authentication password-prompt "enter your password" Also, if we want to show a message when the credentials entered by the user are wrong then we can show that by using the command shown below. router1(config)#aaa authentication fail-message "wrong username or password. Please try again..." Also, we can limit the number of attempts a user can enter wrong credentials. After the 3rd attempt to enter the credentials, the session will be automatically terminated. router1(config)#aaa authentication attempts login 3 ManasChhabra2 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments UDP Server-Client implementation in C Error Detection in Computer Networks Distance Vector Routing (DVR) Protocol Socket Programming in Java Differences between IPv4 and IPv6 Hamming Code in Computer Network Implementation of Diffie-Hellman Algorithm Advanced Encryption Standard (AES) User Datagram Protocol (UDP) Introduction of Classful IP Addressing
[ { "code": null, "e": 24432, "s": 24404, "text": "\n10 Mar, 2022" }, { "code": null, "e": 24818, "s": 24432, "text": "Prerequisite – AAA (Authentication, Authorization and Accounting) To provide security to access network resources, AAA is used. AAA is a standard based framework used to control who is permitted to use network resources (through authentication), what they are authorized to do (through authorization) and capture the actions performed while accessing the network (through accounting). " }, { "code": null, "e": 25019, "s": 24818, "text": "AAA can be implemented by using the local database (running configuration of the device) or by using an external ACS server. Here, we will talk about the AAA configuration on the device locally only. " }, { "code": null, "e": 25165, "s": 25019, "text": "AAA configuration – Now, in this example, we are configuring AAA Authentication on router.It includes following steps:- 1. Enable AAA on router " }, { "code": null, "e": 25195, "s": 25165, "text": "router1(config)#aaa new-model" }, { "code": null, "e": 25242, "s": 25195, "text": "AAA is enabled by the command aaa new-model . " }, { "code": null, "e": 25284, "s": 25242, "text": "2. Create default authentication list – " }, { "code": null, "e": 25361, "s": 25284, "text": "router1(config)#aaa authentication \n login default local" }, { "code": null, "e": 25543, "s": 25361, "text": "It enabled by the command aaa authentication login default local. In this command, default means we will Use the default method list and local Means we will use the local database. " }, { "code": null, "e": 25578, "s": 25543, "text": "3. Apply the list to vty lines – " }, { "code": null, "e": 25673, "s": 25578, "text": "router1(config)#line vty 0 4\nrouter1(config)#login authentication default\nrouter1(config)#exit" }, { "code": null, "e": 25884, "s": 25673, "text": "After creating the default method list, we have to apply it to the vty lines so that whenever some user try to access the router through SSH or telnet, the user has to provide credentials which are configured. " }, { "code": null, "e": 25925, "s": 25884, "text": "4. Creating local user on the router – " }, { "code": null, "e": 26007, "s": 25925, "text": "router1(config)#username GeeksforGeeks \n privilege 15 password saurabh " }, { "code": null, "e": 26177, "s": 26007, "text": "This is the most important step as we have to create a local database in which we provide the username (as geeksforgeeks), privilege level 15 and password (as saurabh). " }, { "code": null, "e": 26381, "s": 26177, "text": "Note – The default method list we have applied on the vty lines will force the user (who wants to access the router) to enter these credentials when he wants to take remote access through telnet or ssh. " }, { "code": null, "e": 26508, "s": 26381, "text": "5. Debugging aaa authentication – we can see the AAA authentication messages through the command ”debug aaa authentication”. " }, { "code": null, "e": 26542, "s": 26508, "text": "router1#debug aaa authentication " }, { "code": null, "e": 26667, "s": 26546, "text": " router2# telnet 10_1_1_1\nTrying 10_1_1_1 .... Open\nUser Access Verification\nUsername: geeksforgeeks\nPassword:\nrouter1> " }, { "code": null, "e": 26825, "s": 26667, "text": "Now, we will telnet the router1 (ip address-10.1.1.1/24) from router2 (ip address – 10.1.1.2/24) and it will ask for the credentials as shown in the figure. " }, { "code": null, "e": 27035, "s": 26827, "text": "As soon as the user enters the credentials, we can see the authentication messages. In addition to this, if we want to apply a banner before asking for credentials, we can apply it using the command shown. " }, { "code": null, "e": 27113, "s": 27035, "text": "router1(config)#aaa authentication \n banner \" welcome to our network\" " }, { "code": null, "e": 27213, "s": 27113, "text": "If we want to add username and password prompt, we can apply it by using the command shown below. " }, { "code": null, "e": 27377, "s": 27213, "text": "router1(config)#aaa authentication \n username-prompt \"enter your username\" \nrouter1(config)#aaa authentication \n password-prompt \"enter your password\" " }, { "code": null, "e": 27521, "s": 27377, "text": "Also, if we want to show a message when the credentials entered by the user are wrong then we can show that by using the command shown below. " }, { "code": null, "e": 27625, "s": 27521, "text": "router1(config)#aaa authentication \n fail-message \"wrong username or password. \n Please try again...\" " }, { "code": null, "e": 27799, "s": 27625, "text": "Also, we can limit the number of attempts a user can enter wrong credentials. After the 3rd attempt to enter the credentials, the session will be automatically terminated. " }, { "code": null, "e": 27859, "s": 27799, "text": "router1(config)#aaa authentication \n attempts login 3" }, { "code": null, "e": 27875, "s": 27861, "text": "ManasChhabra2" }, { "code": null, "e": 27893, "s": 27875, "text": "Computer Networks" }, { "code": null, "e": 27911, "s": 27893, "text": "Computer Networks" }, { "code": null, "e": 28009, "s": 27911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28018, "s": 28009, "text": "Comments" }, { "code": null, "e": 28031, "s": 28018, "text": "Old Comments" }, { "code": null, "e": 28069, "s": 28031, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28106, "s": 28069, "text": "Error Detection in Computer Networks" }, { "code": null, "e": 28145, "s": 28106, "text": "Distance Vector Routing (DVR) Protocol" }, { "code": null, "e": 28172, "s": 28145, "text": "Socket Programming in Java" }, { "code": null, "e": 28206, "s": 28172, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 28239, "s": 28206, "text": "Hamming Code in Computer Network" }, { "code": null, "e": 28282, "s": 28239, "text": "Implementation of Diffie-Hellman Algorithm" }, { "code": null, "e": 28317, "s": 28282, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 28346, "s": 28317, "text": "User Datagram Protocol (UDP)" } ]
Stream Editor - Basic Commands
This chapter describes several useful SED commands. SED provides various commands to manipulate text. Let us first explore about the delete command. Here is how you execute a delete command: [address1[,address2]]d address1 and address2 are the starting and the ending addresses respectively, which can be either line numbers or pattern strings. Both of these addresses are optional parameters. As the name suggests, the delete command is used to perform delete operation and since the SED operates on line, we can say that this command is used to delete lines. Note that the delete command removes lines only from the pattern buffer; the line is not sent to the output stream and the original file remains unchanged. The following example illustrates the point. [jerry]$ sed 'd' books.txt But where is the output? If no line address is provided, then the SED operates on every line by default. Hence, it deletes all the lines from the pattern buffer. That is why the command does not print anything on the standard output. Let us instruct the SED to operate only on certain lines. The following example removes the 4th line only. [jerry]$ sed '4d' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 Additionally, SED also accepts address range using comma(,). We can instruct the SED to remove N1 to N2 lines. For instance, the following example deletes all the lines from 2 through 4. [jerry]$ sed '2, 4 d' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 SED's address range is not only limited to numbers. We can also specify patterns as an address. The following example removes all the books of the author Paulo Coelho. [jerry]$ sed '/Paulo Coelho/d' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 6) A Game of Thrones, George R. R. Martin, 864 We can also specify an address range using textual pattern. The following example removes all lines between the patterns Storm and Fellowship. [jerry]$ sed '/Storm/,/Fellowship/d' books.txt 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 In addition to this, we can also use dollar($), plus(+), and tilde(~) operators with SED. One of the important operations we perform on any file is backup, i.e., we make another copy of the file. SED provides the write command to store the contents of the pattern buffer in a file. Given below is the syntax of the write command which is similar to the delete command. [address1[,address2]]w file Here, address1 and address2 are the starting and the ending address respectively, which can be either line numbers or pattern strings. Both of these addresses are optional parameters. In the above syntax, w refers to the write command and file is the file name in which you store contents. Be careful with the file parameter. When a file name is provided, the SED creates a file on the fly if it is not present, and overwrites it if it is already present. Let us make an exact copy of the file using SED. Note that there must be exactly one space between w and file. [jerry]$ sed -n 'w books.bak' books.txt We created another file called books.bak. Now verify that both the files have identical content. [jerry]$ diff books.txt books.bak [jerry]$ echo $? On executing the above code, you get the following result: 0 You may assume that the cp command does exactly the same thing. Yes! The cp command does the same thing, but SED is a matured utility. It allows creating a file containing only certain lines from the source file. Let us store only even lines to another file. [jerry]$ sed -n '2~2 w junk.txt' books.txt [jerry]$ cat junk.txt On executing the above code, you get the following result: 2) The Two Towers, J. R. R. Tolkien, 352 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 6) A Game of Thrones, George R. R. Martin, 864 You can also use comma(,), dollar($), and plus(+) operators with the write command. In addition to this, SED also supports pattern matching with the write command. Suppose you want to store all the books of individual authors into a separate file. One boring and lengthy way is do it manually, and the smarter way is to use SED. [jerry]$ sed -n -e '/Martin/ w Martin.txt' -e '/Paulo/ w Paulo.txt' -e '/Tolkien/ w Tolkien.txt' books.txt In the above example, we are matching each line against a pattern and storing the matched line in a particular file. It is very simple. To specify multiple commands, we used -e switch of the SED command. Now let use see what each file contains: [jerry]$ cat Martin.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 6) A Game of Thrones, George R. R. Martin, 864 Let us display the file contents. [jerry]$ cat Paulo.txt On executing the above code, you get the following result: 3) The Alchemist, Paulo Coelho, 197 5) The Pilgrimage, Paulo Coelho, 288 Let us display the file contents. [jerry]$ cat Tolkien.txt On executing the above code, you get the following result: 2) The Two Towers, J. R. R. Tolkien, 352 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 Excellent! We got the expected result. SED is really an amazing utility. One of the most useful operations of any text editor is to provide append functionality. SED supports this operation through its append command. Given below is the syntax of append: [address]a\ Append text Let us append a new book entry after line number 4. The following example shows how to do it [jerry]$ sed '4 a 7) Adultry, Paulo Coelho, 234' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 7) Adultry, Paulo Coelho, 234 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 In the command section, 4 implies the line number, a is the append command, and the remaining part is the text to be appended. Let us insert a text line at the end of the file. To do this, use $ as the address. The following example illustrates this: [jerry]$ sed '$ a 7) Adultry, Paulo Coelho, 234' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 7) Adultry, Paulo Coelho, 234 Apart from line number, we can also specify an address using textual pattern. For instance, the following example appends text after matching the string The Alchemist. [jerry]$ sed '/The Alchemist/ a 7) Adultry, Paulo Coelho, 234' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 7) Adultry, Paulo Coelho, 234 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 Note that if there are multiple patterns matching, then the text is appended after each match. The following example illustrates this scenario. [jerry]$ sed '/The/ a 7) Adultry, Paulo Coelho, 234' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 7) Adultry, Paulo Coelho, 234 3) The Alchemist, Paulo Coelho, 197 7) Adultry, Paulo Coelho, 234 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 7) Adultry, Paulo Coelho, 234 5) The Pilgrimage, Paulo Coelho, 288 7) Adultry, Paulo Coelho, 234 6) A Game of Thrones, George R. R. Martin, 864 SED provides change or replace command which is represented by c. This command helps replace an existing line with new text. When line range is provided, all the lines are replaced as a group by a single text line. Given below is the syntax of the change command: [address1[,address2]]c\ Replace text Let us replace the third line with some other text. [jerry]$ sed '3 c 3) Adultry, Paulo Coelho, 324' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) Adultry, Paulo Coelho, 324 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 SED also accepts patterns as an address. In the following example, a line is replaced when the pattern match succeeds. [jerry]$ sed '/The Alchemist/ c 3) Adultry, Paulo Coelho, 324' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) Adultry, Paulo Coelho, 324 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 SED also allows replacement of multiple lines with a single line. The following example removes lines from fourth through sixth and replaces them with new text. [jerry]$ sed '4, 6 c 4) Adultry, Paulo Coelho, 324' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) Adultry, Paulo Coelho, 324 The insert command works much in the same way as append does. The only difference is that it inserts a line before a specific position. Given below is the syntax of the insert command: [address]i\ Insert text Let us understand the insert command with some examples. The following command inserts a new entry before the fourth line. [jerry]$ sed '4 i 7) Adultry, Paulo Coelho, 324' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 7) Adultry, Paulo Coelho, 324 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 In the above example, 4 is the location number, i implies the insert command, and the remaining part is the text to be inserted. To insert text at the start of a file, provide the line address as 1. The following command illustrates this: [jerry]$ sed '1 i 7) Adultry, Paulo Coelho, 324' books.txt On executing the above code, you get the following result: 7) Adultry, Paulo Coelho, 324 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 Additionally, we can insert multiple lines. The following command inserts two lines before the last line. [jerry]$ sed '$ i 7) Adultry, Paulo Coelho, 324 On executing the above code, you get the following result: 8) Eleven Minutes, Paulo Coelho, 304' books.txt 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage,Paulo Coelho, 288 7) Adultry, Paulo Coelho, 324 8) Eleven Minutes, Paulo Coelho, 304 6) A Game of Thrones, George R. R. Martin, 864 Note that the entries to be inserted are entered on separate lines and delimited by the backslash(\) character. SED provides a command to translate characters and it is represented as y. It transforms the characters by position. Given below is the syntax of the translate command: [address1[,address2]]y/list-1/list-2/ Note that translation is based on the position of the character from list 1 to the character in the same position in list 2 and both lists must be explicit character lists. Regular expressions and character classes are unsupported. Additionally, the size of list 1 and list 2 must be same. The following example converts Arabic numbers to Roman numbers. [jerry]$ echo "1 5 15 20" | sed 'y/151520/IVXVXX/' On executing the above code, you get the following result: I V IV XX Can you differentiate between words separated by spaces and words separated by tab characters only by looking at them? Certainly not. But SED can do this for you. SED uses the l command to display hidden characters in the text. For example, tab character with \t and End-Of-Line with $ character. Given below is the syntax of the l command. [address1[,address2]]l [address1[,address2]]l [len] Let us create a file with tab characters for demonstration. For simplicity, we are going to use the same file, just by replacing spaces with tabs. Wait! But how to do that — by opening the file in a text editor and replacing each space with tab? Certainly not! We can make use of SED commands for that. [jerry]$ sed 's/ /\t/g' books.txt > junk.txt Now let us display the hidden characters by using the l command: [jerry]$ sed -n 'l' junk.txt On executing the above code, you get the following result: 1)\tA\tStorm\tof\tSwords,George\tR.\tR.\tMartin,1216$ 2)\tThe\tTwo\tTowers,J.\tR.\tR.\tTolkien,352$ 3)\tThe\tAlchemist,Paulo\tCoelho,197$ 4)\tThe\tFellowship\tof\tthe\tRing,J.\tR.\tR.\tTolkien,432$ 5)\tThe\tPilgrimage,Paulo\tCoelho,288$ 6)\tA\tGame\tof\tThrones,George\tR.\tR.\tMartin\t,864$ Like other SED commands, it also accepts line numbers and patterns as an address. You can try it yourselves. Let us take a close look at another interesting feature of SED. We can instruct the SED to perform line wrapping after a certain number of characters. The following example wraps lines after 25 characters. [jerry]$ sed -n 'l 25' books.txt On executing the above code, you get the following result: 1) A Storm of Swords,Geo\ rge R. R. Martin,1216$ 2) The Two Towers,J. R. \ R. Tolkien,352$ 3) The Alchemist,Paulo C\ oelho,197$ 4) The Fellowship of the\ Ring,J. R. R. Tolkien,4\ 32$ 5) The Pilgrimage,Paulo \ Coelho,288$ 6) A Game of Thrones,Geo\ rge R. R. Martin ,864$ Note that in the above example, wrap limit is provided after l command. In this case, it is 25 characters. This option is GNU specific and may not work with other variants of the SED. A wrap limit of 0 means never break the line unless there is a new line character. The following simple command illustrates this. [jerry]$ sed -n 'l 0' books.txt On executing the above code, you get the following result: 1) A Storm of Swords,George R. R. Martin,1216$ 2) The Two Towers,J. R. R. Tolkien,352$ 3) The Alchemist,Paulo Coelho,197$ 4) The Fellowship of the Ring,J. R. R. Tolkien,432$ 5) The Pilgrimage,Paulo Coelho,288$ 6) A Game of Thrones,George R. R. Martin,864$ Quit command instructs the SED to quit the current execution flow. It is represented by the q command. Given below is the syntax of the quit command: [address]q [address]q [value] Note that the quit command does not accept range of addresses, it only supports a single address. By default, SED follows read, execute, and repeat workflow; but when the quit command is encountered, it simply stops the current execution. Let us print the first 3 lines from the file. [jerry]$ sed '3 q' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 In addition to line number, we can also use textual patterns. The following command quits when pattern match succeeds. [jerry]$ sed '/The Alchemist/ q' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 In addition to this, SED can also accept a value which can be used as the exit status. The following command shows its exit status as 100. [jerry]$ sed '/The Alchemist/ q 100' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 Now let us verify the exit status. [jerry]$ echo $? On executing the above code, you get the following result: 100 We can instruct the SED to read the contents of a file and display them when a specific condition matches. The command is represented by the alphabet r. Given below is the syntax of the read command. [address]r file Note that there must be exactly one space between the r command and the file name. Let us understand it with a simple example. Create a sample file called junk.txt. [jerry]$ echo "This is junk text." > junk.txt The following command instructs the SED to read the contents of junk.txt and insert them after the third line. [jerry]$ sed '3 r junk.txt' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 This is junk text. 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 In the above example, 3 implies the line address, r is the command name, and junk.txt is the file name the contents of which are to be displayed. Additionally, the GNU SED also accepts a range of addresses. For instance, the following command inserts the contents of junk.txt after the third, fourth, and fifth lines. [jerry]$ sed '3, 5 r junk.txt' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 This is junk text. 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 This is junk text. 5) The Pilgrimage, Paulo Coelho, 288 This is junk text. 6) A Game of Thrones, George R. R. Martin, 864 Like other SED commands, the read command also accepts pattern as an address. For instance, the following command inserts the contents of junk.txt when the pattern match succeeds. [jerry]$ sed '/Paulo/ r junk.txt' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 3) The Alchemist, Paulo Coelho, 197 This is junk text. 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 This is junk text. 6) A Game of Thrones, George R. R. Martin, 864 We can execute external commands from SED using the execute command. It is represented by e. Given below is the syntax of the execute command. [address1[,address2]]e [command] Let us illustrate the execute command with a simple example. The following SED command executes the UNIX date command before the third line. [jerry]$ sed '3 e date' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 Sun Sep 7 18:04:49 IST 2014 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 Like other commands, it also accepts patterns as an address. For example, the following example executes date command when a pattern match succeeds. Note that after each pattern match, first the command is executed and then the contents of the pattern buffer are displayed. [jerry]$ sed '/Paulo/ e date' books.txt On executing the above code, you get the following result: 1) A Storm of Swords, George R. R. Martin, 1216 2) The Two Towers, J. R. R. Tolkien, 352 Sun Sep 7 18:06:04 IST 2014 3) The Alchemist, Paulo Coelho, 197 4) The Fellowship of the Ring, J. R. R. Tolkien, 432 Sun Sep 7 18:06:04 IST 2014 5) The Pilgrimage, Paulo Coelho, 288 6) A Game of Thrones, George R. R. Martin, 864 If you observe the syntax of the e command carefully, you will notice that command is optional. When no command is provided after e, it treats the contents of the pattern buffer as an external command. To illustrate this, let us create a commands.txt file with a few simple commands. [jerry]$ echo -e "date\ncal\nuname" > commands.txt [jerry]$ cat commands.txt On executing the above code, you get the following result: date cal uname Commands from the file are self-explanatory. In the absence of command after e, SED executes all these commands one by one. The following simple example illustrates this. [jerry]$ sed 'e' commands.txt On executing the above code, you get the following result: Sun Sep 7 18:14:20 IST 2014 September 2014 Su Mo Tu We Th Fr Sa 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 27 28 29 30 Linux Like other SED commands, the execute command also accepts all valid ranges of addresses. By default, SED operates on single line, however it can operate on multiple lines as well. Multi-line commands are denoted by uppercase letters. For example, unlike the n command, the N command does not clear and print the pattern space. Instead, it adds a newline (\n) at the end of the current pattern space and appends the next line from the input-file to the current pattern space and continues with the SED's standard flow by executing the rest of the SED commands. Given below is the syntax of the N command. [address1[,address2]]N Let us print a comma-separated list of book titles and their respective authors. The following example illustrates this. [jerry]$ sed 'N; s/\n/, /g' books.txt On executing the above code, you get the following result: A Storm of Swords, George R. R. Martin The Two Towers, J. R. R. Tolkien The Alchemist, Paulo Coelho The Fellowship of the Ring, J. R. R. Tolkien The Pilgrimage, Paulo Coelho A Game of Thrones, George R. R. Martin Let us understand how the above example works. The N command reads the first line, i.e.,A Storm of Swords into the pattern buffer and appends \n followed by the next line. The pattern space now contains A Storm of Swords\nGeorge R. R. Martin. In the next step, we are replacing the newline with a comma. Like p command, we have a P command to print the first part (up to embedded newline) of the multi-line pattern space created by the N command. Given below is the syntax of the P command which is similar to the p command. [address1[,address2]]P In the previous example, we saw that the N command creates a newline- separated list of book titles and their authors. Let us print only the first part of it, i.e., only the titles of the book. The following command illustrates this. [jerry]$ sed -n 'N;P' books.txt On executing the above code, you get the following result: A Storm of Swords The Two Towers The Alchemist The Fellowship of the Ring The Pilgrimage A Game of Thrones Note that in the absence of N, it behaves same as the p command. The following simple command illustrates this scenario. [jerry]$ sed -n 'P' books.txt On executing the above code, you get the following result: A Storm of Swords George R. R. Martin The Two Towers J. R. R. Tolkien The Alchemist Paulo Coelho The Fellowship of the Ring J. R. R. Tolkien The Pilgrimage Paulo Coelho A Game of Thrones George R. R. Martin In addition to this, SED also provides a v command which checks for version. If the provided version is greater than the installed SED version, then the command execution fails. Note that this option is GNU specific and may not work with other variants of SED. Given below is the syntax of the v command. [address1[,address2]]v [version] First, find out the current version of SED. [jerry]$ sed --version On executing the above code, you get the following result: sed (GNU sed) 4.2.2 In the following example, the SED version is greater than version 4.2.2, hence the SED command aborts its execution. [jerry]$ sed 'v 4.2.3' books.txt On executing the above code, you get the following result: sed: -e expression #1, char 7: expected newer version of sed But if the provided version is lesser than or equal to version 4.2.2, then the command works as expected. [jerry]$ sed 'v 4.2.2' books.txt On executing the above code, you get the following result: A Storm of Swords George R. R. Martin The Two Towers J. R. R. Tolkien The Alchemist Paulo Coelho The Fellowship of the Ring J. R. R. Tolkien The Pilgrimage Paulo Coelho A Game of Thrones George R. R. Martin 53 Lectures 3.5 hours Senol Atac 14 Lectures 44 mins Zach Miller 13 Lectures 2 hours Sandip Bhattacharya 28 Lectures 1 hours PARTHA MAJUMDAR 16 Lectures 1.5 hours Taurius Litvinavicius 38 Lectures 2 hours Davida Shensky Print Add Notes Bookmark this page
[ { "code": null, "e": 1875, "s": 1823, "text": "This chapter describes several useful SED commands." }, { "code": null, "e": 2014, "s": 1875, "text": "SED provides various commands to manipulate text. Let us first explore about the delete command. Here is how you execute a delete command:" }, { "code": null, "e": 2039, "s": 2014, "text": "[address1[,address2]]d \n" }, { "code": null, "e": 2219, "s": 2039, "text": "address1 and address2 are the starting and the ending addresses respectively, which can be either line numbers or pattern strings. Both of these addresses are optional parameters." }, { "code": null, "e": 2587, "s": 2219, "text": "As the name suggests, the delete command is used to perform delete operation and since the SED operates on line, we can say that this command is used to delete lines. Note that the delete command removes lines only from the pattern buffer; the line is not sent to the output stream and the original file remains unchanged. The following example illustrates the point." }, { "code": null, "e": 2616, "s": 2587, "text": "[jerry]$ sed 'd' books.txt \n" }, { "code": null, "e": 2850, "s": 2616, "text": "But where is the output? If no line address is provided, then the SED operates on every line by default. Hence, it deletes all the lines from the pattern buffer. That is why the command does not print anything on the standard output." }, { "code": null, "e": 2957, "s": 2850, "text": "Let us instruct the SED to operate only on certain lines. The following example removes the 4th line only." }, { "code": null, "e": 2987, "s": 2957, "text": "[jerry]$ sed '4d' books.txt \n" }, { "code": null, "e": 3046, "s": 2987, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 3260, "s": 3046, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 3447, "s": 3260, "text": "Additionally, SED also accepts address range using comma(,). We can instruct the SED to remove N1 to N2 lines. For instance, the following example deletes all the lines from 2 through 4." }, { "code": null, "e": 3481, "s": 3447, "text": "[jerry]$ sed '2, 4 d' books.txt \n" }, { "code": null, "e": 3540, "s": 3481, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 3675, "s": 3540, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 3843, "s": 3675, "text": "SED's address range is not only limited to numbers. We can also specify patterns as an address. The following example removes all the books of the author Paulo Coelho." }, { "code": null, "e": 3886, "s": 3843, "text": "[jerry]$ sed '/Paulo Coelho/d' books.txt \n" }, { "code": null, "e": 3945, "s": 3886, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 4139, "s": 3945, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 4282, "s": 4139, "text": "We can also specify an address range using textual pattern. The following example removes all lines between the patterns Storm and Fellowship." }, { "code": null, "e": 4418, "s": 4282, "text": "[jerry]$ sed '/Storm/,/Fellowship/d' books.txt \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 4508, "s": 4418, "text": "In addition to this, we can also use dollar($), plus(+), and tilde(~) operators with SED." }, { "code": null, "e": 4787, "s": 4508, "text": "One of the important operations we perform on any file is backup, i.e., we make another copy of the file. SED provides the write command to store the contents of the pattern buffer in a file. Given below is the syntax of the write command which is similar to the delete command." }, { "code": null, "e": 4817, "s": 4787, "text": "[address1[,address2]]w file \n" }, { "code": null, "e": 5001, "s": 4817, "text": "Here, address1 and address2 are the starting and the ending address respectively, which can be either line numbers or pattern strings. Both of these addresses are optional parameters." }, { "code": null, "e": 5273, "s": 5001, "text": "In the above syntax, w refers to the write command and file is the file name in which you store contents. Be careful with the file parameter. When a file name is provided, the SED creates a file on the fly if it is not present, and overwrites it if it is already present." }, { "code": null, "e": 5384, "s": 5273, "text": "Let us make an exact copy of the file using SED. Note that there must be exactly one space between w and file." }, { "code": null, "e": 5426, "s": 5384, "text": "[jerry]$ sed -n 'w books.bak' books.txt \n" }, { "code": null, "e": 5523, "s": 5426, "text": "We created another file called books.bak. Now verify that both the files have identical content." }, { "code": null, "e": 5577, "s": 5523, "text": "[jerry]$ diff books.txt books.bak \n[jerry]$ echo $?\n" }, { "code": null, "e": 5636, "s": 5577, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 5639, "s": 5636, "text": "0\n" }, { "code": null, "e": 5898, "s": 5639, "text": "You may assume that the cp command does exactly the same thing. Yes! The cp command does the same thing, but SED is a matured utility. It allows creating a file containing only certain lines from the source file. Let us store only even lines to another file." }, { "code": null, "e": 5967, "s": 5898, "text": "[jerry]$ sed -n '2~2 w junk.txt' books.txt \n[jerry]$ cat junk.txt \n" }, { "code": null, "e": 6026, "s": 5967, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 6171, "s": 6026, "text": "2) The Two Towers, J. R. R. Tolkien, 352 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 6255, "s": 6171, "text": "You can also use comma(,), dollar($), and plus(+) operators with the write command." }, { "code": null, "e": 6500, "s": 6255, "text": "In addition to this, SED also supports pattern matching with the write command. Suppose you want to store all the books of individual authors into a separate file. One boring and lengthy way is do it manually, and the smarter way is to use SED." }, { "code": null, "e": 6610, "s": 6500, "text": "[jerry]$ sed -n -e '/Martin/ w Martin.txt' -e '/Paulo/ w Paulo.txt' -e '/Tolkien/ w \nTolkien.txt' books.txt \n" }, { "code": null, "e": 6855, "s": 6610, "text": "In the above example, we are matching each line against a pattern and storing the matched line in a particular file. It is very simple. To specify multiple commands, we used -e switch of the SED command. Now let use see what each file contains:" }, { "code": null, "e": 6880, "s": 6855, "text": "[jerry]$ cat Martin.txt\n" }, { "code": null, "e": 6939, "s": 6880, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 7036, "s": 6939, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 7070, "s": 7036, "text": "Let us display the file contents." }, { "code": null, "e": 7094, "s": 7070, "text": "[jerry]$ cat Paulo.txt\n" }, { "code": null, "e": 7153, "s": 7094, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 7229, "s": 7153, "text": "3) The Alchemist, Paulo Coelho, 197 \n5) The Pilgrimage, Paulo Coelho, 288 \n" }, { "code": null, "e": 7263, "s": 7229, "text": "Let us display the file contents." }, { "code": null, "e": 7289, "s": 7263, "text": "[jerry]$ cat Tolkien.txt\n" }, { "code": null, "e": 7348, "s": 7289, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 7445, "s": 7348, "text": "2) The Two Towers, J. R. R. Tolkien, 352 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n" }, { "code": null, "e": 7518, "s": 7445, "text": "Excellent! We got the expected result. SED is really an amazing utility." }, { "code": null, "e": 7700, "s": 7518, "text": "One of the most useful operations of any text editor is to provide append functionality. SED supports this operation through its append command. Given below is the syntax of append:" }, { "code": null, "e": 7727, "s": 7700, "text": "[address]a\\ \nAppend text \n" }, { "code": null, "e": 7820, "s": 7727, "text": "Let us append a new book entry after line number 4. The following example shows how to do it" }, { "code": null, "e": 7881, "s": 7820, "text": "[jerry]$ sed '4 a 7) Adultry, Paulo Coelho, 234' books.txt \n" }, { "code": null, "e": 7940, "s": 7881, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 8239, "s": 7940, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n7) Adultry, Paulo Coelho, 234 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 8366, "s": 8239, "text": "In the command section, 4 implies the line number, a is the append command, and the remaining part is the text to be appended." }, { "code": null, "e": 8490, "s": 8366, "text": "Let us insert a text line at the end of the file. To do this, use $ as the address. The following example illustrates this:" }, { "code": null, "e": 8550, "s": 8490, "text": "[jerry]$ sed '$ a 7) Adultry, Paulo Coelho, 234' books.txt\n" }, { "code": null, "e": 8609, "s": 8550, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 8909, "s": 8609, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n7) Adultry, Paulo Coelho, 234 \n" }, { "code": null, "e": 9077, "s": 8909, "text": "Apart from line number, we can also specify an address using textual pattern. For instance, the following example appends text after matching the string The Alchemist." }, { "code": null, "e": 9153, "s": 9077, "text": "[jerry]$ sed '/The Alchemist/ a 7) Adultry, Paulo Coelho, 234' books.txt \n" }, { "code": null, "e": 9212, "s": 9153, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 9512, "s": 9212, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n7) Adultry, Paulo Coelho, 234 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 9656, "s": 9512, "text": "Note that if there are multiple patterns matching, then the text is appended after each match. The following example illustrates this scenario." }, { "code": null, "e": 9721, "s": 9656, "text": "[jerry]$ sed '/The/ a 7) Adultry, Paulo Coelho, 234' books.txt \n" }, { "code": null, "e": 9780, "s": 9721, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 10173, "s": 9780, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n7) Adultry, Paulo Coelho, 234 \n3) The Alchemist, Paulo Coelho, 197 \n7) Adultry, Paulo Coelho, 234 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n7) Adultry, Paulo Coelho, 234 \n5) The Pilgrimage, Paulo Coelho, 288 \n7) Adultry, Paulo Coelho, 234 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 10437, "s": 10173, "text": "SED provides change or replace command which is represented by c. This command helps replace an existing line with new text. When line range is provided, all the lines are replaced as a group by a single text line. Given below is the syntax of the change command:" }, { "code": null, "e": 10476, "s": 10437, "text": "[address1[,address2]]c\\ \nReplace text\n" }, { "code": null, "e": 10528, "s": 10476, "text": "Let us replace the third line with some other text." }, { "code": null, "e": 10588, "s": 10528, "text": "[jerry]$ sed '3 c 3) Adultry, Paulo Coelho, 324' books.txt\n" }, { "code": null, "e": 10647, "s": 10588, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 10909, "s": 10647, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) Adultry, Paulo Coelho, 324 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 11028, "s": 10909, "text": "SED also accepts patterns as an address. In the following example, a line is replaced when the pattern match succeeds." }, { "code": null, "e": 11102, "s": 11028, "text": "[jerry]$ sed '/The Alchemist/ c 3) Adultry, Paulo Coelho, 324' books.txt\n" }, { "code": null, "e": 11161, "s": 11102, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 11424, "s": 11161, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) Adultry, Paulo Coelho, 324 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 11585, "s": 11424, "text": "SED also allows replacement of multiple lines with a single line. The following example removes lines from fourth through sixth and replaces them with new text." }, { "code": null, "e": 11650, "s": 11585, "text": "[jerry]$ sed '4, 6 c 4) Adultry, Paulo Coelho, 324' books.txt \n" }, { "code": null, "e": 11709, "s": 11650, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 11868, "s": 11709, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) Adultry, Paulo Coelho, 324\n" }, { "code": null, "e": 12053, "s": 11868, "text": "The insert command works much in the same way as append does. The only difference is that it inserts a line before a specific position. Given below is the syntax of the insert command:" }, { "code": null, "e": 12080, "s": 12053, "text": "[address]i\\ \nInsert text \n" }, { "code": null, "e": 12203, "s": 12080, "text": "Let us understand the insert command with some examples. The following command inserts a new entry before the fourth line." }, { "code": null, "e": 12264, "s": 12203, "text": "[jerry]$ sed '4 i 7) Adultry, Paulo Coelho, 324' books.txt \n" }, { "code": null, "e": 12323, "s": 12264, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 12622, "s": 12323, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n7) Adultry, Paulo Coelho, 324 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 12751, "s": 12622, "text": "In the above example, 4 is the location number, i implies the insert command, and the remaining part is the text to be inserted." }, { "code": null, "e": 12861, "s": 12751, "text": "To insert text at the start of a file, provide the line address as 1. The following command illustrates this:" }, { "code": null, "e": 12921, "s": 12861, "text": "[jerry]$ sed '1 i 7) Adultry, Paulo Coelho, 324' books.txt\n" }, { "code": null, "e": 12980, "s": 12921, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 13012, "s": 12980, "text": "7) Adultry, Paulo Coelho, 324 \n" }, { "code": null, "e": 13280, "s": 13012, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 13386, "s": 13280, "text": "Additionally, we can insert multiple lines. The following command inserts two lines before the last line." }, { "code": null, "e": 13435, "s": 13386, "text": "[jerry]$ sed '$ i 7) Adultry, Paulo Coelho, 324\n" }, { "code": null, "e": 13494, "s": 13435, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 13879, "s": 13494, "text": "8) Eleven Minutes, Paulo Coelho, 304' books.txt \n1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage,Paulo Coelho, 288 \n7) Adultry, Paulo Coelho, 324 \n8) Eleven Minutes, Paulo Coelho, 304 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 13991, "s": 13879, "text": "Note that the entries to be inserted are entered on separate lines and delimited by the backslash(\\) character." }, { "code": null, "e": 14160, "s": 13991, "text": "SED provides a command to translate characters and it is represented as y. It transforms the characters by position. Given below is the syntax of the translate command:" }, { "code": null, "e": 14199, "s": 14160, "text": "[address1[,address2]]y/list-1/list-2/\n" }, { "code": null, "e": 14489, "s": 14199, "text": "Note that translation is based on the position of the character from list 1 to the character in the same position in list 2 and both lists must be explicit character lists. Regular expressions and character classes are unsupported. Additionally, the size of list 1 and list 2 must be same." }, { "code": null, "e": 14553, "s": 14489, "text": "The following example converts Arabic numbers to Roman numbers." }, { "code": null, "e": 14606, "s": 14553, "text": "[jerry]$ echo \"1 5 15 20\" | sed 'y/151520/IVXVXX/' \n" }, { "code": null, "e": 14665, "s": 14606, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 14677, "s": 14665, "text": "I V IV XX \n" }, { "code": null, "e": 15018, "s": 14677, "text": "Can you differentiate between words separated by spaces and words separated by tab characters only by looking at them? Certainly not. But SED can do this for you. SED uses the l command to display hidden characters in the text. For example, tab character with \\t and End-Of-Line with $ character. Given below is the syntax of the l command." }, { "code": null, "e": 15073, "s": 15018, "text": "[address1[,address2]]l \n[address1[,address2]]l [len] \n" }, { "code": null, "e": 15376, "s": 15073, "text": "Let us create a file with tab characters for demonstration. For simplicity, we are going to use the same file, just by replacing spaces with tabs. Wait! But how to do that — by opening the file in a text editor and replacing each space with tab? Certainly not! We can make use of SED commands for that." }, { "code": null, "e": 15423, "s": 15376, "text": "[jerry]$ sed 's/ /\\t/g' books.txt > junk.txt \n" }, { "code": null, "e": 15488, "s": 15423, "text": "Now let us display the hidden characters by using the l command:" }, { "code": null, "e": 15518, "s": 15488, "text": "[jerry]$ sed -n 'l' junk.txt\n" }, { "code": null, "e": 15577, "s": 15518, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 15875, "s": 15577, "text": "1)\\tA\\tStorm\\tof\\tSwords,George\\tR.\\tR.\\tMartin,1216$ \n2)\\tThe\\tTwo\\tTowers,J.\\tR.\\tR.\\tTolkien,352$ \n3)\\tThe\\tAlchemist,Paulo\\tCoelho,197$ \n4)\\tThe\\tFellowship\\tof\\tthe\\tRing,J.\\tR.\\tR.\\tTolkien,432$ \n5)\\tThe\\tPilgrimage,Paulo\\tCoelho,288$ \n6)\\tA\\tGame\\tof\\tThrones,George\\tR.\\tR.\\tMartin\\t,864$\n" }, { "code": null, "e": 15984, "s": 15875, "text": "Like other SED commands, it also accepts line numbers and patterns as an address. You can try it yourselves." }, { "code": null, "e": 16190, "s": 15984, "text": "Let us take a close look at another interesting feature of SED. We can instruct the SED to perform line wrapping after a certain number of characters. The following example wraps lines after 25 characters." }, { "code": null, "e": 16224, "s": 16190, "text": "[jerry]$ sed -n 'l 25' books.txt\n" }, { "code": null, "e": 16283, "s": 16224, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 16567, "s": 16283, "text": "1) A Storm of Swords,Geo\\ \nrge R. R. Martin,1216$ \n2) The Two Towers,J. R. \\ \nR. Tolkien,352$ \n3) The Alchemist,Paulo C\\ \noelho,197$ \n4) The Fellowship of the\\ \n Ring,J. R. R. Tolkien,4\\ \n32$ \n5) The Pilgrimage,Paulo \\ \nCoelho,288$ \n6) A Game of Thrones,Geo\\ \nrge R. R. Martin ,864$\n" }, { "code": null, "e": 16751, "s": 16567, "text": "Note that in the above example, wrap limit is provided after l command. In this case, it is 25 characters. This option is GNU specific and may not work with other variants of the SED." }, { "code": null, "e": 16881, "s": 16751, "text": "A wrap limit of 0 means never break the line unless there is a new line character. The following simple command illustrates this." }, { "code": null, "e": 16915, "s": 16881, "text": "[jerry]$ sed -n 'l 0' books.txt \n" }, { "code": null, "e": 16974, "s": 16915, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 17237, "s": 16974, "text": "1) A Storm of Swords,George R. R. Martin,1216$ \n2) The Two Towers,J. R. R. Tolkien,352$ \n3) The Alchemist,Paulo Coelho,197$ \n4) The Fellowship of the Ring,J. R. R. Tolkien,432$ \n5) The Pilgrimage,Paulo Coelho,288$ \n6) A Game of Thrones,George R. R. Martin,864$ \n" }, { "code": null, "e": 17387, "s": 17237, "text": "Quit command instructs the SED to quit the current execution flow. It is represented by the q command. Given below is the syntax of the quit command:" }, { "code": null, "e": 17419, "s": 17387, "text": "[address]q \n[address]q [value]\n" }, { "code": null, "e": 17658, "s": 17419, "text": "Note that the quit command does not accept range of addresses, it only supports a single address. By default, SED follows read, execute, and repeat workflow; but when the quit command is encountered, it simply stops the current execution." }, { "code": null, "e": 17704, "s": 17658, "text": "Let us print the first 3 lines from the file." }, { "code": null, "e": 17734, "s": 17704, "text": "[jerry]$ sed '3 q' books.txt\n" }, { "code": null, "e": 17793, "s": 17734, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 17921, "s": 17793, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197\n" }, { "code": null, "e": 18040, "s": 17921, "text": "In addition to line number, we can also use textual patterns. The following command quits when pattern match succeeds." }, { "code": null, "e": 18085, "s": 18040, "text": "[jerry]$ sed '/The Alchemist/ q' books.txt \n" }, { "code": null, "e": 18144, "s": 18085, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 18272, "s": 18144, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197\n" }, { "code": null, "e": 18411, "s": 18272, "text": "In addition to this, SED can also accept a value which can be used as the exit status. The following command shows its exit status as 100." }, { "code": null, "e": 18459, "s": 18411, "text": "[jerry]$ sed '/The Alchemist/ q 100' books.txt\n" }, { "code": null, "e": 18518, "s": 18459, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 18645, "s": 18518, "text": "1) A Storm of Swords, George R. R. Martin, 1216\n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197\n" }, { "code": null, "e": 18680, "s": 18645, "text": "Now let us verify the exit status." }, { "code": null, "e": 18699, "s": 18680, "text": "[jerry]$ echo $? \n" }, { "code": null, "e": 18758, "s": 18699, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 18763, "s": 18758, "text": "100\n" }, { "code": null, "e": 18963, "s": 18763, "text": "We can instruct the SED to read the contents of a file and display them when a specific condition matches. The command is represented by the alphabet r. Given below is the syntax of the read command." }, { "code": null, "e": 18980, "s": 18963, "text": "[address]r file\n" }, { "code": null, "e": 19063, "s": 18980, "text": "Note that there must be exactly one space between the r command and the file name." }, { "code": null, "e": 19145, "s": 19063, "text": "Let us understand it with a simple example. Create a sample file called junk.txt." }, { "code": null, "e": 19193, "s": 19145, "text": "[jerry]$ echo \"This is junk text.\" > junk.txt \n" }, { "code": null, "e": 19304, "s": 19193, "text": "The following command instructs the SED to read the contents of junk.txt and insert them after the third line." }, { "code": null, "e": 19344, "s": 19304, "text": "[jerry]$ sed '3 r junk.txt' books.txt \n" }, { "code": null, "e": 19403, "s": 19344, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 19691, "s": 19403, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \nThis is junk text. \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 20009, "s": 19691, "text": "In the above example, 3 implies the line address, r is the command name, and junk.txt is the file name the contents of which are to be displayed. Additionally, the GNU SED also accepts a range of addresses. For instance, the following command inserts the contents of junk.txt after the third, fourth, and fifth lines." }, { "code": null, "e": 20052, "s": 20009, "text": "[jerry]$ sed '3, 5 r junk.txt' books.txt \n" }, { "code": null, "e": 20111, "s": 20052, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 20439, "s": 20111, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \nThis is junk text. \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \nThis is junk text. \n5) The Pilgrimage, Paulo Coelho, 288 \nThis is junk text. \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 20619, "s": 20439, "text": "Like other SED commands, the read command also accepts pattern as an address. For instance, the following command inserts the contents of junk.txt when the pattern match succeeds." }, { "code": null, "e": 20666, "s": 20619, "text": "[jerry]$ sed '/Paulo/ r junk.txt' books.txt \n" }, { "code": null, "e": 20725, "s": 20666, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 21034, "s": 20725, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \nThis is junk text. \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \nThis is junk text. \n6) A Game of Thrones, George R. R. Martin, 864 \n" }, { "code": null, "e": 21177, "s": 21034, "text": "We can execute external commands from SED using the execute command. It is represented by e. Given below is the syntax of the execute command." }, { "code": null, "e": 21211, "s": 21177, "text": "[address1[,address2]]e [command]\n" }, { "code": null, "e": 21352, "s": 21211, "text": "Let us illustrate the execute command with a simple example. The following SED command executes the UNIX date command before the third line." }, { "code": null, "e": 21387, "s": 21352, "text": "[jerry]$ sed '3 e date' books.txt\n" }, { "code": null, "e": 21446, "s": 21387, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 21744, "s": 21446, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \nSun Sep 7 18:04:49 IST 2014 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 22018, "s": 21744, "text": "Like other commands, it also accepts patterns as an address. For example, the following example executes date command when a pattern match succeeds. Note that after each pattern match, first the command is executed and then the contents of the pattern buffer are displayed." }, { "code": null, "e": 22060, "s": 22018, "text": "[jerry]$ sed '/Paulo/ e date' books.txt \n" }, { "code": null, "e": 22119, "s": 22060, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 22447, "s": 22119, "text": "1) A Storm of Swords, George R. R. Martin, 1216 \n2) The Two Towers, J. R. R. Tolkien, 352 \nSun Sep 7 18:06:04 IST 2014 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \nSun Sep 7 18:06:04 IST 2014 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864\n" }, { "code": null, "e": 22731, "s": 22447, "text": "If you observe the syntax of the e command carefully, you will notice that command is optional. When no command is provided after e, it treats the contents of the pattern buffer as an external command. To illustrate this, let us create a commands.txt file with a few simple commands." }, { "code": null, "e": 22810, "s": 22731, "text": "[jerry]$ echo -e \"date\\ncal\\nuname\" > commands.txt \n[jerry]$ cat commands.txt\n" }, { "code": null, "e": 22869, "s": 22810, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 22887, "s": 22869, "text": "date \ncal \nuname\n" }, { "code": null, "e": 23058, "s": 22887, "text": "Commands from the file are self-explanatory. In the absence of command after e, SED executes all these commands one by one. The following simple example illustrates this." }, { "code": null, "e": 23090, "s": 23058, "text": "[jerry]$ sed 'e' commands.txt \n" }, { "code": null, "e": 23149, "s": 23090, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 23379, "s": 23149, "text": "Sun Sep 7 18:14:20 IST 2014 \n September 2014 \nSu Mo Tu We Th Fr Sa \n 1 2 3 4 5 6 \n 7 8 9 10 11 12 13 \n14 15 16 17 18 19 20 \n21 22 23 24 25 26 27 \n28 29 30 \n \nLinux \n" }, { "code": null, "e": 23468, "s": 23379, "text": "Like other SED commands, the execute command also accepts all valid ranges of addresses." }, { "code": null, "e": 23983, "s": 23468, "text": "By default, SED operates on single line, however it can operate on multiple lines as well. Multi-line commands are denoted by uppercase letters. For example, unlike the n command, the N command does not clear and print the pattern space. Instead, it adds a newline (\\n) at the end of the current pattern space and appends the next line from the input-file to the current pattern space and continues with the SED's standard flow by executing the rest of the SED commands. Given below is the syntax of the N command." }, { "code": null, "e": 24007, "s": 23983, "text": "[address1[,address2]]N\n" }, { "code": null, "e": 24128, "s": 24007, "text": "Let us print a comma-separated list of book titles and their respective authors. The following example illustrates this." }, { "code": null, "e": 24168, "s": 24128, "text": "[jerry]$ sed 'N; s/\\n/, /g' books.txt \n" }, { "code": null, "e": 24227, "s": 24168, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 24446, "s": 24227, "text": "A Storm of Swords, George R. R. Martin \nThe Two Towers, J. R. R. Tolkien \nThe Alchemist, Paulo Coelho \nThe Fellowship of the Ring, J. R. R. Tolkien \nThe Pilgrimage, Paulo Coelho \nA Game of Thrones, George R. R. Martin\n" }, { "code": null, "e": 24750, "s": 24446, "text": "Let us understand how the above example works. The N command reads the first line, i.e.,A Storm of Swords into the pattern buffer and appends \\n followed by the next line. The pattern space now contains A Storm of Swords\\nGeorge R. R. Martin. In the next step, we are replacing the newline with a comma." }, { "code": null, "e": 24971, "s": 24750, "text": "Like p command, we have a P command to print the first part (up to embedded newline) of the multi-line pattern space created by the N command. Given below is the syntax of the P command which is similar to the p command." }, { "code": null, "e": 24996, "s": 24971, "text": "[address1[,address2]]P \n" }, { "code": null, "e": 25230, "s": 24996, "text": "In the previous example, we saw that the N command creates a newline- separated list of book titles and their authors. Let us print only the first part of it, i.e., only the titles of the book. The following command illustrates this." }, { "code": null, "e": 25263, "s": 25230, "text": "[jerry]$ sed -n 'N;P' books.txt\n" }, { "code": null, "e": 25322, "s": 25263, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 25435, "s": 25322, "text": "A Storm of Swords \nThe Two Towers \nThe Alchemist \nThe Fellowship of the Ring \nThe Pilgrimage \nA Game of Thrones\n" }, { "code": null, "e": 25556, "s": 25435, "text": "Note that in the absence of N, it behaves same as the p command. The following simple command illustrates this scenario." }, { "code": null, "e": 25587, "s": 25556, "text": "[jerry]$ sed -n 'P' books.txt\n" }, { "code": null, "e": 25646, "s": 25587, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 25865, "s": 25646, "text": "A Storm of Swords \nGeorge R. R. Martin \nThe Two Towers \nJ. R. R. Tolkien \nThe Alchemist \nPaulo Coelho \nThe Fellowship of the Ring \nJ. R. R. Tolkien \nThe Pilgrimage \nPaulo Coelho \nA Game of Thrones \nGeorge R. R. Martin\n" }, { "code": null, "e": 26170, "s": 25865, "text": "In addition to this, SED also provides a v command which checks for version. If the provided version is greater than the installed SED version, then the command execution fails. Note that this option is GNU specific and may not work with other variants of SED. Given below is the syntax of the v command." }, { "code": null, "e": 26204, "s": 26170, "text": "[address1[,address2]]v [version]\n" }, { "code": null, "e": 26248, "s": 26204, "text": "First, find out the current version of SED." }, { "code": null, "e": 26273, "s": 26248, "text": "[jerry]$ sed --version \n" }, { "code": null, "e": 26332, "s": 26273, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 26354, "s": 26332, "text": "sed (GNU sed) 4.2.2 \n" }, { "code": null, "e": 26471, "s": 26354, "text": "In the following example, the SED version is greater than version 4.2.2, hence the SED command aborts its execution." }, { "code": null, "e": 26506, "s": 26471, "text": "[jerry]$ sed 'v 4.2.3' books.txt \n" }, { "code": null, "e": 26565, "s": 26506, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 26627, "s": 26565, "text": "sed: -e expression #1, char 7: expected newer version of sed\n" }, { "code": null, "e": 26733, "s": 26627, "text": "But if the provided version is lesser than or equal to version 4.2.2, then the command works as expected." }, { "code": null, "e": 26767, "s": 26733, "text": "[jerry]$ sed 'v 4.2.2' books.txt\n" }, { "code": null, "e": 26826, "s": 26767, "text": "On executing the above code, you get the following result:" }, { "code": null, "e": 27044, "s": 26826, "text": "A Storm of Swords \nGeorge R. R. Martin \nThe Two Towers \nJ. R. R. Tolkien \nThe Alchemist \nPaulo Coelho \nThe Fellowship of the Ring \nJ. R. R. Tolkien \nThe Pilgrimage \nPaulo Coelho \nA Game of Thrones George R. R. Martin\n" }, { "code": null, "e": 27079, "s": 27044, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 27091, "s": 27079, "text": " Senol Atac" }, { "code": null, "e": 27123, "s": 27091, "text": "\n 14 Lectures \n 44 mins\n" }, { "code": null, "e": 27136, "s": 27123, "text": " Zach Miller" }, { "code": null, "e": 27169, "s": 27136, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 27190, "s": 27169, "text": " Sandip Bhattacharya" }, { "code": null, "e": 27223, "s": 27190, "text": "\n 28 Lectures \n 1 hours \n" }, { "code": null, "e": 27240, "s": 27223, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 27275, "s": 27240, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 27298, "s": 27275, "text": " Taurius Litvinavicius" }, { "code": null, "e": 27331, "s": 27298, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 27347, "s": 27331, "text": " Davida Shensky" }, { "code": null, "e": 27354, "s": 27347, "text": " Print" }, { "code": null, "e": 27365, "s": 27354, "text": " Add Notes" } ]
C - Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type int − int **var; When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example − #include <stdio.h> int main () { int var; int *ptr; int **pptr; var = 3000; /* take the address of var */ ptr = &var; /* take the address of ptr using address of operator & */ pptr = &ptr; /* take the value using pptr */ printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr ); printf("Value available at **pptr = %d\n", **pptr); return 0; } When the above code is compiled and executed, it produces the following result − Value of var = 3000 Value available at *ptr = 3000 Value available at **pptr = 3000 Print Add Notes Bookmark this page
[ { "code": null, "e": 2399, "s": 2084, "text": "A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below." }, { "code": null, "e": 2621, "s": 2399, "text": "A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type int −" }, { "code": null, "e": 2633, "s": 2621, "text": "int **var;\n" }, { "code": null, "e": 2815, "s": 2633, "text": "When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example −" }, { "code": null, "e": 3236, "s": 2815, "text": "#include <stdio.h>\n \nint main () {\n\n int var;\n int *ptr;\n int **pptr;\n\n var = 3000;\n\n /* take the address of var */\n ptr = &var;\n\n /* take the address of ptr using address of operator & */\n pptr = &ptr;\n\n /* take the value using pptr */\n printf(\"Value of var = %d\\n\", var );\n printf(\"Value available at *ptr = %d\\n\", *ptr );\n printf(\"Value available at **pptr = %d\\n\", **pptr);\n\n return 0;\n}" }, { "code": null, "e": 3317, "s": 3236, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3402, "s": 3317, "text": "Value of var = 3000\nValue available at *ptr = 3000\nValue available at **pptr = 3000\n" }, { "code": null, "e": 3409, "s": 3402, "text": " Print" }, { "code": null, "e": 3420, "s": 3409, "text": " Add Notes" } ]
Sharpe Ratio, Sortino Ratio and Calmar Ratio | by Shuo Wang | Towards Data Science
In portfolio performance analysis, sharpe ratio is the usually the first number that people look at. However, it does not tell us the whole story (nothing does...). So, let’s spend some time looking at a few more metrics that can be very helpful at times. Sharpe ratio is the ratio of average return divided by the standard deviation of returns annualized. We had an introduction to it in a previous story. Let’s take a look at it again with a test price time series. import pandas as pdimport numpy as npfrom pandas.tseries.offsets import BDaydef daily_returns(prices): res = (prices/prices.shift(1) - 1.0)[1:] res.columns = ['return'] return resdef sharpe(returns, risk_free=0): adj_returns = returns - risk_free return (np.nanmean(adj_returns) * np.sqrt(252)) \ / np.nanstd(adj_returns, ddof=1)def test_price1(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] return pd.DataFrame(data={'date': bdates, 'price1': price}).set_index('date')def test_price2(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] for i in range(20)] return pd.DataFrame(data={'date': bdates, 'price2': price}).set_index('date')def test_price3(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] - i/10.0 for i in range(20)] return pd.DataFrame(data={'date': bdates, 'price3': price}).set_index('date')def test_price4(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] - i/8.0 for i in range(20)] return pd.DataFrame(data={'date': bdates, 'price4': price}).set_index('date')price1 = test_price1()return1 = daily_returns(price1)price2 = test_price2()return2 = daily_returns(price2)price3 = test_price3()return3 = daily_returns(price3)price4 = test_price4()return4 = daily_returns(price4)print('price1')print(f'sharpe: {sharpe(return1)}')print('price2')print(f'sharpe: {sharpe(return2)}')print('price3')print(f'sharpe: {sharpe(return3)}')print('price4')print(f'sharpe: {sharpe(return4)}') As you can see in this example, I have 4 test price time series. First one, price1, is simply a straight line (never mind the wiggles, it’s due to weekends that were left out). The second price time series, price2, has a flat region. The third price time series, price3, has a downward sloping region. The last time series, price4, has a slighter larger downward slope. The sharpe ratio for each price is calculated below: '''price1sharpe: 78.59900981328562price2sharpe: 7.9354707022912825price3sharpe: 3.61693599695678price4sharpe: 3.151996500460301''' As you can see, price1 has a very high sharpe ratio, due to almost non-existent volatility. Price2 has a sharpe ratio of almost 10 times less, due to the presence of a flat region. Price3 and Price4 are about two times lower than price2 due to the downward slope, and Price4 sharpe ratio is slightly lower than price3’s sharpe ratio. Looking at these numbers, one thing that might seem a little strange is how much the sharpe ratio decreased simply due to the presence of a flat region. After all, the total return didn’t change, and there is no drawdown at all. For an investor, price1 and price2 are not all that different. On the other hand, price3 and price4 have sizable drawdowns, yet the sharpe ratio decreased by about half, compared to a 10 times drop between price1 and price2. This seems to be a deficiency in the ability of sharpe ratio to tell us how desirable the price time series is. In order to address the issues with Sharpe ratio not reflecting downside of a time series linearly, Sortino ratio can sometimes be a good metric to look at. Sortino Ratio = average returns / downside risk where downside risk is the average negative returns within the time series. def downside_risk(returns, risk_free=0): adj_returns = returns - risk_free sqr_downside = np.square(np.clip(adj_returns, np.NINF, 0)) return np.sqrt(np.nanmean(sqr_downside) * 252)def sortino(returns, risk_free=0): adj_returns = returns - risk_free drisk = downside_risk(adj_returns) if drisk == 0: return np.nan return (np.nanmean(adj_returns) * np.sqrt(252)) \ / drisk Applying sortino ratio to our test prices: '''price1sortino: nanprice2sortino: nanprice3sortino: 2.210224924119601price4sortino: 1.7688718895750382''' prices price1 and price2 does not have negative returns at all, so the sortino ratio does not exist for them. for price3 the sortino ratio is 2.2 and for price4 the sortino ratio is 1.8, due to a more deep downward slope, as desired. Let’s take a look at one more example: def test_price5(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] - i/10.1 for i in range(20)] price[80] = 15 return pd.DataFrame(data={'date': bdates, 'price5': price}).set_index('date') In this new price time series, price5, we added a dip on top of the price3, you would think that this dip should decrease the sortino ratio, right? Let’s take a look: '''price3sharpe: 3.61693599695678sortino: 2.210224924119601price4sharpe: 3.151996500460301sortino: 1.7688718895750382price5sharpe: 2.945329220777157sortino: 0.4660330265232954''' Yes! Sortino ratio does reflect the dip. But don’t you think it is a little too big of a change? due to the dip in price, sortino ratio dropped from 1.8 to 0.5, a drop of more than 3 times. In an effort to control the distortions caused by outliers like we showed earlier, another ratio is helpful in detecting them. That is the calmar ratio. Calmar Ratio = geometric mean of returns / maximum drawdown We have explained maximum drawdown in a previous story. Geometric mean of returns is the cumulative return scaled by the time period length. def annual_returns(returns): num_years = len(returns) / 252 cum_ret_final = (returns + 1).prod().squeeze() return cum_ret_final ** (1 / num_years) - 1def calmar(returns): max_dd = max_drawdown(cumulative_returns(returns)) if max_dd < 0: return annual_returns(returns) / abs(max_dd) return np.nan'''price1sharpe: 78.59900981328562sortino: nancalmar: nanprice2sharpe: 7.9354707022912825sortino: nancalmar: nanprice3sharpe: 3.61693599695678sortino: 2.210224924119601calmar: 35.10246841328119price4sharpe: 3.151996500460301sortino: 1.7688718895750382calmar: 28.081974730625276price5sharpe: 2.945329220777157sortino: 0.4660330265232954calmar: 29.404801742258666''' As you can see in the results, for price4 and price5, calmar ratios are 28 and 29, respectively. It was not affected by the outlier excessively, and also because the downward slope in price5 is actually a tiny bit less than price4 (notice the 10.1 in price5 definition!), it’s calmar ratio actually increased a little! Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 428, "s": 172, "text": "In portfolio performance analysis, sharpe ratio is the usually the first number that people look at. However, it does not tell us the whole story (nothing does...). So, let’s spend some time looking at a few more metrics that can be very helpful at times." }, { "code": null, "e": 579, "s": 428, "text": "Sharpe ratio is the ratio of average return divided by the standard deviation of returns annualized. We had an introduction to it in a previous story." }, { "code": null, "e": 640, "s": 579, "text": "Let’s take a look at it again with a test price time series." }, { "code": null, "e": 2740, "s": 640, "text": "import pandas as pdimport numpy as npfrom pandas.tseries.offsets import BDaydef daily_returns(prices): res = (prices/prices.shift(1) - 1.0)[1:] res.columns = ['return'] return resdef sharpe(returns, risk_free=0): adj_returns = returns - risk_free return (np.nanmean(adj_returns) * np.sqrt(252)) \\ / np.nanstd(adj_returns, ddof=1)def test_price1(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] return pd.DataFrame(data={'date': bdates, 'price1': price}).set_index('date')def test_price2(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] for i in range(20)] return pd.DataFrame(data={'date': bdates, 'price2': price}).set_index('date')def test_price3(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] - i/10.0 for i in range(20)] return pd.DataFrame(data={'date': bdates, 'price3': price}).set_index('date')def test_price4(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] - i/8.0 for i in range(20)] return pd.DataFrame(data={'date': bdates, 'price4': price}).set_index('date')price1 = test_price1()return1 = daily_returns(price1)price2 = test_price2()return2 = daily_returns(price2)price3 = test_price3()return3 = daily_returns(price3)price4 = test_price4()return4 = daily_returns(price4)print('price1')print(f'sharpe: {sharpe(return1)}')print('price2')print(f'sharpe: {sharpe(return2)}')print('price3')print(f'sharpe: {sharpe(return3)}')print('price4')print(f'sharpe: {sharpe(return4)}')" }, { "code": null, "e": 3110, "s": 2740, "text": "As you can see in this example, I have 4 test price time series. First one, price1, is simply a straight line (never mind the wiggles, it’s due to weekends that were left out). The second price time series, price2, has a flat region. The third price time series, price3, has a downward sloping region. The last time series, price4, has a slighter larger downward slope." }, { "code": null, "e": 3163, "s": 3110, "text": "The sharpe ratio for each price is calculated below:" }, { "code": null, "e": 3294, "s": 3163, "text": "'''price1sharpe: 78.59900981328562price2sharpe: 7.9354707022912825price3sharpe: 3.61693599695678price4sharpe: 3.151996500460301'''" }, { "code": null, "e": 3628, "s": 3294, "text": "As you can see, price1 has a very high sharpe ratio, due to almost non-existent volatility. Price2 has a sharpe ratio of almost 10 times less, due to the presence of a flat region. Price3 and Price4 are about two times lower than price2 due to the downward slope, and Price4 sharpe ratio is slightly lower than price3’s sharpe ratio." }, { "code": null, "e": 3920, "s": 3628, "text": "Looking at these numbers, one thing that might seem a little strange is how much the sharpe ratio decreased simply due to the presence of a flat region. After all, the total return didn’t change, and there is no drawdown at all. For an investor, price1 and price2 are not all that different." }, { "code": null, "e": 4194, "s": 3920, "text": "On the other hand, price3 and price4 have sizable drawdowns, yet the sharpe ratio decreased by about half, compared to a 10 times drop between price1 and price2. This seems to be a deficiency in the ability of sharpe ratio to tell us how desirable the price time series is." }, { "code": null, "e": 4351, "s": 4194, "text": "In order to address the issues with Sharpe ratio not reflecting downside of a time series linearly, Sortino ratio can sometimes be a good metric to look at." }, { "code": null, "e": 4399, "s": 4351, "text": "Sortino Ratio = average returns / downside risk" }, { "code": null, "e": 4475, "s": 4399, "text": "where downside risk is the average negative returns within the time series." }, { "code": null, "e": 4881, "s": 4475, "text": "def downside_risk(returns, risk_free=0): adj_returns = returns - risk_free sqr_downside = np.square(np.clip(adj_returns, np.NINF, 0)) return np.sqrt(np.nanmean(sqr_downside) * 252)def sortino(returns, risk_free=0): adj_returns = returns - risk_free drisk = downside_risk(adj_returns) if drisk == 0: return np.nan return (np.nanmean(adj_returns) * np.sqrt(252)) \\ / drisk" }, { "code": null, "e": 4924, "s": 4881, "text": "Applying sortino ratio to our test prices:" }, { "code": null, "e": 5032, "s": 4924, "text": "'''price1sortino: nanprice2sortino: nanprice3sortino: 2.210224924119601price4sortino: 1.7688718895750382'''" }, { "code": null, "e": 5266, "s": 5032, "text": "prices price1 and price2 does not have negative returns at all, so the sortino ratio does not exist for them. for price3 the sortino ratio is 2.2 and for price4 the sortino ratio is 1.8, due to a more deep downward slope, as desired." }, { "code": null, "e": 5305, "s": 5266, "text": "Let’s take a look at one more example:" }, { "code": null, "e": 5675, "s": 5305, "text": "def test_price5(): start_date = pd.Timestamp(2020, 1, 1) + BDay() len = 100 bdates = [start_date + BDay(i) for i in range(len)] price = [10.0 + i/10.0 for i in range(len)] price[40:60] = [price[40] - i/10.1 for i in range(20)] price[80] = 15 return pd.DataFrame(data={'date': bdates, 'price5': price}).set_index('date')" }, { "code": null, "e": 5842, "s": 5675, "text": "In this new price time series, price5, we added a dip on top of the price3, you would think that this dip should decrease the sortino ratio, right? Let’s take a look:" }, { "code": null, "e": 6021, "s": 5842, "text": "'''price3sharpe: 3.61693599695678sortino: 2.210224924119601price4sharpe: 3.151996500460301sortino: 1.7688718895750382price5sharpe: 2.945329220777157sortino: 0.4660330265232954'''" }, { "code": null, "e": 6211, "s": 6021, "text": "Yes! Sortino ratio does reflect the dip. But don’t you think it is a little too big of a change? due to the dip in price, sortino ratio dropped from 1.8 to 0.5, a drop of more than 3 times." }, { "code": null, "e": 6364, "s": 6211, "text": "In an effort to control the distortions caused by outliers like we showed earlier, another ratio is helpful in detecting them. That is the calmar ratio." }, { "code": null, "e": 6424, "s": 6364, "text": "Calmar Ratio = geometric mean of returns / maximum drawdown" }, { "code": null, "e": 6480, "s": 6424, "text": "We have explained maximum drawdown in a previous story." }, { "code": null, "e": 6565, "s": 6480, "text": "Geometric mean of returns is the cumulative return scaled by the time period length." }, { "code": null, "e": 7250, "s": 6565, "text": "def annual_returns(returns): num_years = len(returns) / 252 cum_ret_final = (returns + 1).prod().squeeze() return cum_ret_final ** (1 / num_years) - 1def calmar(returns): max_dd = max_drawdown(cumulative_returns(returns)) if max_dd < 0: return annual_returns(returns) / abs(max_dd) return np.nan'''price1sharpe: 78.59900981328562sortino: nancalmar: nanprice2sharpe: 7.9354707022912825sortino: nancalmar: nanprice3sharpe: 3.61693599695678sortino: 2.210224924119601calmar: 35.10246841328119price4sharpe: 3.151996500460301sortino: 1.7688718895750382calmar: 28.081974730625276price5sharpe: 2.945329220777157sortino: 0.4660330265232954calmar: 29.404801742258666'''" }, { "code": null, "e": 7569, "s": 7250, "text": "As you can see in the results, for price4 and price5, calmar ratios are 28 and 29, respectively. It was not affected by the outlier excessively, and also because the downward slope in price5 is actually a tiny bit less than price4 (notice the 10.1 in price5 definition!), it’s calmar ratio actually increased a little!" } ]
NPDA for L = {0i1j2k | i==j or j==k ; i , j , k >= 1} - GeeksforGeeks
31 Aug, 2018 Prerequisite – Pushdown automata, Pushdown automata acceptance by final stateThe language L = {0i1j2k | i==j or j==k ; i , j , k >= 1} tells that every string of ‘0’, ‘1’ and ‘2’ have certain number of 0’s, then certain number of 1’s and then certain number of 2’s. The condition is that count of each of these 3 symbols should be atleast 1. Two important conditions for this language are that either count of 0 should be equal to count of 1 OR count of 1 should be equal to count of 2. Assume that string is ending with ‘$’. Examples: Input: 0 0 0 1 1 1 2 2 2 2 2 Here 0's = 3, 1's = 3 so i = j, 2's = 5 Output: Accepted Input: 0 0 1 1 1 2 2 2 Here 0's = 2, 1's = 3, 2's = 3 so j = k Output: Accepted Input : 0 0 1 1 1 2 2 2 2 Here 0's = 2, 1's = 3, 2's = 4 Output: Not accepted There are 2 approaches for the solution. First is for i==j and second is for j==k. These are: Steps for i == j : Input all 0’s in the stackWhen we get 1 as input pop a 0 from stack and goto next state.If input is 1 then pop 0 from stack.If stack becomes empty (i.e., every 0 corresponding to a 1 has been popped so i = j) and input is 2 then ignore it and goto next state.If input is 2 then ignore it . If input is finished and $ is received then goto final state. Input all 0’s in the stack When we get 1 as input pop a 0 from stack and goto next state. If input is 1 then pop 0 from stack. If stack becomes empty (i.e., every 0 corresponding to a 1 has been popped so i = j) and input is 2 then ignore it and goto next state. If input is 2 then ignore it . If input is finished and $ is received then goto final state. Steps for j == k : Input all 0’s in the stackWhen we get 1 as input push it onto stack and goto next state.If input is 1 then push it onto stack.If input is 2 pop a 1 from stack and goto next state.If input is 2 then pop 1 from stack. If input is finished and $ is received then pop a 0 from stack.Pop all remaining 0’s from the stack. If stack becomes empty then goto final state . Input all 0’s in the stack When we get 1 as input push it onto stack and goto next state. If input is 1 then push it onto stack. If input is 2 pop a 1 from stack and goto next state. If input is 2 then pop 1 from stack. If input is finished and $ is received then pop a 0 from stack. Pop all remaining 0’s from the stack. If stack becomes empty then goto final state . 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 Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems TCP/IP Model Difference between DFA and NFA Design 101 sequence detector (Mealy machine) Closure properties of Regular languages Conversion of Epsilon-NFA to NFA Regular expression to ∈-NFA
[ { "code": null, "e": 29810, "s": 29782, "text": "\n31 Aug, 2018" }, { "code": null, "e": 30336, "s": 29810, "text": "Prerequisite – Pushdown automata, Pushdown automata acceptance by final stateThe language L = {0i1j2k | i==j or j==k ; i , j , k >= 1} tells that every string of ‘0’, ‘1’ and ‘2’ have certain number of 0’s, then certain number of 1’s and then certain number of 2’s. The condition is that count of each of these 3 symbols should be atleast 1. Two important conditions for this language are that either count of 0 should be equal to count of 1 OR count of 1 should be equal to count of 2. Assume that string is ending with ‘$’." }, { "code": null, "e": 30346, "s": 30336, "text": "Examples:" }, { "code": null, "e": 30633, "s": 30346, "text": "Input: 0 0 0 1 1 1 2 2 2 2 2 \n Here 0's = 3, 1's = 3 so i = j, 2's = 5 \nOutput: Accepted \n \nInput: 0 0 1 1 1 2 2 2\n Here 0's = 2, 1's = 3, 2's = 3 so j = k\nOutput: Accepted\n\nInput : 0 0 1 1 1 2 2 2 2\n Here 0's = 2, 1's = 3, 2's = 4 \nOutput: Not accepted " }, { "code": null, "e": 30727, "s": 30633, "text": "There are 2 approaches for the solution. First is for i==j and second is for j==k. These are:" }, { "code": null, "e": 30746, "s": 30727, "text": "Steps for i == j :" }, { "code": null, "e": 31098, "s": 30746, "text": "Input all 0’s in the stackWhen we get 1 as input pop a 0 from stack and goto next state.If input is 1 then pop 0 from stack.If stack becomes empty (i.e., every 0 corresponding to a 1 has been popped so i = j) and input is 2 then ignore it and goto next state.If input is 2 then ignore it . If input is finished and $ is received then goto final state." }, { "code": null, "e": 31125, "s": 31098, "text": "Input all 0’s in the stack" }, { "code": null, "e": 31188, "s": 31125, "text": "When we get 1 as input pop a 0 from stack and goto next state." }, { "code": null, "e": 31225, "s": 31188, "text": "If input is 1 then pop 0 from stack." }, { "code": null, "e": 31361, "s": 31225, "text": "If stack becomes empty (i.e., every 0 corresponding to a 1 has been popped so i = j) and input is 2 then ignore it and goto next state." }, { "code": null, "e": 31454, "s": 31361, "text": "If input is 2 then ignore it . If input is finished and $ is received then goto final state." }, { "code": null, "e": 31473, "s": 31454, "text": "Steps for j == k :" }, { "code": null, "e": 31837, "s": 31473, "text": "Input all 0’s in the stackWhen we get 1 as input push it onto stack and goto next state.If input is 1 then push it onto stack.If input is 2 pop a 1 from stack and goto next state.If input is 2 then pop 1 from stack. If input is finished and $ is received then pop a 0 from stack.Pop all remaining 0’s from the stack. If stack becomes empty then goto final state ." }, { "code": null, "e": 31864, "s": 31837, "text": "Input all 0’s in the stack" }, { "code": null, "e": 31927, "s": 31864, "text": "When we get 1 as input push it onto stack and goto next state." }, { "code": null, "e": 31966, "s": 31927, "text": "If input is 1 then push it onto stack." }, { "code": null, "e": 32020, "s": 31966, "text": "If input is 2 pop a 1 from stack and goto next state." }, { "code": null, "e": 32121, "s": 32020, "text": "If input is 2 then pop 1 from stack. If input is finished and $ is received then pop a 0 from stack." }, { "code": null, "e": 32206, "s": 32121, "text": "Pop all remaining 0’s from the stack. If stack becomes empty then goto final state ." }, { "code": null, "e": 32214, "s": 32206, "text": "GATE CS" }, { "code": null, "e": 32247, "s": 32214, "text": "Theory of Computation & Automata" }, { "code": null, "e": 32345, "s": 32247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32354, "s": 32345, "text": "Comments" }, { "code": null, "e": 32367, "s": 32354, "text": "Old Comments" }, { "code": null, "e": 32387, "s": 32367, "text": "Layers of OSI Model" }, { "code": null, "e": 32411, "s": 32387, "text": "ACID Properties in DBMS" }, { "code": null, "e": 32432, "s": 32411, "text": "Normal Forms in DBMS" }, { "code": null, "e": 32459, "s": 32432, "text": "Types of Operating Systems" }, { "code": null, "e": 32472, "s": 32459, "text": "TCP/IP Model" }, { "code": null, "e": 32503, "s": 32472, "text": "Difference between DFA and NFA" }, { "code": null, "e": 32548, "s": 32503, "text": "Design 101 sequence detector (Mealy machine)" }, { "code": null, "e": 32588, "s": 32548, "text": "Closure properties of Regular languages" }, { "code": null, "e": 32621, "s": 32588, "text": "Conversion of Epsilon-NFA to NFA" } ]
Basics of Markov Chain Monte Carlo Algorithms | by Sheharyar Akhtar | Towards Data Science
Markov Chain Monte Carlo is a group of algorithms used to map out the posterior distribution by sampling from the posterior distribution. The reason we use this method instead of the quadratic approximation method is because when we encounter distributions that have multiple peaks, it is possible that the algorithm will converge to a local maxima, and not give us the true approximation of the posterior distribution. The Monte Carlo algorithms however, use the principles of randomness and chaos theory to solve problems that would otherwise be difficult, if not impossible, to solve analytically. Let’s start this discussion with an analogy, which we can update as we traverse through the different types of algorithms. Assume that there are 10 islands placed in a circular fashion, and there is a king that oversees these islands. King Markov has been advised by his trustees that in order to avoid a mutiny from the people, he must visit each island regularly. The condition is that each island must be visited in proportion to its population. The populations of the islands are distributed such that island 10 has 10 times the population of island 1, island 5 has 5 times the population of island 1 and so on; therefore, king Markov will stay at island 10, 10 times more than he will stay at island 1. One of king Markov’s statisticians explains a way in which he can plan his visits to the islands and keep his people happy. The method is:Step 1: Each week, king Markov decides between moving to the next island or staying on the current island.Step 2: He flips a coin. If the coin lands heads, king Markov considers moving to the next island in a clockwise direction. If the coin lands a tails, king Markov considers moving to the next island in a counter clockwise direction. Let’s call this island the proposal island.Step 3: if the population of the proposal island is more than that of the current island, king Markov always accepts the proposal, and moves to the proposal island. If the population of the proposal island is less than that of the current island, then he accepts the proposal with the probability of population_proposal/population_current. Since this is a probability, this can also result in king Markov not moving at all, and rejecting the proposal. The code for simulating this is given below. As you increase the number of weeks, you will definitely see that the number of weeks spent on the islands are proportional to the relative populations of the islands. num_weeks <- 1e4positions <- rep(0,num_weeks)current<-10for(i in 1:num_weeks){ ##record current position positions[i] <- current ##flip coin to generate a proposal proposal <- current + sample(c(-1,1), size = 1) ##This is just to make sure that proposal remains between 1 and 10 if(proposal < 1) proposal <- 10 if(proposal >10) proposal <- 1 #move? prob_move <- proposal/current current <- ifelse(runif(1)<prob_move, proposal, current)}barplot(prop.table(table(positions)), ylim = c(0,0.2)) This algorithm is known as the Metropolis algorithm. This is the simplest algorithms that belongs to the class of the Markov Chain Monte Carlo algorithms. Another addition to this is the Metropolis-Hastings algorithm. The only way that these two differ, is that while the Metropolis algorithm is just a random walk through the negative log posterior distribution, the Metropolis-Hastings presents a much more sensible proposal. This can be understood in greater detail with reference to its mathematics here.Let’s try to connect the dots here; you pick an estimated starting point on the posterior distribution. This is the island the king was on at the start of his journey. You generate a random number that proposes the direction in which the point should move. You calculate the density on the proposal point and the current point. If the proposal point has a higher posterior density than the current, you move to the proposal point. If it has a lower density, you move to the proposal point with the probability of density_proposal/density_current.So once you do this over and over again, you will always end up moving towards the peak of the posterior. The samples you take along the way help you estimate the shape of the posterior distribution. The reason we use this algorithm, which samples from the posterior to inform us about the probable shape of the posterior, is because if we try to find the equation for the posterior, and then try to optimize it, we would have to solve a very complex integral. Sometimes, these integrals aren’t even solvable, which is why sampling from the highest density regions gives us a much quicker and precise estimate about the shape of the posterior. Let’s assume king Markov has a brother named King Monte, who oversees the valley which is steep around the edges and flat at the center. For the sake of ease, let’s say that the valley is shaped like a bowl, and the population in the valley is spread inversely proportional to the steepness of the terrain. In simple words, around the edges where the valley is steep, there is a lower population, and around the center where the valley is flatter, there is a higher population. King Monte has been advised, just like king Markov, that in order to avoid a mutiny by his people, he must visit the valley in proportion to the population density. This problem is a little trickier than the previous one. Unlike King Markov’s problem, we are dealing with a continuous chunk of land to explore here.King Monte gets in his car and gives his car some random momentum impulse in some random direction. When the car stars going uphill, its kinetic energy starts converting into potential energy until the car stops and turns around, and moves back towards the center. At some predefined intervals, king Monte stops his car and meets the people in the region where he is; and this process repeats over and over. In the long run, king Monte will always visit the higher population regions more, as gravity will always force him towards the center more than the edges.Let’s try to analyze how this is applicable in determining the shape of the posterior. We have understood so far that computing the exact solution to the posterior would be too computationally expensive; However, we are capable of calculating the probability density at any single point. We can also compute the gradient of the posterior at any given point. The mathematics of this can be found here. So the algorithm basically runs a dynamics simulation, near exact to how king Monte’s car behaves. The only difference is, our point is moving on a frictionless plain. We must also define two things before we start the simulation. One is the number of steps that the point should take before stopping, lets call these leapfrog steps, and the second is the step size. The point is flicked in a random direction, with some random momentum. The gradient and density of the next step is evaluated and the energy considerations are taken into account. After we have taken our total leapfrog steps, the point stops and samples its current position on the posterior. The code for this can be found here. The figure below shows us the path the point takes for 5 samples. Hamilton did not create this algorithm, although he did contribute a lot to modern dynamics. Since HMC uses the principles of dynamics and energy conservation, quite literally, to reach the peak of the posterior, the algorithm was named after him. The reason why HMC is so popular is because unlike the Metropolis or Metropolis-Hastings algorithm, there is a very low chance of rejection to the proposal. The reason for this is, that the next point to sample is determined by a long chain of events which nearly always leads to the next sample having a greater posterior density than the current. The only time the proposal is rejected is when the energy of the system is not conserved, which usually happens when we have a bad numerical approximation of the proposal density. The biggest reason for using HMC, however, is not this. With a low number of parameters, Metropolis and HMC work very similarly. HMC is always more efficient, but the outcome is the quite the same. As you move towards higher dimensions, the mode of the posterior lies further and further away from where most of the probability mass exists. Its difficult to visualize more than 3 dimensions, so think of it this way. Where you have the number of parameters as a relatively low number like 3, the mode of the posterior would give a very good approximation to where most of the probability mass is. When you have a 1000 parameters, the shape of distribution becomes more and more like a donut, with most of the probability mass lying further away from the mode. This causes the Metropolis algorithms to reject proposals a lot more frequently than HMC, and hence takes a lot more time to converge. The plot shown below gives a little more meaning to this. In this article we went through two popular MCMC methods to understand them conceptually. In articles to come, I will be going over their implementations in R and Stan. All the code used in this article to generate the plots and simulate the data can be found here. [1] Richard McElreath, Statistical Rethinking with Examples in R and Stan (2020)[2]Stephanie Glen. “Metropolis-Hastings Algorithm / Metropolis Algorithm” From StatisticsHowTo.com: Elementary Statistics for the rest of us! https://www.statisticshowto.com/metropolis-hastings-algorithm/[3] Colin Carroll, https://colindcarroll.com/2019/04/11/hamiltonian-monte-carlo-from-scratch/
[ { "code": null, "e": 773, "s": 172, "text": "Markov Chain Monte Carlo is a group of algorithms used to map out the posterior distribution by sampling from the posterior distribution. The reason we use this method instead of the quadratic approximation method is because when we encounter distributions that have multiple peaks, it is possible that the algorithm will converge to a local maxima, and not give us the true approximation of the posterior distribution. The Monte Carlo algorithms however, use the principles of randomness and chaos theory to solve problems that would otherwise be difficult, if not impossible, to solve analytically." }, { "code": null, "e": 1222, "s": 773, "text": "Let’s start this discussion with an analogy, which we can update as we traverse through the different types of algorithms. Assume that there are 10 islands placed in a circular fashion, and there is a king that oversees these islands. King Markov has been advised by his trustees that in order to avoid a mutiny from the people, he must visit each island regularly. The condition is that each island must be visited in proportion to its population." }, { "code": null, "e": 2453, "s": 1222, "text": "The populations of the islands are distributed such that island 10 has 10 times the population of island 1, island 5 has 5 times the population of island 1 and so on; therefore, king Markov will stay at island 10, 10 times more than he will stay at island 1. One of king Markov’s statisticians explains a way in which he can plan his visits to the islands and keep his people happy. The method is:Step 1: Each week, king Markov decides between moving to the next island or staying on the current island.Step 2: He flips a coin. If the coin lands heads, king Markov considers moving to the next island in a clockwise direction. If the coin lands a tails, king Markov considers moving to the next island in a counter clockwise direction. Let’s call this island the proposal island.Step 3: if the population of the proposal island is more than that of the current island, king Markov always accepts the proposal, and moves to the proposal island. If the population of the proposal island is less than that of the current island, then he accepts the proposal with the probability of population_proposal/population_current. Since this is a probability, this can also result in king Markov not moving at all, and rejecting the proposal." }, { "code": null, "e": 2666, "s": 2453, "text": "The code for simulating this is given below. As you increase the number of weeks, you will definitely see that the number of weeks spent on the islands are proportional to the relative populations of the islands." }, { "code": null, "e": 3173, "s": 2666, "text": "num_weeks <- 1e4positions <- rep(0,num_weeks)current<-10for(i in 1:num_weeks){ ##record current position positions[i] <- current ##flip coin to generate a proposal proposal <- current + sample(c(-1,1), size = 1) ##This is just to make sure that proposal remains between 1 and 10 if(proposal < 1) proposal <- 10 if(proposal >10) proposal <- 1 #move? prob_move <- proposal/current current <- ifelse(runif(1)<prob_move, proposal, current)}barplot(prop.table(table(positions)), ylim = c(0,0.2))" }, { "code": null, "e": 4427, "s": 3173, "text": "This algorithm is known as the Metropolis algorithm. This is the simplest algorithms that belongs to the class of the Markov Chain Monte Carlo algorithms. Another addition to this is the Metropolis-Hastings algorithm. The only way that these two differ, is that while the Metropolis algorithm is just a random walk through the negative log posterior distribution, the Metropolis-Hastings presents a much more sensible proposal. This can be understood in greater detail with reference to its mathematics here.Let’s try to connect the dots here; you pick an estimated starting point on the posterior distribution. This is the island the king was on at the start of his journey. You generate a random number that proposes the direction in which the point should move. You calculate the density on the proposal point and the current point. If the proposal point has a higher posterior density than the current, you move to the proposal point. If it has a lower density, you move to the proposal point with the probability of density_proposal/density_current.So once you do this over and over again, you will always end up moving towards the peak of the posterior. The samples you take along the way help you estimate the shape of the posterior distribution." }, { "code": null, "e": 4871, "s": 4427, "text": "The reason we use this algorithm, which samples from the posterior to inform us about the probable shape of the posterior, is because if we try to find the equation for the posterior, and then try to optimize it, we would have to solve a very complex integral. Sometimes, these integrals aren’t even solvable, which is why sampling from the highest density regions gives us a much quicker and precise estimate about the shape of the posterior." }, { "code": null, "e": 7390, "s": 4871, "text": "Let’s assume king Markov has a brother named King Monte, who oversees the valley which is steep around the edges and flat at the center. For the sake of ease, let’s say that the valley is shaped like a bowl, and the population in the valley is spread inversely proportional to the steepness of the terrain. In simple words, around the edges where the valley is steep, there is a lower population, and around the center where the valley is flatter, there is a higher population. King Monte has been advised, just like king Markov, that in order to avoid a mutiny by his people, he must visit the valley in proportion to the population density. This problem is a little trickier than the previous one. Unlike King Markov’s problem, we are dealing with a continuous chunk of land to explore here.King Monte gets in his car and gives his car some random momentum impulse in some random direction. When the car stars going uphill, its kinetic energy starts converting into potential energy until the car stops and turns around, and moves back towards the center. At some predefined intervals, king Monte stops his car and meets the people in the region where he is; and this process repeats over and over. In the long run, king Monte will always visit the higher population regions more, as gravity will always force him towards the center more than the edges.Let’s try to analyze how this is applicable in determining the shape of the posterior. We have understood so far that computing the exact solution to the posterior would be too computationally expensive; However, we are capable of calculating the probability density at any single point. We can also compute the gradient of the posterior at any given point. The mathematics of this can be found here. So the algorithm basically runs a dynamics simulation, near exact to how king Monte’s car behaves. The only difference is, our point is moving on a frictionless plain. We must also define two things before we start the simulation. One is the number of steps that the point should take before stopping, lets call these leapfrog steps, and the second is the step size. The point is flicked in a random direction, with some random momentum. The gradient and density of the next step is evaluated and the energy considerations are taken into account. After we have taken our total leapfrog steps, the point stops and samples its current position on the posterior. The code for this can be found here. The figure below shows us the path the point takes for 5 samples." }, { "code": null, "e": 8167, "s": 7390, "text": "Hamilton did not create this algorithm, although he did contribute a lot to modern dynamics. Since HMC uses the principles of dynamics and energy conservation, quite literally, to reach the peak of the posterior, the algorithm was named after him. The reason why HMC is so popular is because unlike the Metropolis or Metropolis-Hastings algorithm, there is a very low chance of rejection to the proposal. The reason for this is, that the next point to sample is determined by a long chain of events which nearly always leads to the next sample having a greater posterior density than the current. The only time the proposal is rejected is when the energy of the system is not conserved, which usually happens when we have a bad numerical approximation of the proposal density." }, { "code": null, "e": 8927, "s": 8167, "text": "The biggest reason for using HMC, however, is not this. With a low number of parameters, Metropolis and HMC work very similarly. HMC is always more efficient, but the outcome is the quite the same. As you move towards higher dimensions, the mode of the posterior lies further and further away from where most of the probability mass exists. Its difficult to visualize more than 3 dimensions, so think of it this way. Where you have the number of parameters as a relatively low number like 3, the mode of the posterior would give a very good approximation to where most of the probability mass is. When you have a 1000 parameters, the shape of distribution becomes more and more like a donut, with most of the probability mass lying further away from the mode." }, { "code": null, "e": 9120, "s": 8927, "text": "This causes the Metropolis algorithms to reject proposals a lot more frequently than HMC, and hence takes a lot more time to converge. The plot shown below gives a little more meaning to this." }, { "code": null, "e": 9386, "s": 9120, "text": "In this article we went through two popular MCMC methods to understand them conceptually. In articles to come, I will be going over their implementations in R and Stan. All the code used in this article to generate the plots and simulate the data can be found here." } ]
Display tick marks in a JSlider with Java
To display tick marks in a JSlider, you need to use the setPaintTicks() method and set it to TRUE − JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 75); slider.setPaintTicks(true); The following is an example to display tick marks in a slider in Java − package my; import java.awt.Color; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Frame with Slider"); JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 75); slider.setMinorTickSpacing(5); slider.setMajorTickSpacing(20); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setBackground(Color.yellow); slider.setForeground(Color.red); Font font = new Font("Serif", Font.BOLD, 18); slider.setFont(font); JPanel panel = new JPanel(); panel.add(slider); frame.add(panel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(600, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1162, "s": 1062, "text": "To display tick marks in a JSlider, you need to use the setPaintTicks() method and set it to TRUE −" }, { "code": null, "e": 1252, "s": 1162, "text": "JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 75);\nslider.setPaintTicks(true);" }, { "code": null, "e": 1324, "s": 1252, "text": "The following is an example to display tick marks in a slider in Java −" }, { "code": null, "e": 2216, "s": 1324, "text": "package my;\nimport java.awt.Color;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JSlider;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Frame with Slider\");\n JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 75);\n slider.setMinorTickSpacing(5);\n slider.setMajorTickSpacing(20);\n slider.setPaintTicks(true);\n slider.setPaintLabels(true);\n slider.setBackground(Color.yellow);\n slider.setForeground(Color.red);\n Font font = new Font(\"Serif\", Font.BOLD, 18);\n slider.setFont(font);\n JPanel panel = new JPanel();\n panel.add(slider);\n frame.add(panel);\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.setSize(600, 300);\n frame.setVisible(true);\n }\n}" } ]
Getting Started with Comet ML. An overview of the popular... | by Angelica Lo Duca | Towards Data Science
Comet ML is an experimentation platform, which permits testing Machine Learning projects, from the beginning up to the final monitoring. Many other similar platforms exist on the Web, including Neptune.ai, Guild.ai, Sacred, and so on. Comet ML can be easily integrated with the most popular Machine Learning libraries, including scikit-learn, Pytorch, Tensorflow, Keras, and so on. Experiments can be written in Python, Javascript, Java, R, and REST APIs. In this article, I focus on Python. The article is organized as follows: Overview of Comet ML Working with Comet ML Example of usage Comet ML is an online platform, which permits tracking experiments. The main advantage of Comet ML is that I can easily build a reporting dashboard and a monitoring system. Comet ML provides the following features: compare experiments: I can easily build different experiments for the same project, and compare the results, in terms of metrics, system metrics, parameters, and so on; monitor the model: I can monitor the model from the early stages up to production. This can be done through alerts and debugging strategies; collaborate with other people: I can share my workspace project with other people; build reports and panels: starting from the results of my experiment, I can easily build reports and dashboards; keep my project public or make it public. Once I enter the Comet ML Web site, I can create a free account. Then, I log in to the platform and I create a new project, by clicking the relative top right button. I fill the form with needed information: When I click on the Create button, an empty dashboard appears. I can add a new experiment, by clicking the button on the top right of the page (+Add). I select Experiment from the dropdown menu. The platform generates a new API for the experiment, that can be used in my Python code: # import comet_ml at the top of your filefrom comet_ml import Experiment# Create an experiment with your api keyexperiment = Experiment( api_key="PUT HERE MY API KEY", project_name="decisiontree", workspace="PUT HERE MY ACCOUNT NAME",) Now, I need to install the comet_ml Python package on my local computer: pip3 install comet_ml And then I can start coding, as usual. The Experiment class is the interface of the local code to Comet ML. It defines many methods, which are described in the Comet Official Documentation. Here, I describe some common methods: log_metric() and log_metrics() — register one or more evaluation metrics to the experiment, such as accuracy, precision, and recall; log_confusion_matrix() —register a confusion matrix to the experiment; log_figure() — register a figure (e.g. pyplot) to the experiment and save it as an SVG image; display() — create an interactive environment in Jupyter, showing the Comet ML dashboard as the output of a cell; end() — if the experiment runs in Jupyter, this method specifies that the experiment is concluded. Once an experiment has been completed, Comet ML provides a dashboard, where I can see all the metrics, figures, parameters, and so on, that I have tracked in my code. Evaluation metrics are automatically plotted. For example, if an experiment is run over multiple steps, I can easily draw graphs showing metrics versus step numbers. In the left part of the Experiment Dashboard, many options can be selected, included but not limited to: Panels — final dashboards, that can be used as reports for the final user; Metrics — a table with all the metrics and their values; System Metrics — a visual representation of all the system metrics, including Memory Usage, CPU Utilization. As a practical use case of Comet ML, I exploit the Heart Attacks dataset, provided by Kaggle. Firstly, I set up the experiment, by specifying the project name and the workspace (my account name). from comet_ml import Experimentexperiment = Experiment( api_key="PUT HERE MY API KEY", project_name="decisiontree", workspace="PUT HERE MY ACCOUNT NAME",) Now I can work as usual. I load the dataset as a pandas dataframe. import pandas as pddf = pd.read_csv('source/heart.csv')df.head() I define feature columns. cols = []for col in df.columns: if col != 'output': cols.append(col) I define input and output variables: X = df[cols]y = df['output'] I scale all the input features through a MinMaxScaler from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()X_scaled = scaler.fit_transform(X) I set up the dataset in training and test sets. from sklearn.model_selection import train_test_splitrandom_state = 42X_train, X_test, y_train, y_test = train_test_split(X_scaled,y, random_state=random_state) I exploit a DecisionTreeClassifier as a model. I fit it with a progressive number of samples included in the training set and I predict the output class for all the samples in the test set. I also build a classification report for each step. I log the metrics returned by the classification_report() function through the Comet Experiment function, called log_metrics(). I also log the confusion matrix, through the experiment.log_confusion_matrix() function. from sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import classification_reportimport numpy as npmodel = DecisionTreeClassifier(random_state=random_state, max_depth=2)min_samples = 5target_names = ["class 0", "class 1"]for step in range(min_samples, len(X_train)): model.fit(X_train[0:step], y_train[0:step]) y_pred = model.predict(X_test) pred_proba = np.max(model.predict_proba(X_test), axis=1) report = classification_report(y_test, y_pred, target_names=target_names, output_dict=True) for label, metric in report.items(): try: experiment.log_metrics(metric, prefix=label, step=step)except: experiment.log_metric(label, metric,step=i) experiment.log_confusion_matrix(y_test.tolist(), y_pred.tolist()) I show the experiment results in Jupyter. experiment.display(tab="confusion-matrices") The following figure shows an excerpt of the produced dashboard: I conclude the experiment. experiment.end() Congratulations! You have learned how to configure and run an experiment in Comet ML, an Experimentation Platform for Machine Learning. Comet ML can be exploited to run more complex experiments. Stay tuned for more tips 😃 If you have come this far to read, for me it is already a lot for today. Thanks! You can read more about me in this article.
[ { "code": null, "e": 407, "s": 172, "text": "Comet ML is an experimentation platform, which permits testing Machine Learning projects, from the beginning up to the final monitoring. Many other similar platforms exist on the Web, including Neptune.ai, Guild.ai, Sacred, and so on." }, { "code": null, "e": 628, "s": 407, "text": "Comet ML can be easily integrated with the most popular Machine Learning libraries, including scikit-learn, Pytorch, Tensorflow, Keras, and so on. Experiments can be written in Python, Javascript, Java, R, and REST APIs." }, { "code": null, "e": 664, "s": 628, "text": "In this article, I focus on Python." }, { "code": null, "e": 701, "s": 664, "text": "The article is organized as follows:" }, { "code": null, "e": 722, "s": 701, "text": "Overview of Comet ML" }, { "code": null, "e": 744, "s": 722, "text": "Working with Comet ML" }, { "code": null, "e": 761, "s": 744, "text": "Example of usage" }, { "code": null, "e": 934, "s": 761, "text": "Comet ML is an online platform, which permits tracking experiments. The main advantage of Comet ML is that I can easily build a reporting dashboard and a monitoring system." }, { "code": null, "e": 976, "s": 934, "text": "Comet ML provides the following features:" }, { "code": null, "e": 1145, "s": 976, "text": "compare experiments: I can easily build different experiments for the same project, and compare the results, in terms of metrics, system metrics, parameters, and so on;" }, { "code": null, "e": 1286, "s": 1145, "text": "monitor the model: I can monitor the model from the early stages up to production. This can be done through alerts and debugging strategies;" }, { "code": null, "e": 1369, "s": 1286, "text": "collaborate with other people: I can share my workspace project with other people;" }, { "code": null, "e": 1482, "s": 1369, "text": "build reports and panels: starting from the results of my experiment, I can easily build reports and dashboards;" }, { "code": null, "e": 1524, "s": 1482, "text": "keep my project public or make it public." }, { "code": null, "e": 1732, "s": 1524, "text": "Once I enter the Comet ML Web site, I can create a free account. Then, I log in to the platform and I create a new project, by clicking the relative top right button. I fill the form with needed information:" }, { "code": null, "e": 1795, "s": 1732, "text": "When I click on the Create button, an empty dashboard appears." }, { "code": null, "e": 1927, "s": 1795, "text": "I can add a new experiment, by clicking the button on the top right of the page (+Add). I select Experiment from the dropdown menu." }, { "code": null, "e": 2016, "s": 1927, "text": "The platform generates a new API for the experiment, that can be used in my Python code:" }, { "code": null, "e": 2261, "s": 2016, "text": "# import comet_ml at the top of your filefrom comet_ml import Experiment# Create an experiment with your api keyexperiment = Experiment( api_key=\"PUT HERE MY API KEY\", project_name=\"decisiontree\", workspace=\"PUT HERE MY ACCOUNT NAME\",)" }, { "code": null, "e": 2334, "s": 2261, "text": "Now, I need to install the comet_ml Python package on my local computer:" }, { "code": null, "e": 2357, "s": 2334, "text": "pip3 install comet_ml " }, { "code": null, "e": 2396, "s": 2357, "text": "And then I can start coding, as usual." }, { "code": null, "e": 2547, "s": 2396, "text": "The Experiment class is the interface of the local code to Comet ML. It defines many methods, which are described in the Comet Official Documentation." }, { "code": null, "e": 2585, "s": 2547, "text": "Here, I describe some common methods:" }, { "code": null, "e": 2718, "s": 2585, "text": "log_metric() and log_metrics() — register one or more evaluation metrics to the experiment, such as accuracy, precision, and recall;" }, { "code": null, "e": 2789, "s": 2718, "text": "log_confusion_matrix() —register a confusion matrix to the experiment;" }, { "code": null, "e": 2883, "s": 2789, "text": "log_figure() — register a figure (e.g. pyplot) to the experiment and save it as an SVG image;" }, { "code": null, "e": 2997, "s": 2883, "text": "display() — create an interactive environment in Jupyter, showing the Comet ML dashboard as the output of a cell;" }, { "code": null, "e": 3096, "s": 2997, "text": "end() — if the experiment runs in Jupyter, this method specifies that the experiment is concluded." }, { "code": null, "e": 3263, "s": 3096, "text": "Once an experiment has been completed, Comet ML provides a dashboard, where I can see all the metrics, figures, parameters, and so on, that I have tracked in my code." }, { "code": null, "e": 3429, "s": 3263, "text": "Evaluation metrics are automatically plotted. For example, if an experiment is run over multiple steps, I can easily draw graphs showing metrics versus step numbers." }, { "code": null, "e": 3534, "s": 3429, "text": "In the left part of the Experiment Dashboard, many options can be selected, included but not limited to:" }, { "code": null, "e": 3609, "s": 3534, "text": "Panels — final dashboards, that can be used as reports for the final user;" }, { "code": null, "e": 3666, "s": 3609, "text": "Metrics — a table with all the metrics and their values;" }, { "code": null, "e": 3775, "s": 3666, "text": "System Metrics — a visual representation of all the system metrics, including Memory Usage, CPU Utilization." }, { "code": null, "e": 3869, "s": 3775, "text": "As a practical use case of Comet ML, I exploit the Heart Attacks dataset, provided by Kaggle." }, { "code": null, "e": 3971, "s": 3869, "text": "Firstly, I set up the experiment, by specifying the project name and the workspace (my account name)." }, { "code": null, "e": 4135, "s": 3971, "text": "from comet_ml import Experimentexperiment = Experiment( api_key=\"PUT HERE MY API KEY\", project_name=\"decisiontree\", workspace=\"PUT HERE MY ACCOUNT NAME\",)" }, { "code": null, "e": 4202, "s": 4135, "text": "Now I can work as usual. I load the dataset as a pandas dataframe." }, { "code": null, "e": 4267, "s": 4202, "text": "import pandas as pddf = pd.read_csv('source/heart.csv')df.head()" }, { "code": null, "e": 4293, "s": 4267, "text": "I define feature columns." }, { "code": null, "e": 4372, "s": 4293, "text": "cols = []for col in df.columns: if col != 'output': cols.append(col)" }, { "code": null, "e": 4409, "s": 4372, "text": "I define input and output variables:" }, { "code": null, "e": 4438, "s": 4409, "text": "X = df[cols]y = df['output']" }, { "code": null, "e": 4492, "s": 4438, "text": "I scale all the input features through a MinMaxScaler" }, { "code": null, "e": 4596, "s": 4492, "text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()X_scaled = scaler.fit_transform(X)" }, { "code": null, "e": 4644, "s": 4596, "text": "I set up the dataset in training and test sets." }, { "code": null, "e": 4804, "s": 4644, "text": "from sklearn.model_selection import train_test_splitrandom_state = 42X_train, X_test, y_train, y_test = train_test_split(X_scaled,y, random_state=random_state)" }, { "code": null, "e": 5046, "s": 4804, "text": "I exploit a DecisionTreeClassifier as a model. I fit it with a progressive number of samples included in the training set and I predict the output class for all the samples in the test set. I also build a classification report for each step." }, { "code": null, "e": 5263, "s": 5046, "text": "I log the metrics returned by the classification_report() function through the Comet Experiment function, called log_metrics(). I also log the confusion matrix, through the experiment.log_confusion_matrix() function." }, { "code": null, "e": 6031, "s": 5263, "text": "from sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import classification_reportimport numpy as npmodel = DecisionTreeClassifier(random_state=random_state, max_depth=2)min_samples = 5target_names = [\"class 0\", \"class 1\"]for step in range(min_samples, len(X_train)): model.fit(X_train[0:step], y_train[0:step]) y_pred = model.predict(X_test) pred_proba = np.max(model.predict_proba(X_test), axis=1) report = classification_report(y_test, y_pred, target_names=target_names, output_dict=True) for label, metric in report.items(): try: experiment.log_metrics(metric, prefix=label, step=step)except: experiment.log_metric(label, metric,step=i) experiment.log_confusion_matrix(y_test.tolist(), y_pred.tolist())" }, { "code": null, "e": 6073, "s": 6031, "text": "I show the experiment results in Jupyter." }, { "code": null, "e": 6118, "s": 6073, "text": "experiment.display(tab=\"confusion-matrices\")" }, { "code": null, "e": 6183, "s": 6118, "text": "The following figure shows an excerpt of the produced dashboard:" }, { "code": null, "e": 6210, "s": 6183, "text": "I conclude the experiment." }, { "code": null, "e": 6227, "s": 6210, "text": "experiment.end()" }, { "code": null, "e": 6363, "s": 6227, "text": "Congratulations! You have learned how to configure and run an experiment in Comet ML, an Experimentation Platform for Machine Learning." }, { "code": null, "e": 6449, "s": 6363, "text": "Comet ML can be exploited to run more complex experiments. Stay tuned for more tips 😃" } ]
Python | Remove empty tuples from a list
When it is required to remove empty tuples from a list of tuples, a simple loop can be used. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list. Below is a demonstration for the same − Live Demo def remove_empty(my_tuple): my_tuple = [t for t in my_tuple if t] return my_tuple my_tuple = [(), (), (''), (" " , " "), (45, 67, 35, 66, 74, 89, 100) , 'jane'] print("The tuple is : ") print(my_tuple) print("The method to remove empty tuples is being called...") my_result = remove_empty(my_tuple) print("The list of tuple after remvoing empty tuples is : ") print(my_result) The tuple is : [(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane'] The method to remove empty tuples is being called... The list of tuple after remvoing empty tuples is : [(' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane'] A method named ‘remove_empty’ is defined, that takes a list of tuple as parameter. It iterates through the tuple and returns values only if they are non-empty. A list of tuple is defined, and is displayed on the console. The method is called by passing this list of tuple. This operation’s data is assigned to a variable. It is then displayed as output on the console.
[ { "code": null, "e": 1155, "s": 1062, "text": "When it is required to remove empty tuples from a list of tuples, a simple loop can be used." }, { "code": null, "e": 1282, "s": 1155, "text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)." }, { "code": null, "e": 1344, "s": 1282, "text": "A list of tuple basically contains tuples enclosed in a list." }, { "code": null, "e": 1384, "s": 1344, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1395, "s": 1384, "text": " Live Demo" }, { "code": null, "e": 1778, "s": 1395, "text": "def remove_empty(my_tuple):\n my_tuple = [t for t in my_tuple if t]\n return my_tuple\nmy_tuple = [(), (), (''), (\" \" , \" \"), (45, 67, 35, 66, 74, 89, 100) , 'jane']\nprint(\"The tuple is : \")\nprint(my_tuple)\nprint(\"The method to remove empty tuples is being called...\")\nmy_result = remove_empty(my_tuple)\nprint(\"The list of tuple after remvoing empty tuples is : \")\nprint(my_result)" }, { "code": null, "e": 2013, "s": 1778, "text": "The tuple is :\n[(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']\nThe method to remove empty tuples is being called...\nThe list of tuple after remvoing empty tuples is :\n[(' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']" }, { "code": null, "e": 2096, "s": 2013, "text": "A method named ‘remove_empty’ is defined, that takes a list of tuple as parameter." }, { "code": null, "e": 2173, "s": 2096, "text": "It iterates through the tuple and returns values only if they are non-empty." }, { "code": null, "e": 2234, "s": 2173, "text": "A list of tuple is defined, and is displayed on the console." }, { "code": null, "e": 2286, "s": 2234, "text": "The method is called by passing this list of tuple." }, { "code": null, "e": 2335, "s": 2286, "text": "This operation’s data is assigned to a variable." }, { "code": null, "e": 2382, "s": 2335, "text": "It is then displayed as output on the console." } ]
Univariate Outlier Detection in Python | by Philip Wilkinson | Towards Data Science
Outlier detection can often be an important part of any exploratory data analysis. This is because in the real world, data is often messy and many different things can affect the underlying data. It is thus important to be able to identify different methods to be able to identify these from the underlying data. The first thing to ask, then, is “what is an outlier?” An outlier can be classed as a data point, or several data points, that don’t fit the pattern, data structure, or within the normal bounds to what we would expect for the data that we have. This is a very subjective definition as outliers depend heavily on the context in which you are examining as to whether a data point is an outlier or not. This outlier could be the result of many different issues: Human error Instrument error Experimental error Intentional creation Data processing error Sampling error Natural outlier The purpose for being able to identify this outlier of course can also be different. This could be because an outlier would indicate something has changed in the action that produces the data which is useful in the case of: Fraud detection Intrusion detection Fault diagnostics Time series monitoring Health monitoring Where an outlier would indicate maybe something has gone wrong in the process or the nature of the process generating the data has changed. This would thus entail identifying outliers on the basis of underlying accepted normal data. In other cases it is useful to be able to remove outliers from existing data to ensure a model works. For example: Recommendation engines Time series forecasting Scientific experimentation Model building Where outliers in existing data would affect model implementation such as in linear regression or classification tasks. Thus it would be important to identify outliers from existing data where we are not exactly sure what normal behavior is yet. These two tasks can thus be separated, with the first referring to novelty detection in newly generated data, and the latter referring to anomaly detection in underlying data. It is primarily to this second domain that we turn our attention to although the methods outlined below can also be applied to the first scenario as well. The dataset that I use for this is that of Pokémon through the first seven generations containing a total of 801 Pokémon. Specifically, I will focus on analysing the distribution of the HP attribute from this dataset to be able to detect any potential anomalies. Of course, any anomalies in the dataset detected by these methods may not actually be anomalies, but we can make a choice in light of the results. Distribution plot The first method for this is by examining the distribution of the underlying dataset through a distribution plot. This can be implemented using the following code: #create the displotsns.displot(pokemon["hp"], kde = True)#label the axisplt.xlabel("HP", fontsize = 15)plt.ylabel("Count", fontsize = 15)plt.title("Pokemon HP distribution", fontsize = 15)plt.show() From this we can see that the distribution appears positively skewed with a few points that fall to the extreme right of this distribution. On the basis of the visual inspection we could say that Pokémon that have HP greater than 200 could potentially be outliers in this dataset. This can be extracted from the dataset using: pokemon_above_150_HP = pokemon[pokemon["HP"] > 150]pokemon_above_150_HP Which we can see results in 8 potential outliers, however this is just based on purely visual inspection. Z-score We can see that the distribution of the HP attribute is roughly normal, albeit with some degree of skew. We could thus supplement the visual inspecting by using the Z-score. This is based on the following formula: Where μ is the mean of the data and σ is the standard deviation. The purpose of this is to see how many standard deviations away is the data point from the mean of the dataset. The further away the data point is, as indicated by a higher Z-score, the more likely we could argue that the data point is an outlier. This can be implemented in Python as: #calculate the Z scorepokemon["HP_z"] = (pokemon["hp"] - pokemon["hp"].mean())/pokemon["hp"].std() On this basis, we can use the Z-score to examine data that lies greater than 2, 2.5, 3 or 3.5 standard deviations from the mean. The choice of which Z-score to act as the cutoff will depend on the underlying data, but here choosing a cut-off of 3 extracts the following Pokémon: The main difference here is that this includes those with HP of 150 or greater, rather than just greater than 150. This therefore suggests that the initial visual inspection and choice of cut off was relatively accurate in terms of this dataset. Boxplot Another good method for this is that of the Boxplot. This again is another visualisation method that can be used to identify any outliers from the dataset. This is done on the basis that any value that is less than the lower quartile less 1.5 times the inter quartile range or that is greater than the upper quartile plus 1.5 times the interquartile range can be seen as an outlier. On the plot, this shows as separate points being identified beyond the min and max of the boxplot itself. This can be implemented using the Seaborn library as: #create the boxplotax = sns.boxplot(x = pokemon["HP"])#add labels to the plotax.set_xlabel("HP", fontsize = 15)ax.set_ylabel("Variable", fontsize = 15)ax.set_title("pokemon HP boxplot", fontsize =20, pad = 20)plt.show() In contrast to the distribution plot, this box plot suggests more clearly what data points could be classed as outliers and we can see that this suggests not only are there outliers at the higher end of the distribution but also one at the lower end of the distribution. Tukey fences These points can be extracted using the values of the interquartile range as follows: #extract the upper and lower quantilespokemon_HP_lq = pokemon["HP"].quantile(0.25)pokemon_HP_uq = pokemon["HP"].quantile(0.75)#extract the inter quartile rangepokemon_HP_iqr = pokemon_HP_uq - pokemon_HP_lq#get the upper and lower boundslower_bound = pokemon_HP_lq - 1.5*pokemon_HP_iqrupper_bound = pokemon_HP_uq + 1.5*pokemon_HP_iqr#extract values outside these bounds Pokemon_IQR_outliers = pokemon[(pokemon.HP <= lower_bound) | (pokemon.HP >= upper_bound)]Pokemon_IQR_outliers Which suggests many more outliers than the previous inspection. Indeed, this suggests one Pokémon whose HP falls below the lower bound and twenty-three that fall above the upper bound. An alternative to this, given the high number of potential outliers identified, is to use alternate values to multiply the inter-quartile range by. To get extreme outliers from this instead of multiplying by only 1.5, we could multiply by 3. In doing so we get: Which suggests only six outliers at the upper end of the distribution. Which one you select will depend on the type of outliers you are looking to identify. Clustering The final method to potentially use is that of clustering. The aim of clustering is to be able to identify groups from the dataset, where potential outliers may fit in extreme groups or in a group of their own depending on how different their characteristics are from the underlying dataset. For univariate analysis this may be limited in terms of its ability to identify clearly distinct groups, but visualising the results could potentially identify outliers much clearer than just examining the underling distribution. Using K-Means clustering therefore this can be implemented as: #convert the HP values to a float to be able to use numpy HP_raw = pokemon["hp"].values.astype("float")#use the kmeans function from scipycentroids, avg_distance = kmeans(HP_raw, 4)#extract the groups from the datagroups, cdit = vq(HP_raw, centroids)#plot the results#assign groups back to the dataframepokemon["HP_groups"] = groups#plot the scatter plotfig = px.scatter(pokemon, x = "hp", y = pokemon.index, color = "HP_groups", hover_name = "name")#add a titlefig.update_layout(title = "K-Means outlier detection", title_x = 0.5)#show the plotfig.show() From which we could more potentially identify outliers from both the lower and upper ends of the distribution. The fact that these methods suggest different potential outliers all from the same dataset shows the fact that outlier detection is not an exact science and judgement calls have to be made. An important part of this will also be deciding what needs to be done with these outliers and what they mean in terms of removing them from the dataset, imputing values to cover these outliers or acknowledging their existing but continuing with the analysis as is. This of course will depend on the purpose of identifying the outliers, the underlying dataset and the analysis that will be performed in the future. While practical applications of trying to find outliers from a single variable from a whole dataset may be limited, these methods can be used to supplement multivariate outlier detection algorithms such as Isolation Forest, Local Outlier Factor or Elliptic Envelope where outlier scores can be analysed to decide contamination values. Code available: https://github.com/PhilipDW183/Outlier_detection Dataset available: https://www.kaggle.com/rounakbanik/pokemon?select=pokemon.csv
[ { "code": null, "e": 485, "s": 172, "text": "Outlier detection can often be an important part of any exploratory data analysis. This is because in the real world, data is often messy and many different things can affect the underlying data. It is thus important to be able to identify different methods to be able to identify these from the underlying data." }, { "code": null, "e": 885, "s": 485, "text": "The first thing to ask, then, is “what is an outlier?” An outlier can be classed as a data point, or several data points, that don’t fit the pattern, data structure, or within the normal bounds to what we would expect for the data that we have. This is a very subjective definition as outliers depend heavily on the context in which you are examining as to whether a data point is an outlier or not." }, { "code": null, "e": 944, "s": 885, "text": "This outlier could be the result of many different issues:" }, { "code": null, "e": 956, "s": 944, "text": "Human error" }, { "code": null, "e": 973, "s": 956, "text": "Instrument error" }, { "code": null, "e": 992, "s": 973, "text": "Experimental error" }, { "code": null, "e": 1013, "s": 992, "text": "Intentional creation" }, { "code": null, "e": 1035, "s": 1013, "text": "Data processing error" }, { "code": null, "e": 1050, "s": 1035, "text": "Sampling error" }, { "code": null, "e": 1066, "s": 1050, "text": "Natural outlier" }, { "code": null, "e": 1290, "s": 1066, "text": "The purpose for being able to identify this outlier of course can also be different. This could be because an outlier would indicate something has changed in the action that produces the data which is useful in the case of:" }, { "code": null, "e": 1306, "s": 1290, "text": "Fraud detection" }, { "code": null, "e": 1326, "s": 1306, "text": "Intrusion detection" }, { "code": null, "e": 1344, "s": 1326, "text": "Fault diagnostics" }, { "code": null, "e": 1367, "s": 1344, "text": "Time series monitoring" }, { "code": null, "e": 1385, "s": 1367, "text": "Health monitoring" }, { "code": null, "e": 1618, "s": 1385, "text": "Where an outlier would indicate maybe something has gone wrong in the process or the nature of the process generating the data has changed. This would thus entail identifying outliers on the basis of underlying accepted normal data." }, { "code": null, "e": 1733, "s": 1618, "text": "In other cases it is useful to be able to remove outliers from existing data to ensure a model works. For example:" }, { "code": null, "e": 1756, "s": 1733, "text": "Recommendation engines" }, { "code": null, "e": 1780, "s": 1756, "text": "Time series forecasting" }, { "code": null, "e": 1807, "s": 1780, "text": "Scientific experimentation" }, { "code": null, "e": 1822, "s": 1807, "text": "Model building" }, { "code": null, "e": 2068, "s": 1822, "text": "Where outliers in existing data would affect model implementation such as in linear regression or classification tasks. Thus it would be important to identify outliers from existing data where we are not exactly sure what normal behavior is yet." }, { "code": null, "e": 2399, "s": 2068, "text": "These two tasks can thus be separated, with the first referring to novelty detection in newly generated data, and the latter referring to anomaly detection in underlying data. It is primarily to this second domain that we turn our attention to although the methods outlined below can also be applied to the first scenario as well." }, { "code": null, "e": 2811, "s": 2399, "text": "The dataset that I use for this is that of Pokémon through the first seven generations containing a total of 801 Pokémon. Specifically, I will focus on analysing the distribution of the HP attribute from this dataset to be able to detect any potential anomalies. Of course, any anomalies in the dataset detected by these methods may not actually be anomalies, but we can make a choice in light of the results." }, { "code": null, "e": 2829, "s": 2811, "text": "Distribution plot" }, { "code": null, "e": 2993, "s": 2829, "text": "The first method for this is by examining the distribution of the underlying dataset through a distribution plot. This can be implemented using the following code:" }, { "code": null, "e": 3202, "s": 2993, "text": "#create the displotsns.displot(pokemon[\"hp\"], kde = True)#label the axisplt.xlabel(\"HP\", fontsize = 15)plt.ylabel(\"Count\", fontsize = 15)plt.title(\"Pokemon HP distribution\", fontsize = 15)plt.show()" }, { "code": null, "e": 3530, "s": 3202, "text": "From this we can see that the distribution appears positively skewed with a few points that fall to the extreme right of this distribution. On the basis of the visual inspection we could say that Pokémon that have HP greater than 200 could potentially be outliers in this dataset. This can be extracted from the dataset using:" }, { "code": null, "e": 3602, "s": 3530, "text": "pokemon_above_150_HP = pokemon[pokemon[\"HP\"] > 150]pokemon_above_150_HP" }, { "code": null, "e": 3708, "s": 3602, "text": "Which we can see results in 8 potential outliers, however this is just based on purely visual inspection." }, { "code": null, "e": 3716, "s": 3708, "text": "Z-score" }, { "code": null, "e": 3930, "s": 3716, "text": "We can see that the distribution of the HP attribute is roughly normal, albeit with some degree of skew. We could thus supplement the visual inspecting by using the Z-score. This is based on the following formula:" }, { "code": null, "e": 4281, "s": 3930, "text": "Where μ is the mean of the data and σ is the standard deviation. The purpose of this is to see how many standard deviations away is the data point from the mean of the dataset. The further away the data point is, as indicated by a higher Z-score, the more likely we could argue that the data point is an outlier. This can be implemented in Python as:" }, { "code": null, "e": 4380, "s": 4281, "text": "#calculate the Z scorepokemon[\"HP_z\"] = (pokemon[\"hp\"] - pokemon[\"hp\"].mean())/pokemon[\"hp\"].std()" }, { "code": null, "e": 4660, "s": 4380, "text": "On this basis, we can use the Z-score to examine data that lies greater than 2, 2.5, 3 or 3.5 standard deviations from the mean. The choice of which Z-score to act as the cutoff will depend on the underlying data, but here choosing a cut-off of 3 extracts the following Pokémon:" }, { "code": null, "e": 4906, "s": 4660, "text": "The main difference here is that this includes those with HP of 150 or greater, rather than just greater than 150. This therefore suggests that the initial visual inspection and choice of cut off was relatively accurate in terms of this dataset." }, { "code": null, "e": 4914, "s": 4906, "text": "Boxplot" }, { "code": null, "e": 5457, "s": 4914, "text": "Another good method for this is that of the Boxplot. This again is another visualisation method that can be used to identify any outliers from the dataset. This is done on the basis that any value that is less than the lower quartile less 1.5 times the inter quartile range or that is greater than the upper quartile plus 1.5 times the interquartile range can be seen as an outlier. On the plot, this shows as separate points being identified beyond the min and max of the boxplot itself. This can be implemented using the Seaborn library as:" }, { "code": null, "e": 5677, "s": 5457, "text": "#create the boxplotax = sns.boxplot(x = pokemon[\"HP\"])#add labels to the plotax.set_xlabel(\"HP\", fontsize = 15)ax.set_ylabel(\"Variable\", fontsize = 15)ax.set_title(\"pokemon HP boxplot\", fontsize =20, pad = 20)plt.show()" }, { "code": null, "e": 5948, "s": 5677, "text": "In contrast to the distribution plot, this box plot suggests more clearly what data points could be classed as outliers and we can see that this suggests not only are there outliers at the higher end of the distribution but also one at the lower end of the distribution." }, { "code": null, "e": 5961, "s": 5948, "text": "Tukey fences" }, { "code": null, "e": 6047, "s": 5961, "text": "These points can be extracted using the values of the interquartile range as follows:" }, { "code": null, "e": 6526, "s": 6047, "text": "#extract the upper and lower quantilespokemon_HP_lq = pokemon[\"HP\"].quantile(0.25)pokemon_HP_uq = pokemon[\"HP\"].quantile(0.75)#extract the inter quartile rangepokemon_HP_iqr = pokemon_HP_uq - pokemon_HP_lq#get the upper and lower boundslower_bound = pokemon_HP_lq - 1.5*pokemon_HP_iqrupper_bound = pokemon_HP_uq + 1.5*pokemon_HP_iqr#extract values outside these bounds Pokemon_IQR_outliers = pokemon[(pokemon.HP <= lower_bound) | (pokemon.HP >= upper_bound)]Pokemon_IQR_outliers" }, { "code": null, "e": 6712, "s": 6526, "text": "Which suggests many more outliers than the previous inspection. Indeed, this suggests one Pokémon whose HP falls below the lower bound and twenty-three that fall above the upper bound." }, { "code": null, "e": 6974, "s": 6712, "text": "An alternative to this, given the high number of potential outliers identified, is to use alternate values to multiply the inter-quartile range by. To get extreme outliers from this instead of multiplying by only 1.5, we could multiply by 3. In doing so we get:" }, { "code": null, "e": 7131, "s": 6974, "text": "Which suggests only six outliers at the upper end of the distribution. Which one you select will depend on the type of outliers you are looking to identify." }, { "code": null, "e": 7142, "s": 7131, "text": "Clustering" }, { "code": null, "e": 7727, "s": 7142, "text": "The final method to potentially use is that of clustering. The aim of clustering is to be able to identify groups from the dataset, where potential outliers may fit in extreme groups or in a group of their own depending on how different their characteristics are from the underlying dataset. For univariate analysis this may be limited in terms of its ability to identify clearly distinct groups, but visualising the results could potentially identify outliers much clearer than just examining the underling distribution. Using K-Means clustering therefore this can be implemented as:" }, { "code": null, "e": 8329, "s": 7727, "text": "#convert the HP values to a float to be able to use numpy HP_raw = pokemon[\"hp\"].values.astype(\"float\")#use the kmeans function from scipycentroids, avg_distance = kmeans(HP_raw, 4)#extract the groups from the datagroups, cdit = vq(HP_raw, centroids)#plot the results#assign groups back to the dataframepokemon[\"HP_groups\"] = groups#plot the scatter plotfig = px.scatter(pokemon, x = \"hp\", y = pokemon.index, color = \"HP_groups\", hover_name = \"name\")#add a titlefig.update_layout(title = \"K-Means outlier detection\", title_x = 0.5)#show the plotfig.show()" }, { "code": null, "e": 8440, "s": 8329, "text": "From which we could more potentially identify outliers from both the lower and upper ends of the distribution." }, { "code": null, "e": 8895, "s": 8440, "text": "The fact that these methods suggest different potential outliers all from the same dataset shows the fact that outlier detection is not an exact science and judgement calls have to be made. An important part of this will also be deciding what needs to be done with these outliers and what they mean in terms of removing them from the dataset, imputing values to cover these outliers or acknowledging their existing but continuing with the analysis as is." }, { "code": null, "e": 9379, "s": 8895, "text": "This of course will depend on the purpose of identifying the outliers, the underlying dataset and the analysis that will be performed in the future. While practical applications of trying to find outliers from a single variable from a whole dataset may be limited, these methods can be used to supplement multivariate outlier detection algorithms such as Isolation Forest, Local Outlier Factor or Elliptic Envelope where outlier scores can be analysed to decide contamination values." }, { "code": null, "e": 9444, "s": 9379, "text": "Code available: https://github.com/PhilipDW183/Outlier_detection" } ]
Computer Graphics - Quick Guide
Computer graphics is an art of drawing pictures on computer screens with the help of programming. It involves computations, creation, and manipulation of data. In other words, we can say that computer graphics is a rendering tool for the generation and manipulation of images. The primary output device in a graphical system is the video monitor. The main element of a video monitor is the Cathode Ray Tube CRT, shown in the following illustration. The operation of CRT is very simple − The electron gun emits a beam of electrons cathoderays. The electron gun emits a beam of electrons cathoderays. The electron beam passes through focusing and deflection systems that direct it towards specified positions on the phosphor-coated screen. The electron beam passes through focusing and deflection systems that direct it towards specified positions on the phosphor-coated screen. When the beam hits the screen, the phosphor emits a small spot of light at each position contacted by the electron beam. When the beam hits the screen, the phosphor emits a small spot of light at each position contacted by the electron beam. It redraws the picture by directing the electron beam back over the same screen points quickly. It redraws the picture by directing the electron beam back over the same screen points quickly. There are two ways RandomscanandRasterscan by which we can display an object on the screen. In a raster scan system, the electron beam is swept across the screen, one row at a time from top to bottom. As the electron beam moves across each row, the beam intensity is turned on and off to create a pattern of illuminated spots. Picture definition is stored in memory area called the Refresh Buffer or Frame Buffer. This memory area holds the set of intensity values for all the screen points. Stored intensity values are then retrieved from the refresh buffer and “painted” on the screen one row scanline at a time as shown in the following illustration. Each screen point is referred to as a pixel pictureelement or pel. At the end of each scan line, the electron beam returns to the left side of the screen to begin displaying the next scan line. In this technique, the electron beam is directed only to the part of the screen where the picture is to be drawn rather than scanning from left to right and top to bottom as in raster scan. It is also called vector display, stroke-writing display, or calligraphic display. Picture definition is stored as a set of line-drawing commands in an area of memory referred to as the refresh display file. To display a specified picture, the system cycles through the set of commands in the display file, drawing each component line in turn. After all the line-drawing commands are processed, the system cycles back to the first line command in the list. Random-scan displays are designed to draw all the component lines of a picture 30 to 60 times each second. Computer Graphics has numerous applications, some of which are listed below − Computer graphics user interfaces GUIs − A graphic, mouse-oriented paradigm which allows the user to interact with a computer. Computer graphics user interfaces GUIs − A graphic, mouse-oriented paradigm which allows the user to interact with a computer. Business presentation graphics − "A picture is worth a thousand words". Business presentation graphics − "A picture is worth a thousand words". Cartography − Drawing maps. Cartography − Drawing maps. Weather Maps − Real-time mapping, symbolic representations. Weather Maps − Real-time mapping, symbolic representations. Satellite Imaging − Geodesic images. Satellite Imaging − Geodesic images. Photo Enhancement − Sharpening blurred photos. Photo Enhancement − Sharpening blurred photos. Medical imaging − MRIs, CAT scans, etc. - Non-invasive internal examination. Medical imaging − MRIs, CAT scans, etc. - Non-invasive internal examination. Engineering drawings − mechanical, electrical, civil, etc. - Replacing the blueprints of the past. Engineering drawings − mechanical, electrical, civil, etc. - Replacing the blueprints of the past. Typography − The use of character images in publishing - replacing the hard type of the past. Typography − The use of character images in publishing - replacing the hard type of the past. Architecture − Construction plans, exterior sketches - replacing the blueprints and hand drawings of the past. Architecture − Construction plans, exterior sketches - replacing the blueprints and hand drawings of the past. Art − Computers provide a new medium for artists. Art − Computers provide a new medium for artists. Training − Flight simulators, computer aided instruction, etc. Training − Flight simulators, computer aided instruction, etc. Entertainment − Movies and games. Entertainment − Movies and games. Simulation and modeling − Replacing physical modeling and enactments Simulation and modeling − Replacing physical modeling and enactments A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line. In the following three algorithms, we refer the one point of line as X0,Y0 and the second point of line as X1,Y1. Digital Differential Analyzer DDA algorithm is the simple line generation algorithm which is explained step by step here. Step 1 − Get the input of two end points (X0,Y0) and (X1,Y1). Step 2 − Calculate the difference between two end points. dx = X1 - X0 dy = Y1 - Y0 Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate. if (absolute(dx) > absolute(dy)) Steps = absolute(dx); else Steps = absolute(dy); Step 4 − Calculate the increment in x coordinate and y coordinate. Xincrement = dx / (float) steps; Yincrement = dy / (float) steps; Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the drawing of the line. for(int v=0; v < Steps; v++) { x = x + Xincrement; y = y + Yincrement; putpixel(Round(x), Round(y)); } The Bresenham algorithm is another incremental scan conversion algorithm. The big advantage of this algorithm is that, it uses only integer calculations. Moving across the x axis in unit intervals and at each step choose between two different y coordinates. For example, as shown in the following illustration, from position 2,3 you need to choose between 3,3 and 3,4. You would like the point that is closer to the original line. At sample position Xk+1, the vertical separations from the mathematical line are labelled as dupper and dlower. From the above illustration, the y coordinate on the mathematical line at xk+1 is − Y = m + b So, and are given as follows − and You can use these to make a simple decision about which pixel is closer to the mathematical line. This simple decision is based on the difference between the two pixel positions. Let us substitute m with dy/dx where dx and dy are the differences between the end-points. So, a decision parameter for the kth step along a line is given by − The sign of the decision parameter is the same as that of . If is negative, then choose the lower pixel, otherwise choose the upper pixel. Remember, the coordinate changes occur along the x axis in unit steps, so you can do everything with integer calculations. At step k+1, the decision parameter is given as − Subtracting from this we get − But, is the same as . So − Where, is either 0 or 1 depending on the sign of . The first decision parameter is evaluated at is given as − Now, keeping in mind all the above points and calculations, here is the Bresenham algorithm for slope m < 1 − Step 1 − Input the two end-points of line, storing the left end-point in . Step 2 − Plot the point . Step 3 − Calculate the constants dx, dy, 2dy, and and get the first value for the decision parameter as − Step 4 − At each along the line, starting at k = 0, perform the following test − If < 0, the next point to plot is and Otherwise, Step 5 − Repeat step 4 times. For m > 1, find out whether you need to increment x while incrementing y each time. After solving, the equation for decision parameter will be very similar, just the x and y in the equation gets interchanged. Mid-point algorithm is due to Bresenham which was modified by Pitteway and Van Aken. Assume that you have already put the point P at coordinate and the slope of the line is 0 ≤ k ≤ 1 as shown in the following illustration. Now you need to decide whether to put the next point at E or N. This can be chosen by identifying the intersection point Q closest to the point N or E. If the intersection point Q is closest to the point N then N is considered as the next point; otherwise E. To determine that, first calculate the mid-point M1⁄2. If the intersection point Q of the line with the vertical line connecting E and N is below M, then take E as the next point; otherwise take N as the next point. In order to check this, we need to consider the implicit equation − F = mx + b - y For positive m at any given X, If y is on the line, then F = 0 If y is above the line, then F < 0 If y is below the line, then F > 0 Drawing a circle on the screen is a little complex than drawing a line. There are two popular algorithms for generating a circle − Bresenham’s Algorithm and Midpoint Circle Algorithm. These algorithms are based on the idea of determining the subsequent points required to draw the circle. Let us discuss the algorithms in detail − The equation of circle is where r is radius. We cannot display a continuous arc on the raster display. Instead, we have to choose the nearest pixel position to complete the arc. From the following illustration, you can see that we have put the pixel at location and now need to decide where to put the next pixel − at N or at S . This can be decided by the decision parameter d. If d <= 0, then N is to be chosen as next pixel. If d > 0, then S is to be chosen as the next pixel. Step 1 − Get the coordinates of the center of the circle and radius, and store them in x, y, and R respectively. Set P=0 and Q=R. Step 2 − Set decision parameter D = 3 – 2R. Step 3 − Repeat through step-8 while P ≤ Q. Step 4 − Call Draw Circle . Step 5 − Increment the value of P. Step 6 − If D < 0 then D = D + 4P + 6. Step 7 − Else Set R = R - 1, D = D + 4 + 10. Step 8 − Call Draw Circle . Draw Circle Method(X, Y, P, Q). Call Putpixel (X + P, Y + Q). Call Putpixel (X - P, Y + Q). Call Putpixel (X + P, Y - Q). Call Putpixel (X - P, Y - Q). Call Putpixel (X + Q, Y + P). Call Putpixel (X - Q, Y + P). Call Putpixel (X + Q, Y - P). Call Putpixel (X - Q, Y - P). Step 1 − Input radius r and circle center and obtain the first point on the circumference of the circle centered on the origin as (x0, y0) = (0, r) Step 2 − Calculate the initial value of decision parameter as = 5/4 – r f(x, y) = x2 + y2 - r2 = 0 f(xi - 1/2 + e, yi + 1) = (xi - 1/2 + e)2 + (yi + 1)2 - r2 = (xi- 1/2)2 + (yi + 1)2 - r2 + 2(xi - 1/2)e + e2 = f(xi - 1/2, yi + 1) + 2(xi - 1/2)e + e2 = 0 Let di = f(xi - 1/2, yi + 1) = -2(xi - 1/2)e - e2 Thus, If e < 0 then di > 0 so choose point S = (xi - 1, yi + 1). di+1 = f(xi - 1 - 1/2, yi + 1 + 1) = ((xi - 1/2) - 1)2 + ((yi + 1) + 1)2 - r2 = di - 2(xi - 1) + 2(yi + 1) + 1 = di + 2(yi + 1 - xi + 1) + 1 If e >= 0 then di <= 0 so choose point T = (xi, yi + 1) di+1 = f(xi - 1/2, yi + 1 + 1) = di + 2yi+1 + 1 The initial value of di is d0 = f(r - 1/2, 0 + 1) = (r - 1/2)2 + 12 - r2 = 5/4 - r {1-r can be used if r is an integer} When point S = (xi - 1, yi + 1) is chosen then di+1 = di + -2xi+1 + 2yi+1 + 1 When point T = (xi, yi + 1) is chosen then di+1 = di + 2yi+1 + 1 Step 3 − At each position starting at K=0, perform the following test − If PK < 0 then next point on circle (0,0) is (XK+1,YK) and PK+1 = PK + 2XK+1 + 1 Else PK+1 = PK + 2XK+1 + 1 – 2YK+1 Where, 2XK+1 = 2XK+2 and 2YK+1 = 2YK-2. Step 4 − Determine the symmetry points in other seven octants. Step 5 − Move each calculate pixel position onto the circular path centered on and plot the coordinate values. X = X + XC, Y = Y + YC Step 6 − Repeat step-3 through 5 until X >= Y. Polygon is an ordered list of vertices as shown in the following figure. For filling polygons with particular colors, you need to determine the pixels falling on the border of the polygon and those which fall inside the polygon. In this chapter, we will see how we can fill polygons using different techniques. This algorithm works by intersecting scanline with polygon edges and fills the polygon between pairs of intersections. The following steps depict how this algorithm works. Step 1 − Find out the Ymin and Ymax from the given polygon. Step 2 − ScanLine intersects with each edge of the polygon from Ymin to Ymax. Name each intersection point of the polygon. As per the figure shown above, they are named as p0, p1, p2, p3. Step 3 − Sort the intersection point in the increasing order of X coordinate i.e. , , and . Step 4 − Fill all those pair of coordinates that are inside polygons and ignore the alternate pairs. Sometimes we come across an object where we want to fill the area and its boundary with different colors. We can paint such objects with a specified interior color instead of searching for particular boundary color as in boundary filling algorithm. Instead of relying on the boundary of the object, it relies on the fill color. In other words, it replaces the interior color of the object with the fill color. When no more pixels of the original interior color exist, the algorithm is completed. Once again, this algorithm relies on the Four-connect or Eight-connect method of filling in the pixels. But instead of looking for the boundary color, it is looking for all adjacent pixels that are a part of the interior. The boundary fill algorithm works as its name. This algorithm picks a point inside an object and starts to fill until it hits the boundary of the object. The color of the boundary and the color that we fill should be different for this algorithm to work. In this algorithm, we assume that color of the boundary is same for the entire object. The boundary fill algorithm can be implemented by 4-connected pixels or 8-connected pixels. In this technique 4-connected pixels are used as shown in the figure. We are putting the pixels above, below, to the right, and to the left side of the current pixels and this process will continue until we find a boundary with different color. Step 1 − Initialize the value of seed point , fcolor and dcol. Step 2 − Define the boundary values of the polygon. Step 3 − Check if the current seed point is of default color, then repeat the steps 4 and 5 till the boundary pixels reached. If getpixel(x, y) = dcol then repeat step 4 and 5 Step 4 − Change the default color with the fill color at the seed point. setPixel(seedx, seedy, fcol) Step 5 − Recursively follow the procedure with four neighborhood points. FloodFill (seedx – 1, seedy, fcol, dcol) FloodFill (seedx + 1, seedy, fcol, dcol) FloodFill (seedx, seedy - 1, fcol, dcol) FloodFill (seedx – 1, seedy + 1, fcol, dcol) Step 6 − Exit There is a problem with this technique. Consider the case as shown below where we tried to fill the entire region. Here, the image is filled only partially. In such cases, 4-connected pixels technique cannot be used. In this technique 8-connected pixels are used as shown in the figure. We are putting pixels above, below, right and left side of the current pixels as we were doing in 4-connected technique. In addition to this, we are also putting pixels in diagonals so that entire area of the current pixel is covered. This process will continue until we find a boundary with different color. Step 1 − Initialize the value of seed point , fcolor and dcol. Step 2 − Define the boundary values of the polygon. Step 3 − Check if the current seed point is of default color then repeat the steps 4 and 5 till the boundary pixels reached If getpixel(x,y) = dcol then repeat step 4 and 5 Step 4 − Change the default color with the fill color at the seed point. setPixel(seedx, seedy, fcol) Step 5 − Recursively follow the procedure with four neighbourhood points FloodFill (seedx – 1, seedy, fcol, dcol) FloodFill (seedx + 1, seedy, fcol, dcol) FloodFill (seedx, seedy - 1, fcol, dcol) FloodFill (seedx, seedy + 1, fcol, dcol) FloodFill (seedx – 1, seedy + 1, fcol, dcol) FloodFill (seedx + 1, seedy + 1, fcol, dcol) FloodFill (seedx + 1, seedy - 1, fcol, dcol) FloodFill (seedx – 1, seedy - 1, fcol, dcol) Step 6 − Exit The 4-connected pixel technique failed to fill the area as marked in the following figure which won’t happen with the 8-connected technique. This method is also known as counting number method. While filling an object, we often need to identify whether particular point is inside the object or outside it. There are two methods by which we can identify whether particular point is inside an object or outside. Odd-Even Rule Nonzero winding number rule In this technique, we count the edge crossing along the line from any point to infinity. If the number of interactions is odd then the point is an interior point. If the number of interactions is even then point is an exterior point. Here is the example to give you the clear idea − From the above figure, we can see that from the point , the number of interactions point on the left side is 5 and on the right side is 3. So the total number of interaction point is 8, which is odd. Hence, the point is considered within the object. This method is also used with the simple polygons to test the given point is interior or not. It can be simply understood with the help of a pin and a rubber band. Fix up the pin on one of the edge of the polygon and tie-up the rubber band in it and then stretch the rubber band along the edges of the polygon. When all the edges of the polygon are covered by the rubber band, check out the pin which has been fixed up at the point to be test. If we find at least one wind at the point consider it within the polygon, else we can say that the point is not inside the polygon. In another alternative method, give directions to all the edges of the polygon. Draw a scan line from the point to be test towards the left most of X direction. Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values. Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values. Check the edge direction values from which the scan line is passing and sum up them. Check the edge direction values from which the scan line is passing and sum up them. If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point. If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point. In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point. In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point. The primary use of clipping in computer graphics is to remove objects, lines, or line segments that are outside the viewing pane. The viewing transformation is insensitive to the position of points relative to the viewing volume − especially those points behind the viewer − and it is necessary to remove these points before generating the view. Clipping a point from a given window is very easy. Consider the following figure, where the rectangle indicates the window. Point clipping tells us whether the given point is within the given window or not; and decides whether we will use the minimum and maximum coordinates of the window. The X-coordinate of the given point is inside the window, if X lies in between Wx1 ≤ X ≤ Wx2. Same way, Y coordinate of the given point is inside the window, if Y lies in between Wy1 ≤ Y ≤ Wy2. The concept of line clipping is same as point clipping. In line clipping, we will cut the portion of line which is outside of window and keep only the portion that is inside the window. This algorithm uses the clipping window as shown in the following figure. The minimum coordinate for the clipping region is and the maximum coordinate for the clipping region is . We will use 4-bits to divide the entire region. These 4 bits represent the Top, Bottom, Right, and Left of the region as shown in the following figure. Here, the TOP and LEFT bit is set to 1 because it is the TOP-LEFT corner. There are 3 possibilities for the line − Line can be completely inside the window . Line can be completely inside the window . Line can be completely outside of the window . Line can be completely outside of the window . Line can be partially inside the window . Line can be partially inside the window . Step 1 − Assign a region code for each endpoints. Step 2 − If both endpoints have a region code 0000 then accept this line. Step 3 − Else, perform the logical ANDoperation for both region codes. Step 3.1 − If the result is not 0000, then reject the line. Step 3.2 − Else you need clipping. Step 3.2.1 − Choose an endpoint of the line that is outside the window. Step 3.2.2 − Find the intersection point at the window boundary . Step 3.2.3 − Replace endpoint with the intersection point and update the region code. Step 3.2.4 − Repeat step 2 until we find a clipped line either trivially accepted or trivially rejected. Step 4 − Repeat step 1 for other lines. This algorithm is more efficient than Cohen-Sutherland algorithm. It employs parametric line representation and simple dot products. Parametric equation of line is − P0P1:P(t) = P0 + t(P1-P0) Let Ni be the outward normal edge Ei. Now pick any arbitrary point PEi on edge Ei then the dot product Ni∙[P – PEi] determines whether the point P is “inside the clip edge” or “outside” the clip edge or “on” the clip edge. The point P is inside if Ni.[P – PEi] < 0 The point P is outside if Ni.[P – PEi] > 0 The point P is on the edge if Ni.[P – PEi] = 0 Ni.[P – PEi] = 0 Ni.[ P0 + t(P1-P0) – PEi] = 0 with P0 + t(P1-P0)) Ni.[P0 – PEi] + Ni.t[P1-P0] = 0 Ni.[P0 – PEi] + Ni∙tD = 0 (substituting D for [P1-P0]) Ni.[P0 – PEi] = - Ni∙tD The equation for t becomes, It is valid for the following conditions − Ni ≠ 0 D ≠ 0 (P1 ≠ P0) Ni∙D ≠ 0 (P0P1 not parallel to Ei) A polygon can also be clipped by specifying the clipping window. Sutherland Hodgeman polygon clipping algorithm is used for polygon clipping. In this algorithm, all the vertices of the polygon are clipped against each edge of the clipping window. First the polygon is clipped against the left edge of the polygon window to get new vertices of the polygon. These new vertices are used to clip the polygon against right edge, top edge, bottom edge, of the clipping window as shown in the following figure. While processing an edge of a polygon with clipping window, an intersection point is found if edge is not completely inside clipping window and the a partial edge from the intersection point to the outside edge is clipped. The following figures show left, right, top and bottom edge clippings − Various techniques are used to provide text clipping in a computer graphics. It depends on the methods used to generate characters and the requirements of a particular application. There are three methods for text clipping which are listed below − All or none string clipping All or none character clipping Text clipping The following figure shows all or none string clipping − In all or none string clipping method, either we keep the entire string or we reject entire string based on the clipping window. As shown in the above figure, STRING2 is entirely inside the clipping window so we keep it and STRING1 being only partially inside the window, we reject. The following figure shows all or none character clipping − This clipping method is based on characters rather than entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then − You reject only the portion of the string being outside You reject only the portion of the string being outside If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string. If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string. The following figure shows text clipping − This clipping method is based on characters rather than the entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then You reject only the portion of string being outside. You reject only the portion of string being outside. If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window. If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window. A bitmap is a collection of pixels that describes an image. It is a type of computer graphics that the computer uses to store and display pictures. In this type of graphics, images are stored bit by bit and hence it is named Bit-map graphics. For better understanding let us consider the following example where we draw a smiley face using bit-map graphics. Now we will see how this smiley face is stored bit by bit in computer graphics. By observing the original smiley face closely, we can see that there are two blue lines which are represented as B1, B2 and E1, E2 in the above figure. In the same way, the smiley is represented using the combination bits of A4, B5, C6, D6, E5, and F4 respectively. The main disadvantages of bitmap graphics are − We cannot resize the bitmap image. If you try to resize, the pixels get blurred. We cannot resize the bitmap image. If you try to resize, the pixels get blurred. Colored bitmaps can be very large. Colored bitmaps can be very large. Transformation means changing some graphics into something else by applying rules. We can have various types of transformations such as translation, scaling up or down, rotation, shearing, etc. When a transformation takes place on a 2D plane, it is called 2D transformation. Transformations play an important role in computer graphics to reposition the graphics on the screen and change their size or orientation. To perform a sequence of transformation such as translation followed by rotation and scaling, we need to follow a sequential process − Translate the coordinates, Rotate the translated coordinates, and then Scale the rotated coordinates to complete the composite transformation. To shorten this process, we have to use 3×3 transformation matrix instead of 2×2 transformation matrix. To convert a 2×2 matrix to 3×3 matrix, we have to add an extra dummy coordinate W. In this way, we can represent the point by 3 numbers instead of 2 numbers, which is called Homogenous Coordinate system. In this system, we can represent all the transformation equations in matrix multiplication. Any Cartesian point P can be converted to homogenous coordinates by P’ (Xh, Yh, h). A translation moves an object to a different position on the screen. You can translate a point in 2D by adding translation coordinate (tx, ty) to the original coordinate to get the new coordinate . From the above figure, you can write that − X’ = X + tx Y’ = Y + ty The pair (tx, ty) is called the translation vector or shift vector. The above equations can also be represented using the column vectors. p' = T = We can write it as − P’ = P + T In rotation, we rotate the object at particular angle θ from its origin. From the following figure, we can see that the point P is located at angle φ from the horizontal X coordinate with distance r from the origin. Let us suppose you want to rotate it at the angle θ. After rotating it to a new location, you will get a new point P’ . Using standard trigonometric the original coordinate of point P can be represented as − Same way we can represent the point P’ as − Substituting equation & in & respectively, we will get Representing the above equation in matrix form, P’ = P ∙ R Where R is the rotation matrix The rotation angle can be positive and negative. For positive rotation angle, we can use the above rotation matrix. However, for negative angle rotation, the matrix will change as shown below − To change the size of an object, scaling transformation is used. In the scaling process, you either expand or compress the dimensions of the object. Scaling can be achieved by multiplying the original coordinates of the object with the scaling factor to get the desired result. Let us assume that the original coordinates are , the scaling factors are (SX, SY), and the produced coordinates are . This can be mathematically represented as shown below − X' = X . SX and Y' = Y . SY The scaling factor SX, SY scales the object in X and Y direction respectively. The above equations can also be represented in matrix form as below − OR P’ = P . S Where S is the scaling matrix. The scaling process is shown in the following figure. If we provide values less than 1 to the scaling factor S, then we can reduce the size of the object. If we provide values greater than 1, then we can increase the size of the object. Reflection is the mirror image of original object. In other words, we can say that it is a rotation operation with 180°. In reflection transformation, the size of the object does not change. The following figures show reflections with respect to X and Y axes, and about the origin respectively. A transformation that slants the shape of an object is called the shear transformation. There are two shear transformations X-Shear and Y-Shear. One shifts X coordinates values and other shifts Y coordinate values. However; in both the cases only one coordinate changes its coordinates and other preserves its values. Shearing is also termed as Skewing. The X-Shear preserves the Y coordinate and changes are made to X coordinates, which causes the vertical lines to tilt right or left as shown in below figure. The transformation matrix for X-Shear can be represented as − Y' = Y + Shy . X X’ = X The Y-Shear preserves the X coordinates and changes the Y coordinates which causes the horizontal lines to transform into lines which slopes up or down as shown in the following figure. The Y-Shear can be represented in matrix from as − X’ = X + Shx . Y Y’ = Y If a transformation of the plane T1 is followed by a second plane transformation T2, then the result itself may be represented by a single transformation T which is the composition of T1 and T2 taken in that order. This is written as T = T1∙T2. Composite transformation can be achieved by concatenation of transformation matrices to obtain a combined transformation matrix. A combined matrix − [T][X] = [X] [T1] [T2] [T3] [T4] .... [Tn] Where [Ti] is any combination of Translation Scaling Shearing Rotation Reflection The change in the order of transformation would lead to different results, as in general matrix multiplication is not cumulative, that is [A] . [B] ≠ [B] . [A] and the order of multiplication. The basic purpose of composing transformations is to gain efficiency by applying a single composed transformation to a point, rather than applying a series of transformation, one after another. For example, to rotate an object about an arbitrary point (Xp, Yp), we have to carry out three steps − Translate point (Xp, Yp) to the origin. Rotate it about the origin. Finally, translate the center of rotation back where it belonged. In the 2D system, we use only two coordinates X and Y but in 3D, an extra coordinate Z is added. 3D graphics techniques and their application are fundamental to the entertainment, games, and computer-aided design industries. It is a continuing area of research in scientific visualization. Furthermore, 3D graphics components are now a part of almost every personal computer and, although traditionally intended for graphics-intensive software such as games, they are increasingly being used by other applications. Parallel projection discards z-coordinate and parallel lines from each vertex on the object are extended until they intersect the view plane. In parallel projection, we specify a direction of projection instead of center of projection. In parallel projection, the distance from the center of projection to project plane is infinite. In this type of projection, we connect the projected vertices by line segments which correspond to connections on the original object. Parallel projections are less realistic, but they are good for exact measurements. In this type of projections, parallel lines remain parallel and angles are not preserved. Various types of parallel projections are shown in the following hierarchy. In orthographic projection the direction of projection is normal to the projection of the plane. There are three types of orthographic projections − Front Projection Top Projection Side Projection In oblique projection, the direction of projection is not normal to the projection of plane. In oblique projection, we can view the object better than orthographic projection. There are two types of oblique projections − Cavalier and Cabinet. The Cavalier projection makes 45° angle with the projection plane. The projection of a line perpendicular to the view plane has the same length as the line itself in Cavalier projection. In a cavalier projection, the foreshortening factors for all three principal directions are equal. The Cabinet projection makes 63.4° angle with the projection plane. In Cabinet projection, lines perpendicular to the viewing surface are projected at 1⁄2 their actual length. Both the projections are shown in the following figure − Orthographic projections that show more than one side of an object are called axonometric orthographic projections. The most common axonometric projection is an isometric projection where the projection plane intersects each coordinate axis in the model coordinate system at an equal distance. In this projection parallelism of lines are preserved but angles are not preserved. The following figure shows isometric projection − In perspective projection, the distance from the center of projection to project plane is finite and the size of the object varies inversely with distance which looks more realistic. The distance and angles are not preserved and parallel lines do not remain parallel. Instead, they all converge at a single point called center of projection or projection reference point. There are 3 types of perspective projections which are shown in the following chart. One point perspective projection is simple to draw. One point perspective projection is simple to draw. Two point perspective projection gives better impression of depth. Two point perspective projection gives better impression of depth. Three point perspective projection is most difficult to draw. Three point perspective projection is most difficult to draw. The following figure shows all the three types of perspective projection − In 3D translation, we transfer the Z coordinate along with the X and Y coordinates. The process for translation in 3D is similar to 2D translation. A translation moves an object into a different position on the screen. The following figure shows the effect of translation − A point can be translated in 3D by adding translation coordinate to the original coordinate to get the new coordinate . P’ = P∙T 3D rotation is not same as 2D rotation. In 3D rotation, we have to specify the angle of rotation along with the axis of rotation. We can perform 3D rotation about X, Y, and Z axes. They are represented in the matrix form as below − The following figure explains the rotation about various axes − You can change the size of an object using scaling transformation. In the scaling process, you either expand or compress the dimensions of the object. Scaling can be achieved by multiplying the original coordinates of the object with the scaling factor to get the desired result. The following figure shows the effect of 3D scaling − In 3D scaling operation, three coordinates are used. Let us assume that the original coordinates are , scaling factors are respectively, and the produced coordinates are . This can be mathematically represented as shown below − P’ = P∙S A transformation that slants the shape of an object is called the shear transformation. Like in 2D shear, we can shear an object along the X-axis, Y-axis, or Z-axis in 3D. As shown in the above figure, there is a coordinate P. You can shear it to get a new coordinate P', which can be represented in 3D matrix form as below − P’ = P ∙ Sh Transformation matrix is a basic tool for transformation. A matrix with n x m dimensions is multiplied with the coordinate of objects. Usually 3 x 3 or 4 x 4 matrices are used for transformation. For example, consider the following matrix for various operation. In computer graphics, we often need to draw different types of objects onto the screen. Objects are not flat all the time and we need to draw curves many times to draw an object. A curve is an infinitely large set of points. Each point has two neighbors except endpoints. Curves can be broadly classified into three categories − explicit, implicit, and parametric curves. Implicit curve representations define the set of points on a curve by employing a procedure that can test to see if a point in on the curve. Usually, an implicit curve is defined by an implicit function of the form − f = 0 It can represent multivalued curves . A common example is the circle, whose implicit representation is x2 + y2 - R2 = 0 A mathematical function y = f can be plotted as a curve. Such a function is the explicit representation of the curve. The explicit representation is not general, since it cannot represent vertical lines and is also single-valued. For each value of x, only a single value of y is normally computed by the function. Curves having parametric form are called parametric curves. The explicit and implicit curve representations can be used only when the function is known. In practice the parametric curves are used. A two-dimensional parametric curve has the following form − P = f, g or P = x, y The functions f and g become the coordinates of any point on the curve, and the points are obtained when the parameter t is varied over a certain interval [a, b], normally [0, 1]. Bezier curve is discovered by the French engineer Pierre Bézier. These curves can be generated under the control of other points. Approximate tangents by using control points are used to generate curve. The Bezier curve can be represented mathematically as − Where is the set of points and represents the Bernstein polynomials which are given by − Where n is the polynomial degree, i is the index, and t is the variable. The simplest Bézier curve is the straight line from the point to . A quadratic Bezier curve is determined by three control points. A cubic Bezier curve is determined by four control points. Bezier curves have the following properties − They generally follow the shape of the control polygon, which consists of the segments joining the control points. They generally follow the shape of the control polygon, which consists of the segments joining the control points. They always pass through the first and last control points. They always pass through the first and last control points. They are contained in the convex hull of their defining control points. They are contained in the convex hull of their defining control points. The degree of the polynomial defining the curve segment is one less that the number of defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3, i.e. cubic polynomial. The degree of the polynomial defining the curve segment is one less that the number of defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3, i.e. cubic polynomial. A Bezier curve generally follows the shape of the defining polygon. A Bezier curve generally follows the shape of the defining polygon. The direction of the tangent vector at the end points is same as that of the vector determined by first and last segments. The direction of the tangent vector at the end points is same as that of the vector determined by first and last segments. The convex hull property for a Bezier curve ensures that the polynomial smoothly follows the control points. The convex hull property for a Bezier curve ensures that the polynomial smoothly follows the control points. No straight line intersects a Bezier curve more times than it intersects its control polygon. No straight line intersects a Bezier curve more times than it intersects its control polygon. They are invariant under an affine transformation. They are invariant under an affine transformation. Bezier curves exhibit global control means moving a control point alters the shape of the whole curve. Bezier curves exhibit global control means moving a control point alters the shape of the whole curve. A given Bezier curve can be subdivided at a point t=t0 into two Bezier segments which join together at the point corresponding to the parameter value t=t0. A given Bezier curve can be subdivided at a point t=t0 into two Bezier segments which join together at the point corresponding to the parameter value t=t0. The Bezier-curve produced by the Bernstein basis function has limited flexibility. First, the number of specified polygon vertices fixes the order of the resulting polynomial which defines the curve. First, the number of specified polygon vertices fixes the order of the resulting polynomial which defines the curve. The second limiting characteristic is that the value of the blending function is nonzero for all parameter values over the entire curve. The second limiting characteristic is that the value of the blending function is nonzero for all parameter values over the entire curve. The B-spline basis contains the Bernstein basis as the special case. The B-spline basis is non-global. A B-spline curve is defined as a linear combination of control points Pi and B-spline basis function k given by Where, {: i=0, 1, 2....n} are the control points {: i=0, 1, 2....n} are the control points k is the order of the polynomial segments of the B-spline curve. Order k means that the curve is made up of piecewise polynomial segments of degree k - 1, k is the order of the polynomial segments of the B-spline curve. Order k means that the curve is made up of piecewise polynomial segments of degree k - 1, the are the “normalized B-spline blending functions”. They are described by the order k and by a non-decreasing sequence of real numbers normally called the “knot sequence”. the are the “normalized B-spline blending functions”. They are described by the order k and by a non-decreasing sequence of real numbers normally called the “knot sequence”. The Ni, k functions are described as follows − and if k > 1, and B-spline curves have the following properties − The sum of the B-spline basis functions for any parameter value is 1. The sum of the B-spline basis functions for any parameter value is 1. Each basis function is positive or zero for all parameter values. Each basis function is positive or zero for all parameter values. Each basis function has precisely one maximum value, except for k=1. Each basis function has precisely one maximum value, except for k=1. The maximum order of the curve is equal to the number of vertices of defining polygon. The maximum order of the curve is equal to the number of vertices of defining polygon. The degree of B-spline polynomial is independent on the number of vertices of defining polygon. The degree of B-spline polynomial is independent on the number of vertices of defining polygon. B-spline allows the local control over the curve surface because each vertex affects the shape of a curve only over a range of parameter values where its associated basis function is nonzero. B-spline allows the local control over the curve surface because each vertex affects the shape of a curve only over a range of parameter values where its associated basis function is nonzero. The curve exhibits the variation diminishing property. The curve exhibits the variation diminishing property. The curve generally follows the shape of defining polygon. The curve generally follows the shape of defining polygon. Any affine transformation can be applied to the curve by applying it to the vertices of defining polygon. Any affine transformation can be applied to the curve by applying it to the vertices of defining polygon. The curve line within the convex hull of its defining polygon. The curve line within the convex hull of its defining polygon. Objects are represented as a collection of surfaces. 3D object representation is divided into two categories. Boundary Representations − It describes a 3D object as a set of surfaces that separates the object interior from the environment. Boundary Representations − It describes a 3D object as a set of surfaces that separates the object interior from the environment. Space–partitioning representations − It is used to describe interior properties, by partitioning the spatial region containing an object into a set of small, non-overlapping, contiguous solids . Space–partitioning representations − It is used to describe interior properties, by partitioning the spatial region containing an object into a set of small, non-overlapping, contiguous solids . The most commonly used boundary representation for a 3D graphics object is a set of surface polygons that enclose the object interior. Many graphics system use this method. Set of polygons are stored for object description. This simplifies and speeds up the surface rendering and display of object since all surfaces can be described with linear equations. The polygon surfaces are common in design and solid-modeling applications, since their wireframe display can be done quickly to give general indication of surface structure. Then realistic scenes are produced by interpolating shading patterns across polygon surface to illuminate. In this method, the surface is specified by the set of vertex coordinates and associated attributes. As shown in the following figure, there are five vertices, from v1 to v5. Each vertex stores x, y, and z coordinate information which is represented in the table as v1: x1, y1, z1. Each vertex stores x, y, and z coordinate information which is represented in the table as v1: x1, y1, z1. The Edge table is used to store the edge information of polygon. In the following figure, edge E1 lies between vertex v1 and v2 which is represented in the table as E1: v1, v2. The Edge table is used to store the edge information of polygon. In the following figure, edge E1 lies between vertex v1 and v2 which is represented in the table as E1: v1, v2. Polygon surface table stores the number of surfaces present in the polygon. From the following figure, surface S1 is covered by edges E1, E2 and E3 which can be represented in the polygon surface table as S1: E1, E2, and E3. Polygon surface table stores the number of surfaces present in the polygon. From the following figure, surface S1 is covered by edges E1, E2 and E3 which can be represented in the polygon surface table as S1: E1, E2, and E3. The equation for plane surface can be expressed as − Ax + By + Cz + D = 0 Where is any point on the plane, and the coefficients A, B, C, and D are constants describing the spatial properties of the plane. We can obtain the values of A, B, C, and D by solving a set of three plane equations using the coordinate values for three non collinear points in the plane. Let us assume that three vertices of the plane are (x1, y1, z1), (x2, y2, z2) and (x3, y3, z3). Let us solve the following simultaneous equations for ratios A/D, B/D, and C/D. You get the values of A, B, C, and D. x1 + y1 + z1 = -1 x2 + y2 + z2 = -1 x3 + y3 + z3 = -1 To obtain the above equations in determinant form, apply Cramer’s rule to the above equations. For any point with parameters A, B, C, and D, we can say that − Ax + By + Cz + D ≠ 0 means the point is not on the plane. Ax + By + Cz + D ≠ 0 means the point is not on the plane. Ax + By + Cz + D < 0 means the point is inside the surface. Ax + By + Cz + D < 0 means the point is inside the surface. Ax + By + Cz + D > 0 means the point is outside the surface. Ax + By + Cz + D > 0 means the point is outside the surface. 3D surfaces and solids can be approximated by a set of polygonal and line elements. Such surfaces are called polygonal meshes. In polygon mesh, each edge is shared by at most two polygons. The set of polygons or faces, together form the “skin” of the object. This method can be used to represent a broad class of solids/surfaces in graphics. A polygonal mesh can be rendered using hidden surface removal algorithms. The polygon mesh can be represented by three ways − Explicit representation Pointers to a vertex list Pointers to an edge list It can be used to model almost any object. They are easy to represent as a collection of vertices. They are easy to transform. They are easy to draw on computer screen. Curved surfaces can only be approximately described. It is difficult to simulate some type of objects like hair or liquid. When we view a picture containing non-transparent objects and surfaces, then we cannot see those objects from view which are behind from objects closer to eye. We must remove these hidden surfaces to get a realistic screen image. The identification and removal of these surfaces is called Hidden-surface problem. There are two approaches for removing hidden surface problems − Object-Space method and Image-space method. The Object-space method is implemented in physical coordinate system and image-space method is implemented in screen coordinate system. When we want to display a 3D object on a 2D screen, we need to identify those parts of a screen that are visible from a chosen viewing position. This method is developed by Cutmull. It is an image-space approach. The basic idea is to test the Z-depth of each surface to determine the closest surface. In this method each surface is processed separately one pixel position at a time across the surface. The depth values for a pixel are compared and the closest surface determines the color to be displayed in the frame buffer. It is applied very efficiently on surfaces of polygon. Surfaces can be processed in any order. To override the closer polygons from the far ones, two buffers named frame buffer and depth buffer, are used. Depth buffer is used to store depth values for position, as surfaces are processed . The frame buffer is used to store the intensity value of color value at each position . The z-coordinates are usually normalized to the range [0, 1]. The 0 value for z-coordinate indicates back clipping pane and 1 value for z-coordinates indicates front clipping pane. Step-1 − Set the buffer values − Depthbuffer = 0 Framebuffer = background color Step-2 − Process each polygon For each projected pixel position of a polygon, calculate depth z. If Z > depthbuffer Compute surface color, set depthbuffer = z, framebuffer = surfacecolor It is easy to implement. It reduces the speed problem if implemented in hardware. It processes one object at a time. It requires large memory. It is time consuming process. It is an image-space method to identify visible surface. This method has a depth information for only single scan-line. In order to require one scan-line of depth values, we must group and process all polygons intersecting a given scan-line at the same time before processing the next scan-line. Two important tables, edge table and polygon table, are maintained for this. The Edge Table − It contains coordinate endpoints of each line in the scene, the inverse slope of each line, and pointers into the polygon table to connect edges to surfaces. The Polygon Table − It contains the plane coefficients, surface material properties, other surface data, and may be pointers to the edge table. To facilitate the search for surfaces crossing a given scan-line, an active list of edges is formed. The active list stores only those edges that cross the scan-line in order of increasing x. Also a flag is set for each surface to indicate whether a position along a scan-line is either inside or outside the surface. Pixel positions across each scan-line are processed from left to right. At the left intersection with a surface, the surface flag is turned on and at the right, the flag is turned off. You only need to perform depth calculations when multiple surfaces have their flags turned on at a certain scan-line position. The area-subdivision method takes advantage by locating those view areas that represent part of a single surface. Divide the total viewing area into smaller and smaller rectangles until each small area is the projection of part of a single visible surface or no surface at all. Continue this process until the subdivisions are easily analyzed as belonging to a single surface or until they are reduced to the size of a single pixel. An easy way to do this is to successively divide the area into four equal parts at each step. There are four possible relationships that a surface can have with a specified area boundary. Surrounding surface − One that completely encloses the area. Surrounding surface − One that completely encloses the area. Overlapping surface − One that is partly inside and partly outside the area. Overlapping surface − One that is partly inside and partly outside the area. Inside surface − One that is completely inside the area. Inside surface − One that is completely inside the area. Outside surface − One that is completely outside the area. Outside surface − One that is completely outside the area. The tests for determining surface visibility within an area can be stated in terms of these four classifications. No further subdivisions of a specified area are needed if one of the following conditions is true − All surfaces are outside surfaces with respect to the area. Only one inside, overlapping or surrounding surface is in the area. A surrounding surface obscures all other surfaces within the area boundaries. A fast and simple object-space method for identifying the back faces of a polyhedron is based on the "inside-outside" tests. A point is "inside" a polygon surface with plane parameters A, B, C, and D if When an inside point is along the line of sight to the surface, the polygon must be a back face . We can simplify this test by considering the normal vector N to a polygon surface, which has Cartesian components . In general, if V is a vector in the viewing direction from the eye position, then this polygon is a back face if V.N > 0 Furthermore, if object descriptions are converted to projection coordinates and your viewing direction is parallel to the viewing z-axis, then − V = (0, 0, Vz) and V.N = VZC So that we only need to consider the sign of C the component of the normal vector N. In a right-handed viewing system with viewing direction along the negative axis, the polygon is a back face if C < 0. Also, we cannot see any face whose normal has z component C = 0, since your viewing direction is towards that polygon. Thus, in general, we can label any polygon as a back face if its normal vector has a z component value − C <= 0 Similar methods can be used in packages that employ a left-handed viewing system. In these packages, plane parameters A, B, C and D can be calculated from polygon vertex coordinates specified in a clockwise direction . Also, back faces have normal vectors that point away from the viewing position and are identified by C >= 0 when the viewing direction is along the positive axis. By examining parameter C for the different planes defining an object, we can immediately identify all the back faces. The A-buffer method is an extension of the depth-buffer method. The A-buffer method is a visibility detection method developed at Lucas film Studios for the rendering system Renders Everything You Ever Saw . The A-buffer expands on the depth buffer method to allow transparencies. The key data structure in the A-buffer is the accumulation buffer. Each position in the A-buffer has two fields − Depth field − It stores a positive or negative real number Depth field − It stores a positive or negative real number Intensity field − It stores surface-intensity information or a pointer value Intensity field − It stores surface-intensity information or a pointer value If depth >= 0, the number stored at that position is the depth of a single surface overlapping the corresponding pixel area. The intensity field then stores the RGB components of the surface color at that point and the percent of pixel coverage. If depth < 0, it indicates multiple-surface contributions to the pixel intensity. The intensity field then stores a pointer to a linked list of surface data. The surface buffer in the A-buffer includes − RGB intensity components Opacity Parameter Depth Percent of area coverage Surface identifier The algorithm proceeds just like the depth buffer algorithm. The depth and opacity values are used to determine the final color of a pixel. Depth sorting method uses both image space and object-space operations. The depth-sorting method performs two basic functions − First, the surfaces are sorted in order of decreasing depth. First, the surfaces are sorted in order of decreasing depth. Second, the surfaces are scan-converted in order, starting with the surface of greatest depth. Second, the surfaces are scan-converted in order, starting with the surface of greatest depth. The scan conversion of the polygon surfaces is performed in image space. This method for solving the hidden-surface problem is often referred to as the painter's algorithm. The following figure shows the effect of depth sorting − The algorithm begins by sorting by depth. For example, the initial “depth” estimate of a polygon may be taken to be the closest z value of any vertex of the polygon. Let us take the polygon P at the end of the list. Consider all polygons Q whose z-extents overlap P’s. Before drawing P, we make the following tests. If any of the following tests is positive, then we can assume P can be drawn before Q. Do the x-extents not overlap? Do the y-extents not overlap? Is P entirely on the opposite side of Q’s plane from the viewpoint? Is Q entirely on the same side of P’s plane as the viewpoint? Do the projections of the polygons not overlap? If all the tests fail, then we split either P or Q using the plane of the other. The new cut polygons are inserting into the depth order and the process continues. Theoretically, this partitioning could generate O(n2) individual polygons, but in practice, the number of polygons is much smaller. Binary space partitioning is used to calculate visibility. To build the BSP trees, one should start with polygons and label all the edges. Dealing with only one edge at a time, extend each edge so that it splits the plane in two. Place the first edge in the tree as root. Add subsequent edges based on whether they are inside or outside. Edges that span the extension of an edge that is already in the tree are split into two and both are added to the tree. From the above figure, first take A as a root. From the above figure, first take A as a root. Make a list of all nodes in figure . Make a list of all nodes in figure . Put all the nodes that are in front of root A to the left side of node A and put all those nodes that are behind the root A to the right side as shown in figure . Put all the nodes that are in front of root A to the left side of node A and put all those nodes that are behind the root A to the right side as shown in figure . Process all the front nodes first and then the nodes at the back. Process all the front nodes first and then the nodes at the back. As shown in figure , we will first process the node B. As there is nothing in front of the node B, we have put NIL. However, we have node C at back of node B, so node C will go to the right side of node B. As shown in figure , we will first process the node B. As there is nothing in front of the node B, we have put NIL. However, we have node C at back of node B, so node C will go to the right side of node B. Repeat the same process for the node D. Repeat the same process for the node D. A French/American mathematician Dr Benoit Mandelbrot discovered Fractals. The word fractal was derived from a Latin word fractus which means broken. Fractals are very complex pictures generated by a computer from a single formula. They are created using iterations. This means one formula is repeated with slightly different values over and over again, taking into account the results from the previous iteration. Fractals are used in many areas such as − Astronomy − For analyzing galaxies, rings of Saturn, etc. Astronomy − For analyzing galaxies, rings of Saturn, etc. Biology/Chemistry − For depicting bacteria cultures, Chemical reactions, human anatomy, molecules, plants, Biology/Chemistry − For depicting bacteria cultures, Chemical reactions, human anatomy, molecules, plants, Others − For depicting clouds, coastline and borderlines, data compression, diffusion, economy, fractal art, fractal music, landscapes, special effect, etc. Others − For depicting clouds, coastline and borderlines, data compression, diffusion, economy, fractal art, fractal music, landscapes, special effect, etc. Fractals can be generated by repeating the same shape over and over again as shown in the following figure. In figure shows an equilateral triangle. In figure , we can see that the triangle is repeated to create a star-like shape. In figure , we can see that the star shape in figure is repeated again and again to create a new shape. We can do unlimited number of iteration to create a desired shape. In programming terms, recursion is used to create such shapes. Geometric fractals deal with shapes found in nature that have non-integer or fractal dimensions. To geometrically construct a deterministic self-similar fractal, we start with a given geometric shape, called the initiator. Subparts of the initiator are then replaced with a pattern, called the generator. As an example, if we use the initiator and generator shown in the above figure, we can construct good pattern by repeating it. Each straight-line segment in the initiator is replaced with four equal-length line segments at each step. The scaling factor is 1/3, so the fractal dimension is D = ln 4/ln 3 ≈ 1.2619. Also, the length of each line segment in the initiator increases by a factor of 4/3 at each step, so that the length of the fractal curve tends to infinity as more detail is added to the curve as shown in the following figure − Animation means giving life to any object in computer graphics. It has the power of injecting energy and emotions into the most seemingly inanimate objects. Computer-assisted animation and computer-generated animation are two categories of computer animation. It can be presented via film or video. The basic idea behind animation is to play back the recorded images at the rates fast enough to fool the human eye into interpreting them as continuous motion. Animation can make a series of dead images come alive. Animation can be used in many areas like entertainment, computer aided-design, scientific visualization, training, education, e-commerce, and computer art. Animators have invented and used a variety of different animation techniques. Basically there are six animation technique which we would discuss one by one in this section. Traditionally most of the animation was done by hand. All the frames in an animation had to be drawn by hand. Since each second of animation requires 24 frames , the amount of efforts required to create even the shortest of movies can be tremendous. In this technique, a storyboard is laid out and then the artists draw the major frames of the animation. Major frames are the ones in which prominent changes take place. They are the key points of animation. Keyframing requires that the animator specifies critical or key positions for the objects. The computer then automatically fills in the missing frames by smoothly interpolating between those positions. In a procedural animation, the objects are animated by a procedure − a set of rules − not by keyframing. The animator specifies rules and initial conditions and runs simulation. Rules are often based on physical rules of the real world expressed by mathematical equations. In behavioral animation, an autonomous character determines its own actions, at least to a certain extent. This gives the character some ability to improvise, and frees the animator from the need to specify each detail of every character's motion. Another technique is Motion Capture, in which magnetic or vision-based sensors record the actions of a human or animal object in three dimensions. A computer then uses these data to animate the object. This technology has enabled a number of famous athletes to supply the actions for characters in sports video games. Motion capture is pretty popular with the animators mainly because some of the commonplace human actions can be captured with relative ease. However, there can be serious discrepancies between the shapes or dimensions of the subject and the graphical character and this may lead to problems of exact execution. Unlike key framing and motion picture, simulation uses the laws of physics to generate motion of pictures and other objects. Simulations can be easily used to produce slightly different sequences while maintaining physical realism. Secondly, real-time simulations allow a higher degree of interactivity where the real person can maneuver the actions of the simulated character. In contrast the applications based on key-framing and motion select and modify motions form a pre-computed library of motions. One drawback that simulation suffers from is the expertise and time required to handcraft the appropriate controls systems. A keyframe is a frame where we define changes in animation. Every frame is a keyframe when we create frame by frame animation. When someone creates a 3D animation on a computer, they usually don’t specify the exact position of any given object on every single frame. They create keyframes. Keyframes are important frames during which an object changes its size, direction, shape or other properties. The computer then figures out all the in-between frames and saves an extreme amount of time for the animator. The following illustrations depict the frames drawn by user and the frames generated by computer. The transformation of object shapes from one form to another form is called morphing. It is one of the most complicated transformations. A morph looks as if two images melt into each other with a very fluid motion. In technical terms, two images are distorted and a fade occurs between them. 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2196, "s": 1919, "text": "Computer graphics is an art of drawing pictures on computer screens with the help of programming. It involves computations, creation, and manipulation of data. In other words, we can say that computer graphics is a rendering tool for the generation and manipulation of images." }, { "code": null, "e": 2368, "s": 2196, "text": "The primary output device in a graphical system is the video monitor. The main element of a video monitor is the Cathode Ray Tube CRT, shown in the following illustration." }, { "code": null, "e": 2406, "s": 2368, "text": "The operation of CRT is very simple −" }, { "code": null, "e": 2462, "s": 2406, "text": "The electron gun emits a beam of electrons cathoderays." }, { "code": null, "e": 2518, "s": 2462, "text": "The electron gun emits a beam of electrons cathoderays." }, { "code": null, "e": 2657, "s": 2518, "text": "The electron beam passes through focusing and deflection systems that direct it towards specified positions on the phosphor-coated screen." }, { "code": null, "e": 2796, "s": 2657, "text": "The electron beam passes through focusing and deflection systems that direct it towards specified positions on the phosphor-coated screen." }, { "code": null, "e": 2917, "s": 2796, "text": "When the beam hits the screen, the phosphor emits a small spot of light at each position contacted by the electron beam." }, { "code": null, "e": 3038, "s": 2917, "text": "When the beam hits the screen, the phosphor emits a small spot of light at each position contacted by the electron beam." }, { "code": null, "e": 3134, "s": 3038, "text": "It redraws the picture by directing the electron beam back over the same screen points quickly." }, { "code": null, "e": 3230, "s": 3134, "text": "It redraws the picture by directing the electron beam back over the same screen points quickly." }, { "code": null, "e": 3322, "s": 3230, "text": "There are two ways RandomscanandRasterscan by which we can display an object on the screen." }, { "code": null, "e": 3557, "s": 3322, "text": "In a raster scan system, the electron beam is swept across the screen, one row at a time from top to bottom. As the electron beam moves across each row, the beam intensity is turned on and off to create a pattern of illuminated spots." }, { "code": null, "e": 3884, "s": 3557, "text": "Picture definition is stored in memory area called the Refresh Buffer or Frame Buffer. This memory area holds the set of intensity values for all the screen points. Stored intensity values are then retrieved from the refresh buffer and “painted” on the screen one row scanline at a time as shown in the following illustration." }, { "code": null, "e": 4078, "s": 3884, "text": "Each screen point is referred to as a pixel pictureelement or pel. At the end of each scan line, the electron beam returns to the left side of the screen to begin displaying the next scan line." }, { "code": null, "e": 4351, "s": 4078, "text": "In this technique, the electron beam is directed only to the part of the screen where the picture is to be drawn rather than scanning from left to right and top to bottom as in raster scan. It is also called vector display, stroke-writing display, or calligraphic display." }, { "code": null, "e": 4725, "s": 4351, "text": "Picture definition is stored as a set of line-drawing commands in an area of memory referred to as the refresh display file. To display a specified picture, the system cycles through the set of commands in the display file, drawing each component line in turn. After all the line-drawing commands are processed, the system cycles back to the first line command in the list." }, { "code": null, "e": 4832, "s": 4725, "text": "Random-scan displays are designed to draw all the component lines of a picture 30 to 60 times each second." }, { "code": null, "e": 4910, "s": 4832, "text": "Computer Graphics has numerous applications, some of which are listed below −" }, { "code": null, "e": 5037, "s": 4910, "text": "Computer graphics user interfaces GUIs − A graphic, mouse-oriented paradigm which allows the user to interact with a computer." }, { "code": null, "e": 5164, "s": 5037, "text": "Computer graphics user interfaces GUIs − A graphic, mouse-oriented paradigm which allows the user to interact with a computer." }, { "code": null, "e": 5236, "s": 5164, "text": "Business presentation graphics − \"A picture is worth a thousand words\"." }, { "code": null, "e": 5308, "s": 5236, "text": "Business presentation graphics − \"A picture is worth a thousand words\"." }, { "code": null, "e": 5336, "s": 5308, "text": "Cartography − Drawing maps." }, { "code": null, "e": 5364, "s": 5336, "text": "Cartography − Drawing maps." }, { "code": null, "e": 5424, "s": 5364, "text": "Weather Maps − Real-time mapping, symbolic representations." }, { "code": null, "e": 5484, "s": 5424, "text": "Weather Maps − Real-time mapping, symbolic representations." }, { "code": null, "e": 5521, "s": 5484, "text": "Satellite Imaging − Geodesic images." }, { "code": null, "e": 5558, "s": 5521, "text": "Satellite Imaging − Geodesic images." }, { "code": null, "e": 5605, "s": 5558, "text": "Photo Enhancement − Sharpening blurred photos." }, { "code": null, "e": 5652, "s": 5605, "text": "Photo Enhancement − Sharpening blurred photos." }, { "code": null, "e": 5729, "s": 5652, "text": "Medical imaging − MRIs, CAT scans, etc. - Non-invasive internal examination." }, { "code": null, "e": 5806, "s": 5729, "text": "Medical imaging − MRIs, CAT scans, etc. - Non-invasive internal examination." }, { "code": null, "e": 5905, "s": 5806, "text": "Engineering drawings − mechanical, electrical, civil, etc. - Replacing the blueprints of the past." }, { "code": null, "e": 6004, "s": 5905, "text": "Engineering drawings − mechanical, electrical, civil, etc. - Replacing the blueprints of the past." }, { "code": null, "e": 6098, "s": 6004, "text": "Typography − The use of character images in publishing - replacing the hard type of the past." }, { "code": null, "e": 6192, "s": 6098, "text": "Typography − The use of character images in publishing - replacing the hard type of the past." }, { "code": null, "e": 6303, "s": 6192, "text": "Architecture − Construction plans, exterior sketches - replacing the blueprints and hand drawings of the past." }, { "code": null, "e": 6414, "s": 6303, "text": "Architecture − Construction plans, exterior sketches - replacing the blueprints and hand drawings of the past." }, { "code": null, "e": 6464, "s": 6414, "text": "Art − Computers provide a new medium for artists." }, { "code": null, "e": 6514, "s": 6464, "text": "Art − Computers provide a new medium for artists." }, { "code": null, "e": 6577, "s": 6514, "text": "Training − Flight simulators, computer aided instruction, etc." }, { "code": null, "e": 6640, "s": 6577, "text": "Training − Flight simulators, computer aided instruction, etc." }, { "code": null, "e": 6674, "s": 6640, "text": "Entertainment − Movies and games." }, { "code": null, "e": 6708, "s": 6674, "text": "Entertainment − Movies and games." }, { "code": null, "e": 6777, "s": 6708, "text": "Simulation and modeling − Replacing physical modeling and enactments" }, { "code": null, "e": 6846, "s": 6777, "text": "Simulation and modeling − Replacing physical modeling and enactments" }, { "code": null, "e": 7094, "s": 6846, "text": "A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line. In the following three algorithms, we refer the one point of line as X0,Y0 and the second point of line as X1,Y1." }, { "code": null, "e": 7216, "s": 7094, "text": "Digital Differential Analyzer DDA algorithm is the simple line generation algorithm which is explained step by step here." }, { "code": null, "e": 7278, "s": 7216, "text": "Step 1 − Get the input of two end points (X0,Y0) and (X1,Y1)." }, { "code": null, "e": 7336, "s": 7278, "text": "Step 2 − Calculate the difference between two end points." }, { "code": null, "e": 7363, "s": 7336, "text": "dx = X1 - X0\ndy = Y1 - Y0\n" }, { "code": null, "e": 7554, "s": 7363, "text": "Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate." }, { "code": null, "e": 7642, "s": 7554, "text": "if (absolute(dx) > absolute(dy))\n Steps = absolute(dx);\nelse\n Steps = absolute(dy);" }, { "code": null, "e": 7709, "s": 7642, "text": "Step 4 − Calculate the increment in x coordinate and y coordinate." }, { "code": null, "e": 7776, "s": 7709, "text": "Xincrement = dx / (float) steps;\nYincrement = dy / (float) steps;\n" }, { "code": null, "e": 7898, "s": 7776, "text": "Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the drawing of the line." }, { "code": null, "e": 8010, "s": 7898, "text": "for(int v=0; v < Steps; v++)\n{\n x = x + Xincrement;\n y = y + Yincrement;\n putpixel(Round(x), Round(y));\n}" }, { "code": null, "e": 8268, "s": 8010, "text": "The Bresenham algorithm is another incremental scan conversion algorithm. The big advantage of this algorithm is that, it uses only integer calculations. Moving across the x axis in unit intervals and at each step choose between two different y coordinates." }, { "code": null, "e": 8441, "s": 8268, "text": "For example, as shown in the following illustration, from position 2,3 you need to choose between 3,3 and 3,4. You would like the point that is closer to the original line." }, { "code": null, "e": 8553, "s": 8441, "text": "At sample position Xk+1, the vertical separations from the mathematical line are labelled as dupper and dlower." }, { "code": null, "e": 8637, "s": 8553, "text": "From the above illustration, the y coordinate on the mathematical line at xk+1 is −" }, { "code": null, "e": 8647, "s": 8637, "text": "Y = m + b" }, { "code": null, "e": 8680, "s": 8647, "text": "So, and are given as follows −" }, { "code": null, "e": 8684, "s": 8680, "text": "and" }, { "code": null, "e": 8863, "s": 8684, "text": "You can use these to make a simple decision about which pixel is closer to the mathematical line. This simple decision is based on the difference between the two pixel positions." }, { "code": null, "e": 8954, "s": 8863, "text": "Let us substitute m with dy/dx where dx and dy are the differences between the end-points." }, { "code": null, "e": 9024, "s": 8954, "text": "So, a decision parameter for the kth step along a line is given by −" }, { "code": null, "e": 9085, "s": 9024, "text": "The sign of the decision parameter is the same as that of ." }, { "code": null, "e": 9165, "s": 9085, "text": "If is negative, then choose the lower pixel, otherwise choose the upper pixel." }, { "code": null, "e": 9338, "s": 9165, "text": "Remember, the coordinate changes occur along the x axis in unit steps, so you can do everything with integer calculations. At step k+1, the decision parameter is given as −" }, { "code": null, "e": 9370, "s": 9338, "text": "Subtracting from this we get −" }, { "code": null, "e": 9398, "s": 9370, "text": "But, is the same as . So −" }, { "code": null, "e": 9450, "s": 9398, "text": "Where, is either 0 or 1 depending on the sign of ." }, { "code": null, "e": 9511, "s": 9450, "text": "The first decision parameter is evaluated at is given as −" }, { "code": null, "e": 9621, "s": 9511, "text": "Now, keeping in mind all the above points and calculations, here is the Bresenham algorithm for slope m < 1 −" }, { "code": null, "e": 9696, "s": 9621, "text": "Step 1 − Input the two end-points of line, storing the left end-point in ." }, { "code": null, "e": 9722, "s": 9696, "text": "Step 2 − Plot the point ." }, { "code": null, "e": 9829, "s": 9722, "text": "Step 3 − Calculate the constants dx, dy, 2dy, and and get the first value for the decision parameter as −" }, { "code": null, "e": 9911, "s": 9829, "text": "Step 4 − At each along the line, starting at k = 0, perform the following test −" }, { "code": null, "e": 9951, "s": 9911, "text": "If < 0, the next point to plot is and" }, { "code": null, "e": 9963, "s": 9951, "text": " Otherwise," }, { "code": null, "e": 9994, "s": 9963, "text": "Step 5 − Repeat step 4 times." }, { "code": null, "e": 10078, "s": 9994, "text": "For m > 1, find out whether you need to increment x while incrementing y each time." }, { "code": null, "e": 10204, "s": 10078, "text": "After solving, the equation for decision parameter will be very similar, just the x and y in the equation gets interchanged." }, { "code": null, "e": 10428, "s": 10204, "text": "Mid-point algorithm is due to Bresenham which was modified by Pitteway and Van Aken. Assume that you have already put the point P at coordinate and the slope of the line is 0 ≤ k ≤ 1 as shown in the following illustration." }, { "code": null, "e": 10687, "s": 10428, "text": "Now you need to decide whether to put the next point at E or N. This can be chosen by identifying the intersection point Q closest to the point N or E. If the intersection point Q is closest to the point N then N is considered as the next point; otherwise E." }, { "code": null, "e": 10903, "s": 10687, "text": "To determine that, first calculate the mid-point M1⁄2. If the intersection point Q of the line with the vertical line connecting E and N is below M, then take E as the next point; otherwise take N as the next point." }, { "code": null, "e": 10971, "s": 10903, "text": "In order to check this, we need to consider the implicit equation −" }, { "code": null, "e": 10986, "s": 10971, "text": "F = mx + b - y" }, { "code": null, "e": 11017, "s": 10986, "text": "For positive m at any given X," }, { "code": null, "e": 11049, "s": 11017, "text": "If y is on the line, then F = 0" }, { "code": null, "e": 11084, "s": 11049, "text": "If y is above the line, then F < 0" }, { "code": null, "e": 11119, "s": 11084, "text": "If y is below the line, then F > 0" }, { "code": null, "e": 11450, "s": 11119, "text": "Drawing a circle on the screen is a little complex than drawing a line. There are two popular algorithms for generating a circle − Bresenham’s Algorithm and Midpoint Circle Algorithm. These algorithms are based on the idea of determining the subsequent points required to draw the circle. Let us discuss the algorithms in detail −" }, { "code": null, "e": 11496, "s": 11450, "text": "The equation of circle is where r is radius." }, { "code": null, "e": 11629, "s": 11496, "text": "We cannot display a continuous arc on the raster display. Instead, we have to choose the nearest pixel position to complete the arc." }, { "code": null, "e": 11783, "s": 11629, "text": "From the following illustration, you can see that we have put the pixel at location and now need to decide where to put the next pixel − at N or at S ." }, { "code": null, "e": 11832, "s": 11783, "text": "This can be decided by the decision parameter d." }, { "code": null, "e": 11881, "s": 11832, "text": "If d <= 0, then N is to be chosen as next pixel." }, { "code": null, "e": 11933, "s": 11881, "text": "If d > 0, then S is to be chosen as the next pixel." }, { "code": null, "e": 12063, "s": 11933, "text": "Step 1 − Get the coordinates of the center of the circle and radius, and store them in x, y, and R respectively. Set P=0 and Q=R." }, { "code": null, "e": 12107, "s": 12063, "text": "Step 2 − Set decision parameter D = 3 – 2R." }, { "code": null, "e": 12151, "s": 12107, "text": "Step 3 − Repeat through step-8 while P ≤ Q." }, { "code": null, "e": 12179, "s": 12151, "text": "Step 4 − Call Draw Circle ." }, { "code": null, "e": 12214, "s": 12179, "text": "Step 5 − Increment the value of P." }, { "code": null, "e": 12253, "s": 12214, "text": "Step 6 − If D < 0 then D = D + 4P + 6." }, { "code": null, "e": 12298, "s": 12253, "text": "Step 7 − Else Set R = R - 1, D = D + 4 + 10." }, { "code": null, "e": 12326, "s": 12298, "text": "Step 8 − Call Draw Circle ." }, { "code": null, "e": 12600, "s": 12326, "text": "Draw Circle Method(X, Y, P, Q).\n\nCall Putpixel (X + P, Y + Q).\nCall Putpixel (X - P, Y + Q).\nCall Putpixel (X + P, Y - Q).\nCall Putpixel (X - P, Y - Q).\nCall Putpixel (X + Q, Y + P).\nCall Putpixel (X - Q, Y + P).\nCall Putpixel (X + Q, Y - P).\nCall Putpixel (X - Q, Y - P).\n" }, { "code": null, "e": 12731, "s": 12600, "text": "Step 1 − Input radius r and circle center and obtain the first point on the circumference of the circle centered on the origin as" }, { "code": null, "e": 12750, "s": 12731, "text": "(x0, y0) = (0, r)\n" }, { "code": null, "e": 12812, "s": 12750, "text": "Step 2 − Calculate the initial value of decision parameter as" }, { "code": null, "e": 12824, "s": 12812, "text": " = 5/4 – r " }, { "code": null, "e": 13032, "s": 12824, "text": "f(x, y) = x2 + y2 - r2 = 0\n\nf(xi - 1/2 + e, yi + 1)\n = (xi - 1/2 + e)2 + (yi + 1)2 - r2 \n = (xi- 1/2)2 + (yi + 1)2 - r2 + 2(xi - 1/2)e + e2\n = f(xi - 1/2, yi + 1) + 2(xi - 1/2)e + e2 = 0" }, { "code": null, "e": 13715, "s": 13032, "text": "Let di = f(xi - 1/2, yi + 1) = -2(xi - 1/2)e - e2\nThus,\n\nIf e < 0 then di > 0 so choose point S = (xi - 1, yi + 1).\ndi+1 = f(xi - 1 - 1/2, yi + 1 + 1) = ((xi - 1/2) - 1)2 + ((yi + 1) + 1)2 - r2\n = di - 2(xi - 1) + 2(yi + 1) + 1\n = di + 2(yi + 1 - xi + 1) + 1\n\t\t \nIf e >= 0 then di <= 0 so choose point T = (xi, yi + 1)\n di+1 = f(xi - 1/2, yi + 1 + 1)\n = di + 2yi+1 + 1\n\t\t \nThe initial value of di is\n d0 = f(r - 1/2, 0 + 1) = (r - 1/2)2 + 12 - r2\n = 5/4 - r {1-r can be used if r is an integer}\n\t\t\nWhen point S = (xi - 1, yi + 1) is chosen then\n di+1 = di + -2xi+1 + 2yi+1 + 1\n\t\nWhen point T = (xi, yi + 1) is chosen then\n di+1 = di + 2yi+1 + 1" }, { "code": null, "e": 13788, "s": 13715, "text": "Step 3 − At each position starting at K=0, perform the following test −" }, { "code": null, "e": 13952, "s": 13788, "text": "If PK < 0 then next point on circle (0,0) is (XK+1,YK) and\n PK+1 = PK + 2XK+1 + 1\nElse\n PK+1 = PK + 2XK+1 + 1 – 2YK+1\n\t\nWhere, 2XK+1 = 2XK+2 and 2YK+1 = 2YK-2." }, { "code": null, "e": 14015, "s": 13952, "text": "Step 4 − Determine the symmetry points in other seven octants." }, { "code": null, "e": 14128, "s": 14015, "text": "Step 5 − Move each calculate pixel position onto the circular path centered on and plot the coordinate values." }, { "code": null, "e": 14154, "s": 14128, "text": "X = X + XC, Y = Y + YC\n" }, { "code": null, "e": 14201, "s": 14154, "text": "Step 6 − Repeat step-3 through 5 until X >= Y." }, { "code": null, "e": 14512, "s": 14201, "text": "Polygon is an ordered list of vertices as shown in the following figure. For filling polygons with particular colors, you need to determine the pixels falling on the border of the polygon and those which fall inside the polygon. In this chapter, we will see how we can fill polygons using different techniques." }, { "code": null, "e": 14684, "s": 14512, "text": "This algorithm works by intersecting scanline with polygon edges and fills the polygon between pairs of intersections. The following steps depict how this algorithm works." }, { "code": null, "e": 14744, "s": 14684, "text": "Step 1 − Find out the Ymin and Ymax from the given polygon." }, { "code": null, "e": 14932, "s": 14744, "text": "Step 2 − ScanLine intersects with each edge of the polygon from Ymin to Ymax. Name each intersection point of the polygon. As per the figure shown above, they are named as p0, p1, p2, p3." }, { "code": null, "e": 15024, "s": 14932, "text": "Step 3 − Sort the intersection point in the increasing order of X coordinate i.e. , , and ." }, { "code": null, "e": 15125, "s": 15024, "text": "Step 4 − Fill all those pair of coordinates that are inside polygons and ignore the alternate pairs." }, { "code": null, "e": 15374, "s": 15125, "text": "Sometimes we come across an object where we want to fill the area and its boundary with different colors. We can paint such objects with a specified interior color instead of searching for particular boundary color as in boundary filling algorithm." }, { "code": null, "e": 15621, "s": 15374, "text": "Instead of relying on the boundary of the object, it relies on the fill color. In other words, it replaces the interior color of the object with the fill color. When no more pixels of the original interior color exist, the algorithm is completed." }, { "code": null, "e": 15843, "s": 15621, "text": "Once again, this algorithm relies on the Four-connect or Eight-connect method of filling in the pixels. But instead of looking for the boundary color, it is looking for all adjacent pixels that are a part of the interior." }, { "code": null, "e": 16098, "s": 15843, "text": "The boundary fill algorithm works as its name. This algorithm picks a point inside an object and starts to fill until it hits the boundary of the object. The color of the boundary and the color that we fill should be different for this algorithm to work." }, { "code": null, "e": 16277, "s": 16098, "text": "In this algorithm, we assume that color of the boundary is same for the entire object. The boundary fill algorithm can be implemented by 4-connected pixels or 8-connected pixels." }, { "code": null, "e": 16522, "s": 16277, "text": "In this technique 4-connected pixels are used as shown in the figure. We are putting the pixels above, below, to the right, and to the left side of the current pixels and this process will continue until we find a boundary with different color." }, { "code": null, "e": 16585, "s": 16522, "text": "Step 1 − Initialize the value of seed point , fcolor and dcol." }, { "code": null, "e": 16637, "s": 16585, "text": "Step 2 − Define the boundary values of the polygon." }, { "code": null, "e": 16763, "s": 16637, "text": "Step 3 − Check if the current seed point is of default color, then repeat the steps 4 and 5 till the boundary pixels reached." }, { "code": null, "e": 16813, "s": 16763, "text": "If getpixel(x, y) = dcol then repeat step 4 and 5" }, { "code": null, "e": 16886, "s": 16813, "text": "Step 4 − Change the default color with the fill color at the seed point." }, { "code": null, "e": 16916, "s": 16886, "text": "setPixel(seedx, seedy, fcol)\n" }, { "code": null, "e": 16989, "s": 16916, "text": "Step 5 − Recursively follow the procedure with four neighborhood points." }, { "code": null, "e": 17158, "s": 16989, "text": "FloodFill (seedx – 1, seedy, fcol, dcol)\nFloodFill (seedx + 1, seedy, fcol, dcol)\nFloodFill (seedx, seedy - 1, fcol, dcol)\nFloodFill (seedx – 1, seedy + 1, fcol, dcol)\n" }, { "code": null, "e": 17172, "s": 17158, "text": "Step 6 − Exit" }, { "code": null, "e": 17389, "s": 17172, "text": "There is a problem with this technique. Consider the case as shown below where we tried to fill the entire region. Here, the image is filled only partially. In such cases, 4-connected pixels technique cannot be used." }, { "code": null, "e": 17580, "s": 17389, "text": "In this technique 8-connected pixels are used as shown in the figure. We are putting pixels above, below, right and left side of the current pixels as we were doing in 4-connected technique." }, { "code": null, "e": 17768, "s": 17580, "text": "In addition to this, we are also putting pixels in diagonals so that entire area of the current pixel is covered. This process will continue until we find a boundary with different color." }, { "code": null, "e": 17831, "s": 17768, "text": "Step 1 − Initialize the value of seed point , fcolor and dcol." }, { "code": null, "e": 17883, "s": 17831, "text": "Step 2 − Define the boundary values of the polygon." }, { "code": null, "e": 18007, "s": 17883, "text": "Step 3 − Check if the current seed point is of default color then repeat the steps 4 and 5 till the boundary pixels reached" }, { "code": null, "e": 18057, "s": 18007, "text": "If getpixel(x,y) = dcol then repeat step 4 and 5\n" }, { "code": null, "e": 18130, "s": 18057, "text": "Step 4 − Change the default color with the fill color at the seed point." }, { "code": null, "e": 18160, "s": 18130, "text": "setPixel(seedx, seedy, fcol)\n" }, { "code": null, "e": 18233, "s": 18160, "text": "Step 5 − Recursively follow the procedure with four neighbourhood points" }, { "code": null, "e": 18578, "s": 18233, "text": "FloodFill (seedx – 1, seedy, fcol, dcol)\nFloodFill (seedx + 1, seedy, fcol, dcol)\nFloodFill (seedx, seedy - 1, fcol, dcol)\nFloodFill (seedx, seedy + 1, fcol, dcol)\nFloodFill (seedx – 1, seedy + 1, fcol, dcol)\nFloodFill (seedx + 1, seedy + 1, fcol, dcol)\nFloodFill (seedx + 1, seedy - 1, fcol, dcol)\nFloodFill (seedx – 1, seedy - 1, fcol, dcol)\n" }, { "code": null, "e": 18592, "s": 18578, "text": "Step 6 − Exit" }, { "code": null, "e": 18733, "s": 18592, "text": "The 4-connected pixel technique failed to fill the area as marked in the following figure which won’t happen with the 8-connected technique." }, { "code": null, "e": 19002, "s": 18733, "text": "This method is also known as counting number method. While filling an object, we often need to identify whether particular point is inside the object or outside it. There are two methods by which we can identify whether particular point is inside an object or outside." }, { "code": null, "e": 19016, "s": 19002, "text": "Odd-Even Rule" }, { "code": null, "e": 19044, "s": 19016, "text": "Nonzero winding number rule" }, { "code": null, "e": 19330, "s": 19044, "text": "In this technique, we count the edge crossing along the line from any point to infinity. If the number of interactions is odd then the point is an interior point. If the number of interactions is even then point is an exterior point. Here is the example to give you the clear idea −" }, { "code": null, "e": 19580, "s": 19330, "text": "From the above figure, we can see that from the point , the number of interactions point on the left side is 5 and on the right side is 3. So the total number of interaction point is 8, which is odd. Hence, the point is considered within the object." }, { "code": null, "e": 19891, "s": 19580, "text": "This method is also used with the simple polygons to test the given point is interior or not. It can be simply understood with the help of a pin and a rubber band. Fix up the pin on one of the edge of the polygon and tie-up the rubber band in it and then stretch the rubber band along the edges of the polygon." }, { "code": null, "e": 20156, "s": 19891, "text": "When all the edges of the polygon are covered by the rubber band, check out the pin which has been fixed up at the point to be test. If we find at least one wind at the point consider it within the polygon, else we can say that the point is not inside the polygon." }, { "code": null, "e": 20317, "s": 20156, "text": "In another alternative method, give directions to all the edges of the polygon. Draw a scan line from the point to be test towards the left most of X direction." }, { "code": null, "e": 20425, "s": 20317, "text": "Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values." }, { "code": null, "e": 20533, "s": 20425, "text": "Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values." }, { "code": null, "e": 20618, "s": 20533, "text": "Check the edge direction values from which the scan line is passing and sum up them." }, { "code": null, "e": 20703, "s": 20618, "text": "Check the edge direction values from which the scan line is passing and sum up them." }, { "code": null, "e": 20843, "s": 20703, "text": "If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point." }, { "code": null, "e": 20983, "s": 20843, "text": "If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point." }, { "code": null, "e": 21169, "s": 20983, "text": "In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point." }, { "code": null, "e": 21355, "s": 21169, "text": "In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point." }, { "code": null, "e": 21701, "s": 21355, "text": "The primary use of clipping in computer graphics is to remove objects, lines, or line segments that are outside the viewing pane. The viewing transformation is insensitive to the position of points relative to the viewing volume − especially those points behind the viewer − and it is necessary to remove these points before generating the view." }, { "code": null, "e": 21992, "s": 21701, "text": "Clipping a point from a given window is very easy. Consider the following figure, where the rectangle indicates the window. Point clipping tells us whether the given point is within the given window or not; and decides whether we will use the minimum and maximum coordinates of the window." }, { "code": null, "e": 22186, "s": 21992, "text": "The X-coordinate of the given point is inside the window, if X lies in between Wx1 ≤ X ≤ Wx2. Same way, Y coordinate of the given point is inside the window, if Y lies in between Wy1 ≤ Y ≤ Wy2." }, { "code": null, "e": 22372, "s": 22186, "text": "The concept of line clipping is same as point clipping. In line clipping, we will cut the portion of line which is outside of window and keep only the portion that is inside the window." }, { "code": null, "e": 22553, "s": 22372, "text": "This algorithm uses the clipping window as shown in the following figure. The minimum coordinate for the clipping region is and the maximum coordinate for the clipping region is ." }, { "code": null, "e": 22779, "s": 22553, "text": "We will use 4-bits to divide the entire region. These 4 bits represent the Top, Bottom, Right, and Left of the region as shown in the following figure. Here, the TOP and LEFT bit is set to 1 because it is the TOP-LEFT corner." }, { "code": null, "e": 22820, "s": 22779, "text": "There are 3 possibilities for the line −" }, { "code": null, "e": 22863, "s": 22820, "text": "Line can be completely inside the window ." }, { "code": null, "e": 22906, "s": 22863, "text": "Line can be completely inside the window ." }, { "code": null, "e": 22953, "s": 22906, "text": "Line can be completely outside of the window ." }, { "code": null, "e": 23000, "s": 22953, "text": "Line can be completely outside of the window ." }, { "code": null, "e": 23042, "s": 23000, "text": "Line can be partially inside the window ." }, { "code": null, "e": 23084, "s": 23042, "text": "Line can be partially inside the window ." }, { "code": null, "e": 23134, "s": 23084, "text": "Step 1 − Assign a region code for each endpoints." }, { "code": null, "e": 23208, "s": 23134, "text": "Step 2 − If both endpoints have a region code 0000 then accept this line." }, { "code": null, "e": 23279, "s": 23208, "text": "Step 3 − Else, perform the logical ANDoperation for both region codes." }, { "code": null, "e": 23339, "s": 23279, "text": "Step 3.1 − If the result is not 0000, then reject the line." }, { "code": null, "e": 23374, "s": 23339, "text": "Step 3.2 − Else you need clipping." }, { "code": null, "e": 23446, "s": 23374, "text": "Step 3.2.1 − Choose an endpoint of the line that is outside the window." }, { "code": null, "e": 23512, "s": 23446, "text": "Step 3.2.2 − Find the intersection point at the window boundary ." }, { "code": null, "e": 23598, "s": 23512, "text": "Step 3.2.3 − Replace endpoint with the intersection point and update the region code." }, { "code": null, "e": 23703, "s": 23598, "text": "Step 3.2.4 − Repeat step 2 until we find a clipped line either trivially accepted or trivially rejected." }, { "code": null, "e": 23743, "s": 23703, "text": "Step 4 − Repeat step 1 for other lines." }, { "code": null, "e": 23876, "s": 23743, "text": "This algorithm is more efficient than Cohen-Sutherland algorithm. It employs parametric line representation and simple dot products." }, { "code": null, "e": 23909, "s": 23876, "text": "Parametric equation of line is −" }, { "code": null, "e": 23936, "s": 23909, "text": "P0P1:P(t) = P0 + t(P1-P0)\n" }, { "code": null, "e": 24159, "s": 23936, "text": "Let Ni be the outward normal edge Ei. Now pick any arbitrary point PEi on edge Ei then the dot product Ni∙[P – PEi] determines whether the point P is “inside the clip edge” or “outside” the clip edge or “on” the clip edge." }, { "code": null, "e": 24201, "s": 24159, "text": "The point P is inside if Ni.[P – PEi] < 0" }, { "code": null, "e": 24244, "s": 24201, "text": "The point P is outside if Ni.[P – PEi] > 0" }, { "code": null, "e": 24292, "s": 24244, "text": "The point P is on the edge if Ni.[P – PEi] = 0 " }, { "code": null, "e": 24309, "s": 24292, "text": "Ni.[P – PEi] = 0" }, { "code": null, "e": 24360, "s": 24309, "text": "Ni.[ P0 + t(P1-P0) – PEi] = 0 with P0 + t(P1-P0))" }, { "code": null, "e": 24392, "s": 24360, "text": "Ni.[P0 – PEi] + Ni.t[P1-P0] = 0" }, { "code": null, "e": 24447, "s": 24392, "text": "Ni.[P0 – PEi] + Ni∙tD = 0 (substituting D for [P1-P0])" }, { "code": null, "e": 24471, "s": 24447, "text": "Ni.[P0 – PEi] = - Ni∙tD" }, { "code": null, "e": 24499, "s": 24471, "text": "The equation for t becomes," }, { "code": null, "e": 24542, "s": 24499, "text": "It is valid for the following conditions −" }, { "code": null, "e": 24551, "s": 24542, "text": "Ni ≠ 0 " }, { "code": null, "e": 24569, "s": 24551, "text": "D ≠ 0 (P1 ≠ P0)" }, { "code": null, "e": 24605, "s": 24569, "text": "Ni∙D ≠ 0 (P0P1 not parallel to Ei)" }, { "code": null, "e": 24852, "s": 24605, "text": "A polygon can also be clipped by specifying the clipping window. Sutherland Hodgeman polygon clipping algorithm is used for polygon clipping. In this algorithm, all the vertices of the polygon are clipped against each edge of the clipping window." }, { "code": null, "e": 25109, "s": 24852, "text": "First the polygon is clipped against the left edge of the polygon window to get new vertices of the polygon. These new vertices are used to clip the polygon against right edge, top edge, bottom edge, of the clipping window as shown in the following figure." }, { "code": null, "e": 25404, "s": 25109, "text": "While processing an edge of a polygon with clipping window, an intersection point is found if edge is not completely inside clipping window and the a partial edge from the intersection point to the outside edge is clipped. The following figures show left, right, top and bottom edge clippings −" }, { "code": null, "e": 25652, "s": 25404, "text": "Various techniques are used to provide text clipping in a computer graphics. It depends on the methods used to generate characters and the requirements of a particular application. There are three methods for text clipping which are listed below −" }, { "code": null, "e": 25680, "s": 25652, "text": "All or none string clipping" }, { "code": null, "e": 25711, "s": 25680, "text": "All or none character clipping" }, { "code": null, "e": 25725, "s": 25711, "text": "Text clipping" }, { "code": null, "e": 25782, "s": 25725, "text": "The following figure shows all or none string clipping −" }, { "code": null, "e": 26065, "s": 25782, "text": "In all or none string clipping method, either we keep the entire string or we reject entire string based on the clipping window. As shown in the above figure, STRING2 is entirely inside the clipping window so we keep it and STRING1 being only partially inside the window, we reject." }, { "code": null, "e": 26125, "s": 26065, "text": "The following figure shows all or none character clipping −" }, { "code": null, "e": 26328, "s": 26125, "text": "This clipping method is based on characters rather than entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then −" }, { "code": null, "e": 26384, "s": 26328, "text": "You reject only the portion of the string being outside" }, { "code": null, "e": 26440, "s": 26384, "text": "You reject only the portion of the string being outside" }, { "code": null, "e": 26564, "s": 26440, "text": "If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string." }, { "code": null, "e": 26688, "s": 26564, "text": "If the character is on the boundary of the clipping window, then we discard that entire character and keep the rest string." }, { "code": null, "e": 26731, "s": 26688, "text": "The following figure shows text clipping −" }, { "code": null, "e": 26936, "s": 26731, "text": "This clipping method is based on characters rather than the entire string. In this method if the string is entirely inside the clipping window, then we keep it. If it is partially outside the window, then" }, { "code": null, "e": 26989, "s": 26936, "text": "You reject only the portion of string being outside." }, { "code": null, "e": 27042, "s": 26989, "text": "You reject only the portion of string being outside." }, { "code": null, "e": 27189, "s": 27042, "text": "If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window." }, { "code": null, "e": 27336, "s": 27189, "text": "If the character is on the boundary of the clipping window, then we discard only that portion of character that is outside of the clipping window." }, { "code": null, "e": 27694, "s": 27336, "text": "A bitmap is a collection of pixels that describes an image. It is a type of computer graphics that the computer uses to store and display pictures. In this type of graphics, images are stored bit by bit and hence it is named Bit-map graphics. For better understanding let us consider the following example where we draw a smiley face using bit-map graphics." }, { "code": null, "e": 27774, "s": 27694, "text": "Now we will see how this smiley face is stored bit by bit in computer graphics." }, { "code": null, "e": 27926, "s": 27774, "text": "By observing the original smiley face closely, we can see that there are two blue lines which are represented as B1, B2 and E1, E2 in the above figure." }, { "code": null, "e": 28040, "s": 27926, "text": "In the same way, the smiley is represented using the combination bits of A4, B5, C6, D6, E5, and F4 respectively." }, { "code": null, "e": 28088, "s": 28040, "text": "The main disadvantages of bitmap graphics are −" }, { "code": null, "e": 28169, "s": 28088, "text": "We cannot resize the bitmap image. If you try to resize, the pixels get blurred." }, { "code": null, "e": 28250, "s": 28169, "text": "We cannot resize the bitmap image. If you try to resize, the pixels get blurred." }, { "code": null, "e": 28285, "s": 28250, "text": "Colored bitmaps can be very large." }, { "code": null, "e": 28320, "s": 28285, "text": "Colored bitmaps can be very large." }, { "code": null, "e": 28595, "s": 28320, "text": "Transformation means changing some graphics into something else by applying rules. We can have various types of transformations such as translation, scaling up or down, rotation, shearing, etc. When a transformation takes place on a 2D plane, it is called 2D transformation." }, { "code": null, "e": 28734, "s": 28595, "text": "Transformations play an important role in computer graphics to reposition the graphics on the screen and change their size or orientation." }, { "code": null, "e": 28869, "s": 28734, "text": "To perform a sequence of transformation such as translation followed by rotation and scaling, we need to follow a sequential process −" }, { "code": null, "e": 28896, "s": 28869, "text": "Translate the coordinates," }, { "code": null, "e": 28940, "s": 28896, "text": "Rotate the translated coordinates, and then" }, { "code": null, "e": 29012, "s": 28940, "text": "Scale the rotated coordinates to complete the composite transformation." }, { "code": null, "e": 29199, "s": 29012, "text": "To shorten this process, we have to use 3×3 transformation matrix instead of 2×2 transformation matrix. To convert a 2×2 matrix to 3×3 matrix, we have to add an extra dummy coordinate W." }, { "code": null, "e": 29496, "s": 29199, "text": "In this way, we can represent the point by 3 numbers instead of 2 numbers, which is called Homogenous Coordinate system. In this system, we can represent all the transformation equations in matrix multiplication. Any Cartesian point P can be converted to homogenous coordinates by P’ (Xh, Yh, h)." }, { "code": null, "e": 29695, "s": 29496, "text": "A translation moves an object to a different position on the screen. You can translate a point in 2D by adding translation coordinate (tx, ty) to the original coordinate to get the new coordinate ." }, { "code": null, "e": 29739, "s": 29695, "text": "From the above figure, you can write that −" }, { "code": null, "e": 29751, "s": 29739, "text": "X’ = X + tx" }, { "code": null, "e": 29763, "s": 29751, "text": "Y’ = Y + ty" }, { "code": null, "e": 29901, "s": 29763, "text": "The pair (tx, ty) is called the translation vector or shift vector. The above equations can also be represented using the column vectors." }, { "code": null, "e": 29912, "s": 29901, "text": " p' = T = " }, { "code": null, "e": 29933, "s": 29912, "text": "We can write it as −" }, { "code": null, "e": 29944, "s": 29933, "text": "P’ = P + T" }, { "code": null, "e": 30161, "s": 29944, "text": "In rotation, we rotate the object at particular angle θ from its origin. From the following figure, we can see that the point P is located at angle φ from the horizontal X coordinate with distance r from the origin." }, { "code": null, "e": 30281, "s": 30161, "text": "Let us suppose you want to rotate it at the angle θ. After rotating it to a new location, you will get a new point P’ ." }, { "code": null, "e": 30369, "s": 30281, "text": "Using standard trigonometric the original coordinate of point P can be represented as −" }, { "code": null, "e": 30414, "s": 30369, "text": "Same way we can represent the point P’ as −" }, { "code": null, "e": 30473, "s": 30414, "text": "Substituting equation & in & respectively, we will get" }, { "code": null, "e": 30521, "s": 30473, "text": "Representing the above equation in matrix form," }, { "code": null, "e": 30532, "s": 30521, "text": "P’ = P ∙ R" }, { "code": null, "e": 30563, "s": 30532, "text": "Where R is the rotation matrix" }, { "code": null, "e": 30612, "s": 30563, "text": "The rotation angle can be positive and negative." }, { "code": null, "e": 30757, "s": 30612, "text": "For positive rotation angle, we can use the above rotation matrix. However, for negative angle rotation, the matrix will change as shown below −" }, { "code": null, "e": 31035, "s": 30757, "text": "To change the size of an object, scaling transformation is used. In the scaling process, you either expand or compress the dimensions of the object. Scaling can be achieved by multiplying the original coordinates of the object with the scaling factor to get the desired result." }, { "code": null, "e": 31210, "s": 31035, "text": "Let us assume that the original coordinates are , the scaling factors are (SX, SY), and the produced coordinates are . This can be mathematically represented as shown below −" }, { "code": null, "e": 31238, "s": 31210, "text": "X' = X . SX and Y' = Y . SY" }, { "code": null, "e": 31387, "s": 31238, "text": "The scaling factor SX, SY scales the object in X and Y direction respectively. The above equations can also be represented in matrix form as below −" }, { "code": null, "e": 31390, "s": 31387, "text": "OR" }, { "code": null, "e": 31401, "s": 31390, "text": "P’ = P . S" }, { "code": null, "e": 31486, "s": 31401, "text": "Where S is the scaling matrix. The scaling process is shown in the following figure." }, { "code": null, "e": 31669, "s": 31486, "text": "If we provide values less than 1 to the scaling factor S, then we can reduce the size of the object. If we provide values greater than 1, then we can increase the size of the object." }, { "code": null, "e": 31860, "s": 31669, "text": "Reflection is the mirror image of original object. In other words, we can say that it is a rotation operation with 180°. In reflection transformation, the size of the object does not change." }, { "code": null, "e": 31964, "s": 31860, "text": "The following figures show reflections with respect to X and Y axes, and about the origin respectively." }, { "code": null, "e": 32318, "s": 31964, "text": "A transformation that slants the shape of an object is called the shear transformation. There are two shear transformations X-Shear and Y-Shear. One shifts X coordinates values and other shifts Y coordinate values. However; in both the cases only one coordinate changes its coordinates and other preserves its values. Shearing is also termed as Skewing." }, { "code": null, "e": 32476, "s": 32318, "text": "The X-Shear preserves the Y coordinate and changes are made to X coordinates, which causes the vertical lines to tilt right or left as shown in below figure." }, { "code": null, "e": 32538, "s": 32476, "text": "The transformation matrix for X-Shear can be represented as −" }, { "code": null, "e": 32555, "s": 32538, "text": "Y' = Y + Shy . X" }, { "code": null, "e": 32562, "s": 32555, "text": "X’ = X" }, { "code": null, "e": 32748, "s": 32562, "text": "The Y-Shear preserves the X coordinates and changes the Y coordinates which causes the horizontal lines to transform into lines which slopes up or down as shown in the following figure." }, { "code": null, "e": 32799, "s": 32748, "text": "The Y-Shear can be represented in matrix from as −" }, { "code": null, "e": 32816, "s": 32799, "text": "X’ = X + Shx . Y" }, { "code": null, "e": 32823, "s": 32816, "text": "Y’ = Y" }, { "code": null, "e": 33068, "s": 32823, "text": "If a transformation of the plane T1 is followed by a second plane transformation T2, then the result itself may be represented by a single transformation T which is the composition of T1 and T2 taken in that order. This is written as T = T1∙T2." }, { "code": null, "e": 33197, "s": 33068, "text": "Composite transformation can be achieved by concatenation of transformation matrices to obtain a combined transformation matrix." }, { "code": null, "e": 33217, "s": 33197, "text": "A combined matrix −" }, { "code": null, "e": 33260, "s": 33217, "text": "[T][X] = [X] [T1] [T2] [T3] [T4] .... [Tn]" }, { "code": null, "e": 33293, "s": 33260, "text": "Where [Ti] is any combination of" }, { "code": null, "e": 33305, "s": 33293, "text": "Translation" }, { "code": null, "e": 33313, "s": 33305, "text": "Scaling" }, { "code": null, "e": 33322, "s": 33313, "text": "Shearing" }, { "code": null, "e": 33331, "s": 33322, "text": "Rotation" }, { "code": null, "e": 33342, "s": 33331, "text": "Reflection" }, { "code": null, "e": 33730, "s": 33342, "text": "The change in the order of transformation would lead to different results, as in general matrix multiplication is not cumulative, that is [A] . [B] ≠ [B] . [A] and the order of multiplication. The basic purpose of composing transformations is to gain efficiency by applying a single composed transformation to a point, rather than applying a series of transformation, one after another." }, { "code": null, "e": 33833, "s": 33730, "text": "For example, to rotate an object about an arbitrary point (Xp, Yp), we have to carry out three steps −" }, { "code": null, "e": 33873, "s": 33833, "text": "Translate point (Xp, Yp) to the origin." }, { "code": null, "e": 33901, "s": 33873, "text": "Rotate it about the origin." }, { "code": null, "e": 33967, "s": 33901, "text": "Finally, translate the center of rotation back where it belonged." }, { "code": null, "e": 34257, "s": 33967, "text": "In the 2D system, we use only two coordinates X and Y but in 3D, an extra coordinate Z is added. 3D graphics techniques and their application are fundamental to the entertainment, games, and computer-aided design industries. It is a continuing area of research in scientific visualization." }, { "code": null, "e": 34482, "s": 34257, "text": "Furthermore, 3D graphics components are now a part of almost every personal computer and, although traditionally intended for graphics-intensive software such as games, they are increasingly being used by other applications." }, { "code": null, "e": 34718, "s": 34482, "text": "Parallel projection discards z-coordinate and parallel lines from each vertex on the object are extended until they intersect the view plane. In parallel projection, we specify a direction of projection instead of center of projection." }, { "code": null, "e": 34950, "s": 34718, "text": "In parallel projection, the distance from the center of projection to project plane is infinite. In this type of projection, we connect the projected vertices by line segments which correspond to connections on the original object." }, { "code": null, "e": 35199, "s": 34950, "text": "Parallel projections are less realistic, but they are good for exact measurements. In this type of projections, parallel lines remain parallel and angles are not preserved. Various types of parallel projections are shown in the following hierarchy." }, { "code": null, "e": 35348, "s": 35199, "text": "In orthographic projection the direction of projection is normal to the projection of the plane. There are three types of orthographic projections −" }, { "code": null, "e": 35365, "s": 35348, "text": "Front Projection" }, { "code": null, "e": 35380, "s": 35365, "text": "Top Projection" }, { "code": null, "e": 35396, "s": 35380, "text": "Side Projection" }, { "code": null, "e": 35572, "s": 35396, "text": "In oblique projection, the direction of projection is not normal to the projection of plane. In oblique projection, we can view the object better than orthographic projection." }, { "code": null, "e": 35925, "s": 35572, "text": "There are two types of oblique projections − Cavalier and Cabinet. The Cavalier projection makes 45° angle with the projection plane. The projection of a line perpendicular to the view plane has the same length as the line itself in Cavalier projection. In a cavalier projection, the foreshortening factors for all three principal directions are equal." }, { "code": null, "e": 36158, "s": 35925, "text": "The Cabinet projection makes 63.4° angle with the projection plane. In Cabinet projection, lines perpendicular to the viewing surface are projected at 1⁄2 their actual length. Both the projections are shown in the following figure −" }, { "code": null, "e": 36586, "s": 36158, "text": "Orthographic projections that show more than one side of an object are called axonometric orthographic projections. The most common axonometric projection is an isometric projection where the projection plane intersects each coordinate axis in the model coordinate system at an equal distance. In this projection parallelism of lines are preserved but angles are not preserved. The following figure shows isometric projection −" }, { "code": null, "e": 36769, "s": 36586, "text": "In perspective projection, the distance from the center of projection to project plane is finite and the size of the object varies inversely with distance which looks more realistic." }, { "code": null, "e": 37043, "s": 36769, "text": "The distance and angles are not preserved and parallel lines do not remain parallel. Instead, they all converge at a single point called center of projection or projection reference point. There are 3 types of perspective projections which are shown in the following chart." }, { "code": null, "e": 37095, "s": 37043, "text": "One point perspective projection is simple to draw." }, { "code": null, "e": 37147, "s": 37095, "text": "One point perspective projection is simple to draw." }, { "code": null, "e": 37214, "s": 37147, "text": "Two point perspective projection gives better impression of depth." }, { "code": null, "e": 37281, "s": 37214, "text": "Two point perspective projection gives better impression of depth." }, { "code": null, "e": 37343, "s": 37281, "text": "Three point perspective projection is most difficult to draw." }, { "code": null, "e": 37405, "s": 37343, "text": "Three point perspective projection is most difficult to draw." }, { "code": null, "e": 37480, "s": 37405, "text": "The following figure shows all the three types of perspective projection −" }, { "code": null, "e": 37699, "s": 37480, "text": "In 3D translation, we transfer the Z coordinate along with the X and Y coordinates. The process for translation in 3D is similar to 2D translation. A translation moves an object into a different position on the screen." }, { "code": null, "e": 37754, "s": 37699, "text": "The following figure shows the effect of translation −" }, { "code": null, "e": 37876, "s": 37754, "text": "A point can be translated in 3D by adding translation coordinate to the original coordinate to get the new coordinate ." }, { "code": null, "e": 37885, "s": 37876, "text": "P’ = P∙T" }, { "code": null, "e": 38117, "s": 37885, "text": "3D rotation is not same as 2D rotation. In 3D rotation, we have to specify the angle of rotation along with the axis of rotation. We can perform 3D rotation about X, Y, and Z axes. They are represented in the matrix form as below −" }, { "code": null, "e": 38181, "s": 38117, "text": "The following figure explains the rotation about various axes −" }, { "code": null, "e": 38515, "s": 38181, "text": "You can change the size of an object using scaling transformation. In the scaling process, you either expand or compress the dimensions of the object. Scaling can be achieved by multiplying the original coordinates of the object with the scaling factor to get the desired result. The following figure shows the effect of 3D scaling −" }, { "code": null, "e": 38744, "s": 38515, "text": "In 3D scaling operation, three coordinates are used. Let us assume that the original coordinates are , scaling factors are respectively, and the produced coordinates are . This can be mathematically represented as shown below −" }, { "code": null, "e": 38753, "s": 38744, "text": "P’ = P∙S" }, { "code": null, "e": 38925, "s": 38753, "text": "A transformation that slants the shape of an object is called the shear transformation. Like in 2D shear, we can shear an object along the X-axis, Y-axis, or Z-axis in 3D." }, { "code": null, "e": 39079, "s": 38925, "text": "As shown in the above figure, there is a coordinate P. You can shear it to get a new coordinate P', which can be represented in 3D matrix form as below −" }, { "code": null, "e": 39091, "s": 39079, "text": "P’ = P ∙ Sh" }, { "code": null, "e": 39353, "s": 39091, "text": "Transformation matrix is a basic tool for transformation. A matrix with n x m dimensions is multiplied with the coordinate of objects. Usually 3 x 3 or 4 x 4 matrices are used for transformation. For example, consider the following matrix for various operation." }, { "code": null, "e": 39532, "s": 39353, "text": "In computer graphics, we often need to draw different types of objects onto the screen. Objects are not flat all the time and we need to draw curves many times to draw an object." }, { "code": null, "e": 39725, "s": 39532, "text": "A curve is an infinitely large set of points. Each point has two neighbors except endpoints. Curves can be broadly classified into three categories − explicit, implicit, and parametric curves." }, { "code": null, "e": 39942, "s": 39725, "text": "Implicit curve representations define the set of points on a curve by employing a procedure that can test to see if a point in on the curve. Usually, an implicit curve is defined by an implicit function of the form −" }, { "code": null, "e": 39948, "s": 39942, "text": "f = 0" }, { "code": null, "e": 40051, "s": 39948, "text": "It can represent multivalued curves . A common example is the circle, whose implicit representation is" }, { "code": null, "e": 40068, "s": 40051, "text": "x2 + y2 - R2 = 0" }, { "code": null, "e": 40382, "s": 40068, "text": "A mathematical function y = f can be plotted as a curve. Such a function is the explicit representation of the curve. The explicit representation is not general, since it cannot represent vertical lines and is also single-valued. For each value of x, only a single value of y is normally computed by the function." }, { "code": null, "e": 40639, "s": 40382, "text": "Curves having parametric form are called parametric curves. The explicit and implicit curve representations can be used only when the function is known. In practice the parametric curves are used. A two-dimensional parametric curve has the following form −" }, { "code": null, "e": 40660, "s": 40639, "text": "P = f, g or P = x, y" }, { "code": null, "e": 40841, "s": 40660, "text": "The functions f and g become the coordinates of any point on the curve, and the points are obtained when the parameter t is varied over a certain interval [a, b], normally [0, 1]." }, { "code": null, "e": 41101, "s": 40841, "text": "Bezier curve is discovered by the French engineer Pierre Bézier. These curves can be generated under the control of other points. Approximate tangents by using control points are used to generate curve. The Bezier curve can be represented mathematically as −" }, { "code": null, "e": 41192, "s": 41101, "text": "Where is the set of points and represents the Bernstein polynomials which are given by −" }, { "code": null, "e": 41265, "s": 41192, "text": "Where n is the polynomial degree, i is the index, and t is the variable." }, { "code": null, "e": 41457, "s": 41265, "text": "The simplest Bézier curve is the straight line from the point to . A quadratic Bezier curve is determined by three control points. A cubic Bezier curve is determined by four control points." }, { "code": null, "e": 41503, "s": 41457, "text": "Bezier curves have the following properties −" }, { "code": null, "e": 41618, "s": 41503, "text": "They generally follow the shape of the control polygon, which consists of the segments joining the control points." }, { "code": null, "e": 41733, "s": 41618, "text": "They generally follow the shape of the control polygon, which consists of the segments joining the control points." }, { "code": null, "e": 41793, "s": 41733, "text": "They always pass through the first and last control points." }, { "code": null, "e": 41853, "s": 41793, "text": "They always pass through the first and last control points." }, { "code": null, "e": 41925, "s": 41853, "text": "They are contained in the convex hull of their defining control points." }, { "code": null, "e": 41997, "s": 41925, "text": "They are contained in the convex hull of their defining control points." }, { "code": null, "e": 42199, "s": 41997, "text": "The degree of the polynomial defining the curve segment is one less that the number of defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3, i.e. cubic polynomial." }, { "code": null, "e": 42401, "s": 42199, "text": "The degree of the polynomial defining the curve segment is one less that the number of defining polygon point. Therefore, for 4 control points, the degree of the polynomial is 3, i.e. cubic polynomial." }, { "code": null, "e": 42469, "s": 42401, "text": "A Bezier curve generally follows the shape of the defining polygon." }, { "code": null, "e": 42537, "s": 42469, "text": "A Bezier curve generally follows the shape of the defining polygon." }, { "code": null, "e": 42660, "s": 42537, "text": "The direction of the tangent vector at the end points is same as that of the vector determined by first and last segments." }, { "code": null, "e": 42783, "s": 42660, "text": "The direction of the tangent vector at the end points is same as that of the vector determined by first and last segments." }, { "code": null, "e": 42892, "s": 42783, "text": "The convex hull property for a Bezier curve ensures that the polynomial smoothly follows the control points." }, { "code": null, "e": 43001, "s": 42892, "text": "The convex hull property for a Bezier curve ensures that the polynomial smoothly follows the control points." }, { "code": null, "e": 43095, "s": 43001, "text": "No straight line intersects a Bezier curve more times than it intersects its control polygon." }, { "code": null, "e": 43189, "s": 43095, "text": "No straight line intersects a Bezier curve more times than it intersects its control polygon." }, { "code": null, "e": 43240, "s": 43189, "text": "They are invariant under an affine transformation." }, { "code": null, "e": 43291, "s": 43240, "text": "They are invariant under an affine transformation." }, { "code": null, "e": 43394, "s": 43291, "text": "Bezier curves exhibit global control means moving a control point alters the shape of the whole curve." }, { "code": null, "e": 43497, "s": 43394, "text": "Bezier curves exhibit global control means moving a control point alters the shape of the whole curve." }, { "code": null, "e": 43653, "s": 43497, "text": "A given Bezier curve can be subdivided at a point t=t0 into two Bezier segments which join together at the point corresponding to the parameter value t=t0." }, { "code": null, "e": 43809, "s": 43653, "text": "A given Bezier curve can be subdivided at a point t=t0 into two Bezier segments which join together at the point corresponding to the parameter value t=t0." }, { "code": null, "e": 43892, "s": 43809, "text": "The Bezier-curve produced by the Bernstein basis function has limited flexibility." }, { "code": null, "e": 44009, "s": 43892, "text": "First, the number of specified polygon vertices fixes the order of the resulting polynomial which defines the curve." }, { "code": null, "e": 44126, "s": 44009, "text": "First, the number of specified polygon vertices fixes the order of the resulting polynomial which defines the curve." }, { "code": null, "e": 44263, "s": 44126, "text": "The second limiting characteristic is that the value of the blending function is nonzero for all parameter values over the entire curve." }, { "code": null, "e": 44400, "s": 44263, "text": "The second limiting characteristic is that the value of the blending function is nonzero for all parameter values over the entire curve." }, { "code": null, "e": 44503, "s": 44400, "text": "The B-spline basis contains the Bernstein basis as the special case. The B-spline basis is non-global." }, { "code": null, "e": 44617, "s": 44503, "text": "A B-spline curve is defined as a linear combination of control points Pi and B-spline basis function k given by" }, { "code": null, "e": 44627, "s": 44620, "text": "Where," }, { "code": null, "e": 44669, "s": 44627, "text": "{: i=0, 1, 2....n} are the control points" }, { "code": null, "e": 44711, "s": 44669, "text": "{: i=0, 1, 2....n} are the control points" }, { "code": null, "e": 44866, "s": 44711, "text": "k is the order of the polynomial segments of the B-spline curve. Order k means that the curve is made up of piecewise polynomial segments of degree k - 1," }, { "code": null, "e": 45021, "s": 44866, "text": "k is the order of the polynomial segments of the B-spline curve. Order k means that the curve is made up of piecewise polynomial segments of degree k - 1," }, { "code": null, "e": 45196, "s": 45021, "text": "the are the “normalized B-spline blending functions”. They are described by the order k and by a non-decreasing sequence of real numbers normally called the “knot sequence”." }, { "code": null, "e": 45371, "s": 45196, "text": "the are the “normalized B-spline blending functions”. They are described by the order k and by a non-decreasing sequence of real numbers normally called the “knot sequence”." }, { "code": null, "e": 45418, "s": 45371, "text": "The Ni, k functions are described as follows −" }, { "code": null, "e": 45432, "s": 45418, "text": "and if k > 1," }, { "code": null, "e": 45436, "s": 45432, "text": "and" }, { "code": null, "e": 45484, "s": 45436, "text": "B-spline curves have the following properties −" }, { "code": null, "e": 45554, "s": 45484, "text": "The sum of the B-spline basis functions for any parameter value is 1." }, { "code": null, "e": 45624, "s": 45554, "text": "The sum of the B-spline basis functions for any parameter value is 1." }, { "code": null, "e": 45690, "s": 45624, "text": "Each basis function is positive or zero for all parameter values." }, { "code": null, "e": 45756, "s": 45690, "text": "Each basis function is positive or zero for all parameter values." }, { "code": null, "e": 45825, "s": 45756, "text": "Each basis function has precisely one maximum value, except for k=1." }, { "code": null, "e": 45894, "s": 45825, "text": "Each basis function has precisely one maximum value, except for k=1." }, { "code": null, "e": 45981, "s": 45894, "text": "The maximum order of the curve is equal to the number of vertices of defining polygon." }, { "code": null, "e": 46068, "s": 45981, "text": "The maximum order of the curve is equal to the number of vertices of defining polygon." }, { "code": null, "e": 46164, "s": 46068, "text": "The degree of B-spline polynomial is independent on the number of vertices of defining polygon." }, { "code": null, "e": 46260, "s": 46164, "text": "The degree of B-spline polynomial is independent on the number of vertices of defining polygon." }, { "code": null, "e": 46452, "s": 46260, "text": "B-spline allows the local control over the curve surface because each vertex affects the shape of a curve only over a range of parameter values where its associated basis function is nonzero." }, { "code": null, "e": 46644, "s": 46452, "text": "B-spline allows the local control over the curve surface because each vertex affects the shape of a curve only over a range of parameter values where its associated basis function is nonzero." }, { "code": null, "e": 46699, "s": 46644, "text": "The curve exhibits the variation diminishing property." }, { "code": null, "e": 46754, "s": 46699, "text": "The curve exhibits the variation diminishing property." }, { "code": null, "e": 46813, "s": 46754, "text": "The curve generally follows the shape of defining polygon." }, { "code": null, "e": 46872, "s": 46813, "text": "The curve generally follows the shape of defining polygon." }, { "code": null, "e": 46978, "s": 46872, "text": "Any affine transformation can be applied to the curve by applying it to the vertices of defining polygon." }, { "code": null, "e": 47084, "s": 46978, "text": "Any affine transformation can be applied to the curve by applying it to the vertices of defining polygon." }, { "code": null, "e": 47147, "s": 47084, "text": "The curve line within the convex hull of its defining polygon." }, { "code": null, "e": 47210, "s": 47147, "text": "The curve line within the convex hull of its defining polygon." }, { "code": null, "e": 47320, "s": 47210, "text": "Objects are represented as a collection of surfaces. 3D object representation is divided into two categories." }, { "code": null, "e": 47451, "s": 47320, "text": "Boundary Representations − It describes a 3D object as a set of surfaces that separates the object interior from the environment." }, { "code": null, "e": 47582, "s": 47451, "text": "Boundary Representations − It describes a 3D object as a set of surfaces that separates the object interior from the environment." }, { "code": null, "e": 47777, "s": 47582, "text": "Space–partitioning representations − It is used to describe interior properties, by partitioning the spatial region containing an object into a set of small, non-overlapping, contiguous solids ." }, { "code": null, "e": 47972, "s": 47777, "text": "Space–partitioning representations − It is used to describe interior properties, by partitioning the spatial region containing an object into a set of small, non-overlapping, contiguous solids ." }, { "code": null, "e": 48329, "s": 47972, "text": "The most commonly used boundary representation for a 3D graphics object is a set of surface polygons that enclose the object interior. Many graphics system use this method. Set of polygons are stored for object description. This simplifies and speeds up the surface rendering and display of object since all surfaces can be described with linear equations." }, { "code": null, "e": 48610, "s": 48329, "text": "The polygon surfaces are common in design and solid-modeling applications, since their wireframe display can be done quickly to give general indication of surface structure. Then realistic scenes are produced by interpolating shading patterns across polygon surface to illuminate." }, { "code": null, "e": 48785, "s": 48610, "text": "In this method, the surface is specified by the set of vertex coordinates and associated attributes. As shown in the following figure, there are five vertices, from v1 to v5." }, { "code": null, "e": 48892, "s": 48785, "text": "Each vertex stores x, y, and z coordinate information which is represented in the table as v1: x1, y1, z1." }, { "code": null, "e": 48999, "s": 48892, "text": "Each vertex stores x, y, and z coordinate information which is represented in the table as v1: x1, y1, z1." }, { "code": null, "e": 49176, "s": 48999, "text": "The Edge table is used to store the edge information of polygon. In the following figure, edge E1 lies between vertex v1 and v2 which is represented in the table as E1: v1, v2." }, { "code": null, "e": 49353, "s": 49176, "text": "The Edge table is used to store the edge information of polygon. In the following figure, edge E1 lies between vertex v1 and v2 which is represented in the table as E1: v1, v2." }, { "code": null, "e": 49578, "s": 49353, "text": "Polygon surface table stores the number of surfaces present in the polygon. From the following figure, surface S1 is covered by edges E1, E2 and E3 which can be represented in the polygon surface table as S1: E1, E2, and E3." }, { "code": null, "e": 49803, "s": 49578, "text": "Polygon surface table stores the number of surfaces present in the polygon. From the following figure, surface S1 is covered by edges E1, E2 and E3 which can be represented in the polygon surface table as S1: E1, E2, and E3." }, { "code": null, "e": 49856, "s": 49803, "text": "The equation for plane surface can be expressed as −" }, { "code": null, "e": 49877, "s": 49856, "text": "Ax + By + Cz + D = 0" }, { "code": null, "e": 50263, "s": 49877, "text": "Where is any point on the plane, and the coefficients A, B, C, and D are constants describing the spatial properties of the plane. We can obtain the values of A, B, C, and D by solving a set of three plane equations using the coordinate values for three non collinear points in the plane. Let us assume that three vertices of the plane are (x1, y1, z1), (x2, y2, z2) and (x3, y3, z3)." }, { "code": null, "e": 50381, "s": 50263, "text": "Let us solve the following simultaneous equations for ratios A/D, B/D, and C/D. You get the values of A, B, C, and D." }, { "code": null, "e": 50402, "s": 50381, "text": " x1 + y1 + z1 = -1" }, { "code": null, "e": 50423, "s": 50402, "text": " x2 + y2 + z2 = -1" }, { "code": null, "e": 50444, "s": 50423, "text": " x3 + y3 + z3 = -1" }, { "code": null, "e": 50539, "s": 50444, "text": "To obtain the above equations in determinant form, apply Cramer’s rule to the above equations." }, { "code": null, "e": 50604, "s": 50539, "text": "For any point with parameters A, B, C, and D, we can say that −" }, { "code": null, "e": 50663, "s": 50604, "text": "Ax + By + Cz + D ≠ 0 means the point is not on the plane." }, { "code": null, "e": 50722, "s": 50663, "text": "Ax + By + Cz + D ≠ 0 means the point is not on the plane." }, { "code": null, "e": 50782, "s": 50722, "text": "Ax + By + Cz + D < 0 means the point is inside the surface." }, { "code": null, "e": 50842, "s": 50782, "text": "Ax + By + Cz + D < 0 means the point is inside the surface." }, { "code": null, "e": 50903, "s": 50842, "text": "Ax + By + Cz + D > 0 means the point is outside the surface." }, { "code": null, "e": 50964, "s": 50903, "text": "Ax + By + Cz + D > 0 means the point is outside the surface." }, { "code": null, "e": 51223, "s": 50964, "text": "3D surfaces and solids can be approximated by a set of polygonal and line elements. Such surfaces are called polygonal meshes. In polygon mesh, each edge is shared by at most two polygons. The set of polygons or faces, together form the “skin” of the object." }, { "code": null, "e": 51432, "s": 51223, "text": "This method can be used to represent a broad class of solids/surfaces in graphics. A polygonal mesh can be rendered using hidden surface removal algorithms. The polygon mesh can be represented by three ways −" }, { "code": null, "e": 51456, "s": 51432, "text": "Explicit representation" }, { "code": null, "e": 51482, "s": 51456, "text": "Pointers to a vertex list" }, { "code": null, "e": 51507, "s": 51482, "text": "Pointers to an edge list" }, { "code": null, "e": 51550, "s": 51507, "text": "It can be used to model almost any object." }, { "code": null, "e": 51606, "s": 51550, "text": "They are easy to represent as a collection of vertices." }, { "code": null, "e": 51634, "s": 51606, "text": "They are easy to transform." }, { "code": null, "e": 51676, "s": 51634, "text": "They are easy to draw on computer screen." }, { "code": null, "e": 51729, "s": 51676, "text": "Curved surfaces can only be approximately described." }, { "code": null, "e": 51799, "s": 51729, "text": "It is difficult to simulate some type of objects like hair or liquid." }, { "code": null, "e": 52112, "s": 51799, "text": "When we view a picture containing non-transparent objects and surfaces, then we cannot see those objects from view which are behind from objects closer to eye. We must remove these hidden surfaces to get a realistic screen image. The identification and removal of these surfaces is called Hidden-surface problem." }, { "code": null, "e": 52356, "s": 52112, "text": "There are two approaches for removing hidden surface problems − Object-Space method and Image-space method. The Object-space method is implemented in physical coordinate system and image-space method is implemented in screen coordinate system." }, { "code": null, "e": 52501, "s": 52356, "text": "When we want to display a 3D object on a 2D screen, we need to identify those parts of a screen that are visible from a chosen viewing position." }, { "code": null, "e": 52658, "s": 52501, "text": "This method is developed by Cutmull. It is an image-space approach. The basic idea is to test the Z-depth of each surface to determine the closest surface." }, { "code": null, "e": 52884, "s": 52658, "text": "In this method each surface is processed separately one pixel position at a time across the surface. The depth values for a pixel are compared and the closest surface determines the color to be displayed in the frame buffer." }, { "code": null, "e": 53089, "s": 52884, "text": "It is applied very efficiently on surfaces of polygon. Surfaces can be processed in any order. To override the closer polygons from the far ones, two buffers named frame buffer and depth buffer, are used." }, { "code": null, "e": 53175, "s": 53089, "text": "Depth buffer is used to store depth values for position, as surfaces are processed ." }, { "code": null, "e": 53263, "s": 53175, "text": "The frame buffer is used to store the intensity value of color value at each position ." }, { "code": null, "e": 53444, "s": 53263, "text": "The z-coordinates are usually normalized to the range [0, 1]. The 0 value for z-coordinate indicates back clipping pane and 1 value for z-coordinates indicates front clipping pane." }, { "code": null, "e": 53477, "s": 53444, "text": "Step-1 − Set the buffer values −" }, { "code": null, "e": 53494, "s": 53477, "text": "Depthbuffer = 0" }, { "code": null, "e": 53526, "s": 53494, "text": "Framebuffer = background color" }, { "code": null, "e": 53557, "s": 53526, "text": "Step-2 − Process each polygon " }, { "code": null, "e": 53625, "s": 53557, "text": "For each projected pixel position of a polygon, calculate depth z." }, { "code": null, "e": 53645, "s": 53625, "text": "If Z > depthbuffer " }, { "code": null, "e": 53668, "s": 53645, "text": "Compute surface color," }, { "code": null, "e": 53690, "s": 53668, "text": "set depthbuffer = z," }, { "code": null, "e": 53719, "s": 53690, "text": "framebuffer = surfacecolor " }, { "code": null, "e": 53744, "s": 53719, "text": "It is easy to implement." }, { "code": null, "e": 53801, "s": 53744, "text": "It reduces the speed problem if implemented in hardware." }, { "code": null, "e": 53836, "s": 53801, "text": "It processes one object at a time." }, { "code": null, "e": 53862, "s": 53836, "text": "It requires large memory." }, { "code": null, "e": 53892, "s": 53862, "text": "It is time consuming process." }, { "code": null, "e": 54265, "s": 53892, "text": "It is an image-space method to identify visible surface. This method has a depth information for only single scan-line. In order to require one scan-line of depth values, we must group and process all polygons intersecting a given scan-line at the same time before processing the next scan-line. Two important tables, edge table and polygon table, are maintained for this." }, { "code": null, "e": 54440, "s": 54265, "text": "The Edge Table − It contains coordinate endpoints of each line in the scene, the inverse slope of each line, and pointers into the polygon table to connect edges to surfaces." }, { "code": null, "e": 54584, "s": 54440, "text": "The Polygon Table − It contains the plane coefficients, surface material properties, other surface data, and may be pointers to the edge table." }, { "code": null, "e": 54902, "s": 54584, "text": "To facilitate the search for surfaces crossing a given scan-line, an active list of edges is formed. The active list stores only those edges that cross the scan-line in order of increasing x. Also a flag is set for each surface to indicate whether a position along a scan-line is either inside or outside the surface." }, { "code": null, "e": 55214, "s": 54902, "text": "Pixel positions across each scan-line are processed from left to right. At the left intersection with a surface, the surface flag is turned on and at the right, the flag is turned off. You only need to perform depth calculations when multiple surfaces have their flags turned on at a certain scan-line position." }, { "code": null, "e": 55492, "s": 55214, "text": "The area-subdivision method takes advantage by locating those view areas that represent part of a single surface. Divide the total viewing area into smaller and smaller rectangles until each small area is the projection of part of a single visible surface or no surface at all." }, { "code": null, "e": 55835, "s": 55492, "text": "Continue this process until the subdivisions are easily analyzed as belonging to a single surface or until they are reduced to the size of a single pixel. An easy way to do this is to successively divide the area into four equal parts at each step. There are four possible relationships that a surface can have with a specified area boundary." }, { "code": null, "e": 55896, "s": 55835, "text": "Surrounding surface − One that completely encloses the area." }, { "code": null, "e": 55957, "s": 55896, "text": "Surrounding surface − One that completely encloses the area." }, { "code": null, "e": 56034, "s": 55957, "text": "Overlapping surface − One that is partly inside and partly outside the area." }, { "code": null, "e": 56111, "s": 56034, "text": "Overlapping surface − One that is partly inside and partly outside the area." }, { "code": null, "e": 56168, "s": 56111, "text": "Inside surface − One that is completely inside the area." }, { "code": null, "e": 56225, "s": 56168, "text": "Inside surface − One that is completely inside the area." }, { "code": null, "e": 56284, "s": 56225, "text": "Outside surface − One that is completely outside the area." }, { "code": null, "e": 56343, "s": 56284, "text": "Outside surface − One that is completely outside the area." }, { "code": null, "e": 56557, "s": 56343, "text": "The tests for determining surface visibility within an area can be stated in terms of these four classifications. No further subdivisions of a specified area are needed if one of the following conditions is true −" }, { "code": null, "e": 56617, "s": 56557, "text": "All surfaces are outside surfaces with respect to the area." }, { "code": null, "e": 56685, "s": 56617, "text": "Only one inside, overlapping or surrounding surface is in the area." }, { "code": null, "e": 56763, "s": 56685, "text": "A surrounding surface obscures all other surfaces within the area boundaries." }, { "code": null, "e": 57065, "s": 56763, "text": "A fast and simple object-space method for identifying the back faces of a polyhedron is based on the \"inside-outside\" tests. A point is \"inside\" a polygon surface with plane parameters A, B, C, and D if When an inside point is along the line of sight to the surface, the polygon must be a back face ." }, { "code": null, "e": 57181, "s": 57065, "text": "We can simplify this test by considering the normal vector N to a polygon surface, which has Cartesian components ." }, { "code": null, "e": 57295, "s": 57181, "text": "In general, if V is a vector in the viewing direction from the eye position, then this polygon is a back face if" }, { "code": null, "e": 57303, "s": 57295, "text": "V.N > 0" }, { "code": null, "e": 57448, "s": 57303, "text": "Furthermore, if object descriptions are converted to projection coordinates and your viewing direction is parallel to the viewing z-axis, then −" }, { "code": null, "e": 57477, "s": 57448, "text": "V = (0, 0, Vz) and V.N = VZC" }, { "code": null, "e": 57562, "s": 57477, "text": "So that we only need to consider the sign of C the component of the normal vector N." }, { "code": null, "e": 57905, "s": 57562, "text": "In a right-handed viewing system with viewing direction along the negative axis, the polygon is a back face if C < 0. Also, we cannot see any face whose normal has z component C = 0, since your viewing direction is towards that polygon. Thus, in general, we can label any polygon as a back face if its normal vector has a z component value −" }, { "code": null, "e": 57912, "s": 57905, "text": "C <= 0" }, { "code": null, "e": 58131, "s": 57912, "text": "Similar methods can be used in packages that employ a left-handed viewing system. In these packages, plane parameters A, B, C and D can be calculated from polygon vertex coordinates specified in a clockwise direction ." }, { "code": null, "e": 58413, "s": 58131, "text": "Also, back faces have normal vectors that point away from the viewing position and are identified by C >= 0 when the viewing direction is along the positive axis. By examining parameter C for the different planes defining an object, we can immediately identify all the back faces." }, { "code": null, "e": 58621, "s": 58413, "text": "The A-buffer method is an extension of the depth-buffer method. The A-buffer method is a visibility detection method developed at Lucas film Studios for the rendering system Renders Everything You Ever Saw ." }, { "code": null, "e": 58761, "s": 58621, "text": "The A-buffer expands on the depth buffer method to allow transparencies. The key data structure in the A-buffer is the accumulation buffer." }, { "code": null, "e": 58808, "s": 58761, "text": "Each position in the A-buffer has two fields −" }, { "code": null, "e": 58867, "s": 58808, "text": "Depth field − It stores a positive or negative real number" }, { "code": null, "e": 58926, "s": 58867, "text": "Depth field − It stores a positive or negative real number" }, { "code": null, "e": 59003, "s": 58926, "text": "Intensity field − It stores surface-intensity information or a pointer value" }, { "code": null, "e": 59080, "s": 59003, "text": "Intensity field − It stores surface-intensity information or a pointer value" }, { "code": null, "e": 59326, "s": 59080, "text": "If depth >= 0, the number stored at that position is the depth of a single surface overlapping the corresponding pixel area. The intensity field then stores the RGB components of the surface color at that point and the percent of pixel coverage." }, { "code": null, "e": 59530, "s": 59326, "text": "If depth < 0, it indicates multiple-surface contributions to the pixel intensity. The intensity field then stores a pointer to a linked list of surface data. The surface buffer in the A-buffer includes −" }, { "code": null, "e": 59555, "s": 59530, "text": "RGB intensity components" }, { "code": null, "e": 59573, "s": 59555, "text": "Opacity Parameter" }, { "code": null, "e": 59579, "s": 59573, "text": "Depth" }, { "code": null, "e": 59604, "s": 59579, "text": "Percent of area coverage" }, { "code": null, "e": 59623, "s": 59604, "text": "Surface identifier" }, { "code": null, "e": 59763, "s": 59623, "text": "The algorithm proceeds just like the depth buffer algorithm. The depth and opacity values are used to determine the final color of a pixel." }, { "code": null, "e": 59891, "s": 59763, "text": "Depth sorting method uses both image space and object-space operations. The depth-sorting method performs two basic functions −" }, { "code": null, "e": 59952, "s": 59891, "text": "First, the surfaces are sorted in order of decreasing depth." }, { "code": null, "e": 60013, "s": 59952, "text": "First, the surfaces are sorted in order of decreasing depth." }, { "code": null, "e": 60108, "s": 60013, "text": "Second, the surfaces are scan-converted in order, starting with the surface of greatest depth." }, { "code": null, "e": 60203, "s": 60108, "text": "Second, the surfaces are scan-converted in order, starting with the surface of greatest depth." }, { "code": null, "e": 60433, "s": 60203, "text": "The scan conversion of the polygon surfaces is performed in image space. This method for solving the hidden-surface problem is often referred to as the painter's algorithm. The following figure shows the effect of depth sorting −" }, { "code": null, "e": 60599, "s": 60433, "text": "The algorithm begins by sorting by depth. For example, the initial “depth” estimate of a polygon may be taken to be the closest z value of any vertex of the polygon." }, { "code": null, "e": 60836, "s": 60599, "text": "Let us take the polygon P at the end of the list. Consider all polygons Q whose z-extents overlap P’s. Before drawing P, we make the following tests. If any of the following tests is positive, then we can assume P can be drawn before Q." }, { "code": null, "e": 60866, "s": 60836, "text": "Do the x-extents not overlap?" }, { "code": null, "e": 60896, "s": 60866, "text": "Do the y-extents not overlap?" }, { "code": null, "e": 60964, "s": 60896, "text": "Is P entirely on the opposite side of Q’s plane from the viewpoint?" }, { "code": null, "e": 61026, "s": 60964, "text": "Is Q entirely on the same side of P’s plane as the viewpoint?" }, { "code": null, "e": 61074, "s": 61026, "text": "Do the projections of the polygons not overlap?" }, { "code": null, "e": 61370, "s": 61074, "text": "If all the tests fail, then we split either P or Q using the plane of the other. The new cut polygons are inserting into the depth order and the process continues. Theoretically, this partitioning could generate O(n2) individual polygons, but in practice, the number of polygons is much smaller." }, { "code": null, "e": 61828, "s": 61370, "text": "Binary space partitioning is used to calculate visibility. To build the BSP trees, one should start with polygons and label all the edges. Dealing with only one edge at a time, extend each edge so that it splits the plane in two. Place the first edge in the tree as root. Add subsequent edges based on whether they are inside or outside. Edges that span the extension of an edge that is already in the tree are split into two and both are added to the tree." }, { "code": null, "e": 61875, "s": 61828, "text": "From the above figure, first take A as a root." }, { "code": null, "e": 61922, "s": 61875, "text": "From the above figure, first take A as a root." }, { "code": null, "e": 61959, "s": 61922, "text": "Make a list of all nodes in figure ." }, { "code": null, "e": 61996, "s": 61959, "text": "Make a list of all nodes in figure ." }, { "code": null, "e": 62159, "s": 61996, "text": "Put all the nodes that are in front of root A to the left side of node A and put all those nodes that are behind the root A to the right side as shown in figure ." }, { "code": null, "e": 62322, "s": 62159, "text": "Put all the nodes that are in front of root A to the left side of node A and put all those nodes that are behind the root A to the right side as shown in figure ." }, { "code": null, "e": 62388, "s": 62322, "text": "Process all the front nodes first and then the nodes at the back." }, { "code": null, "e": 62454, "s": 62388, "text": "Process all the front nodes first and then the nodes at the back." }, { "code": null, "e": 62660, "s": 62454, "text": "As shown in figure , we will first process the node B. As there is nothing in front of the node B, we have put NIL. However, we have node C at back of node B, so node C will go to the right side of node B." }, { "code": null, "e": 62866, "s": 62660, "text": "As shown in figure , we will first process the node B. As there is nothing in front of the node B, we have put NIL. However, we have node C at back of node B, so node C will go to the right side of node B." }, { "code": null, "e": 62906, "s": 62866, "text": "Repeat the same process for the node D." }, { "code": null, "e": 62946, "s": 62906, "text": "Repeat the same process for the node D." }, { "code": null, "e": 63095, "s": 62946, "text": "A French/American mathematician Dr Benoit Mandelbrot discovered Fractals. The word fractal was derived from a Latin word fractus which means broken." }, { "code": null, "e": 63360, "s": 63095, "text": "Fractals are very complex pictures generated by a computer from a single formula. They are created using iterations. This means one formula is repeated with slightly different values over and over again, taking into account the results from the previous iteration." }, { "code": null, "e": 63402, "s": 63360, "text": "Fractals are used in many areas such as −" }, { "code": null, "e": 63460, "s": 63402, "text": "Astronomy − For analyzing galaxies, rings of Saturn, etc." }, { "code": null, "e": 63518, "s": 63460, "text": "Astronomy − For analyzing galaxies, rings of Saturn, etc." }, { "code": null, "e": 63625, "s": 63518, "text": "Biology/Chemistry − For depicting bacteria cultures, Chemical reactions, human anatomy, molecules, plants," }, { "code": null, "e": 63732, "s": 63625, "text": "Biology/Chemistry − For depicting bacteria cultures, Chemical reactions, human anatomy, molecules, plants," }, { "code": null, "e": 63889, "s": 63732, "text": "Others − For depicting clouds, coastline and borderlines, data compression, diffusion, economy, fractal art, fractal music, landscapes, special effect, etc." }, { "code": null, "e": 64046, "s": 63889, "text": "Others − For depicting clouds, coastline and borderlines, data compression, diffusion, economy, fractal art, fractal music, landscapes, special effect, etc." }, { "code": null, "e": 64383, "s": 64046, "text": "Fractals can be generated by repeating the same shape over and over again as shown in the following figure. In figure shows an equilateral triangle. In figure , we can see that the triangle is repeated to create a star-like shape. In figure , we can see that the star shape in figure is repeated again and again to create a new shape." }, { "code": null, "e": 64513, "s": 64383, "text": "We can do unlimited number of iteration to create a desired shape. In programming terms, recursion is used to create such shapes." }, { "code": null, "e": 64819, "s": 64513, "text": "Geometric fractals deal with shapes found in nature that have non-integer or fractal dimensions. To geometrically construct a deterministic self-similar fractal, we start with a given geometric shape, called the initiator. Subparts of the initiator are then replaced with a pattern, called the generator." }, { "code": null, "e": 65132, "s": 64819, "text": "As an example, if we use the initiator and generator shown in the above figure, we can construct good pattern by repeating it. Each straight-line segment in the initiator is replaced with four equal-length line segments at each step. The scaling factor is 1/3, so the fractal dimension is D = ln 4/ln 3 ≈ 1.2619." }, { "code": null, "e": 65360, "s": 65132, "text": "Also, the length of each line segment in the initiator increases by a factor of 4/3 at each step, so that the length of the fractal curve tends to infinity as more detail is added to the curve as shown in the following figure −" }, { "code": null, "e": 65659, "s": 65360, "text": "Animation means giving life to any object in computer graphics. It has the power of injecting energy and emotions into the most seemingly inanimate objects. Computer-assisted animation and computer-generated animation are two categories of computer animation. It can be presented via film or video." }, { "code": null, "e": 66030, "s": 65659, "text": "The basic idea behind animation is to play back the recorded images at the rates fast enough to fool the human eye into interpreting them as continuous motion. Animation can make a series of dead images come alive. Animation can be used in many areas like entertainment, computer aided-design, scientific visualization, training, education, e-commerce, and computer art." }, { "code": null, "e": 66203, "s": 66030, "text": "Animators have invented and used a variety of different animation techniques. Basically there are six animation technique which we would discuss one by one in this section." }, { "code": null, "e": 66453, "s": 66203, "text": "Traditionally most of the animation was done by hand. All the frames in an animation had to be drawn by hand. Since each second of animation requires 24 frames , the amount of efforts required to create even the shortest of movies can be tremendous." }, { "code": null, "e": 66863, "s": 66453, "text": "In this technique, a storyboard is laid out and then the artists draw the major frames of the animation. Major frames are the ones in which prominent changes take place. They are the key points of animation. Keyframing requires that the animator specifies critical or key positions for the objects. The computer then automatically fills in the missing frames by smoothly interpolating between those positions." }, { "code": null, "e": 67136, "s": 66863, "text": "In a procedural animation, the objects are animated by a procedure − a set of rules − not by keyframing. The animator specifies rules and initial conditions and runs simulation. Rules are often based on physical rules of the real world expressed by mathematical equations." }, { "code": null, "e": 67384, "s": 67136, "text": "In behavioral animation, an autonomous character determines its own actions, at least to a certain extent. This gives the character some ability to improvise, and frees the animator from the need to specify each detail of every character's motion." }, { "code": null, "e": 67586, "s": 67384, "text": "Another technique is Motion Capture, in which magnetic or vision-based sensors record the actions of a human or animal object in three dimensions. A computer then uses these data to animate the object." }, { "code": null, "e": 68013, "s": 67586, "text": "This technology has enabled a number of famous athletes to supply the actions for characters in sports video games. Motion capture is pretty popular with the animators mainly because some of the commonplace human actions can be captured with relative ease. However, there can be serious discrepancies between the shapes or dimensions of the subject and the graphical character and this may lead to problems of exact execution." }, { "code": null, "e": 68391, "s": 68013, "text": "Unlike key framing and motion picture, simulation uses the laws of physics to generate motion of pictures and other objects. Simulations can be easily used to produce slightly different sequences while maintaining physical realism. Secondly, real-time simulations allow a higher degree of interactivity where the real person can maneuver the actions of the simulated character." }, { "code": null, "e": 68642, "s": 68391, "text": "In contrast the applications based on key-framing and motion select and modify motions form a pre-computed library of motions. One drawback that simulation suffers from is the expertise and time required to handcraft the appropriate controls systems." }, { "code": null, "e": 68932, "s": 68642, "text": "A keyframe is a frame where we define changes in animation. Every frame is a keyframe when we create frame by frame animation. When someone creates a 3D animation on a computer, they usually don’t specify the exact position of any given object on every single frame. They create keyframes." }, { "code": null, "e": 69250, "s": 68932, "text": "Keyframes are important frames during which an object changes its size, direction, shape or other properties. The computer then figures out all the in-between frames and saves an extreme amount of time for the animator. The following illustrations depict the frames drawn by user and the frames generated by computer." }, { "code": null, "e": 69387, "s": 69250, "text": "The transformation of object shapes from one form to another form is called morphing. It is one of the most complicated transformations." }, { "code": null, "e": 69542, "s": 69387, "text": "A morph looks as if two images melt into each other with a very fluid motion. In technical terms, two images are distorted and a fade occurs between them." }, { "code": null, "e": 69579, "s": 69542, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 69598, "s": 69579, "text": " Arnab Chakraborty" }, { "code": null, "e": 69632, "s": 69598, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 69651, "s": 69632, "text": " Arnab Chakraborty" }, { "code": null, "e": 69684, "s": 69651, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 69703, "s": 69684, "text": " Arnab Chakraborty" }, { "code": null, "e": 69738, "s": 69703, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 69746, "s": 69738, "text": " Shweta" }, { "code": null, "e": 69779, "s": 69746, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 69796, "s": 69779, "text": " Abhilash Nelson" }, { "code": null, "e": 69829, "s": 69796, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 69851, "s": 69829, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 69858, "s": 69851, "text": " Print" }, { "code": null, "e": 69869, "s": 69858, "text": " Add Notes" } ]
Assigning an integer to float and comparison in C/C++ - GeeksforGeeks
29 May, 2017 Consider the below C++ program and predict the output. #include <iostream>using namespace std; int main(){ float f = 0xffffffff; unsigned int x = 0xffffffff; // Value 4294967295 if (f == x) cout << "true"; else cout << "false"; return 0;} The output of above program is false if the “IEEE754 32-bit single float type” is used by compiler. If we define: float f = 0xffffffff; We are basically trying to assign a 32-bit integer (signed or unsigned) to a 32-bit float. The compiler will first convert the integer 0xffffffff to a nearest 32-bit float, and the memory representation of the float f is not the same as the integer 0xffffffff. We can see the above values by printing f and x. #include <iostream>using namespace std; int main(){ float f = 0xffffffff; unsigned int x = 0xffffffff; cout << "f = " << f << endl; cout << "x = " << x << endl; return 0;} Output : f = 4.29497e+09 x = 4294967295 Even if we copy the memory directly, for example, we have an integer (value equal to 0xffffffff), and we copy over the content (memory values). Since the 0xffffffff in IEEE754 is not a valid float number, so if you compare this invalid representation to itself, it is not equal. unsigned int x = 0xffffffff;memoryCopy(&f, &x, sizeof(x)); This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-data-types C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Exception Handling in C++ TCP Server-Client implementation in C 'this' pointer in C++ Input-output system calls in C | Create, Open, Close, Read, Write Multithreading in C Vector in C++ STL Inheritance in C++ Iterators in C++ STL Initialize a vector in C++ (6 different ways) Socket Programming in C/C++
[ { "code": null, "e": 24154, "s": 24126, "text": "\n29 May, 2017" }, { "code": null, "e": 24209, "s": 24154, "text": "Consider the below C++ program and predict the output." }, { "code": "#include <iostream>using namespace std; int main(){ float f = 0xffffffff; unsigned int x = 0xffffffff; // Value 4294967295 if (f == x) cout << \"true\"; else cout << \"false\"; return 0;}", "e": 24425, "s": 24209, "text": null }, { "code": null, "e": 24539, "s": 24425, "text": "The output of above program is false if the “IEEE754 32-bit single float type” is used by compiler. If we define:" }, { "code": "float f = 0xffffffff;", "e": 24561, "s": 24539, "text": null }, { "code": null, "e": 24871, "s": 24561, "text": "We are basically trying to assign a 32-bit integer (signed or unsigned) to a 32-bit float. The compiler will first convert the integer 0xffffffff to a nearest 32-bit float, and the memory representation of the float f is not the same as the integer 0xffffffff. We can see the above values by printing f and x." }, { "code": "#include <iostream>using namespace std; int main(){ float f = 0xffffffff; unsigned int x = 0xffffffff; cout << \"f = \" << f << endl; cout << \"x = \" << x << endl; return 0;}", "e": 25060, "s": 24871, "text": null }, { "code": null, "e": 25069, "s": 25060, "text": "Output :" }, { "code": null, "e": 25101, "s": 25069, "text": "f = 4.29497e+09\nx = 4294967295\n" }, { "code": null, "e": 25380, "s": 25101, "text": "Even if we copy the memory directly, for example, we have an integer (value equal to 0xffffffff), and we copy over the content (memory values). Since the 0xffffffff in IEEE754 is not a valid float number, so if you compare this invalid representation to itself, it is not equal." }, { "code": "unsigned int x = 0xffffffff;memoryCopy(&f, &x, sizeof(x));", "e": 25439, "s": 25380, "text": null }, { "code": null, "e": 25737, "s": 25439, "text": "This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 25862, "s": 25737, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25877, "s": 25862, "text": "cpp-data-types" }, { "code": null, "e": 25888, "s": 25877, "text": "C Language" }, { "code": null, "e": 25892, "s": 25888, "text": "C++" }, { "code": null, "e": 25896, "s": 25892, "text": "CPP" }, { "code": null, "e": 25994, "s": 25896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26003, "s": 25994, "text": "Comments" }, { "code": null, "e": 26016, "s": 26003, "text": "Old Comments" }, { "code": null, "e": 26042, "s": 26016, "text": "Exception Handling in C++" }, { "code": null, "e": 26080, "s": 26042, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26102, "s": 26080, "text": "'this' pointer in C++" }, { "code": null, "e": 26168, "s": 26102, "text": "Input-output system calls in C | Create, Open, Close, Read, Write" }, { "code": null, "e": 26188, "s": 26168, "text": "Multithreading in C" }, { "code": null, "e": 26206, "s": 26188, "text": "Vector in C++ STL" }, { "code": null, "e": 26225, "s": 26206, "text": "Inheritance in C++" }, { "code": null, "e": 26246, "s": 26225, "text": "Iterators in C++ STL" }, { "code": null, "e": 26292, "s": 26246, "text": "Initialize a vector in C++ (6 different ways)" } ]
PyQt5 StringSpinBox - Looping the strings - GeeksforGeeks
17 May, 2020 In this article we will see how we can make the string values repeat themselves when the last value reaches it should go back to the first value similarly when value is decremented after first value it should go back to the last value. In order to do this we have to change the custom class code of the StringSpinBox. Below is the code for the custom StringSpinBox class # custom class for String Spin Box class StringBox(QSpinBox): # constructor def __init__(self, parent=None): super(StringBox, self).__init__(parent) # list of strings strings = ["a", "b", "c", "d", "e", "f", "g"] # calling set Strings method with # adding blank value in front and in end self.setStrings(["BLANK"] + strings + ["BLANK"]) # show first value from index 1 self.setValue(1) def reset_spin(self): if self.value() == len(self.strings()) - 1: self.setValue(0) # method setString # similar to set value method def setStrings(self, strings): # making strings list strings = list(strings) # making tuple from the string list self._strings = tuple(strings) # creating a dictionary self._values = dict(zip(strings, range(len(strings)))) # setting range to it the spin box self.setRange(0, len(strings)-1) # overwriting the textFromValue method def textFromValue(self, value): # returning string from index # _string = tuple return self._strings[value] # overwriting the stepBy method # method that get called when values get incremented or decremented def stepBy(self, step): # checking if current value is 1 and step is -1 # step = -1 means decrement if self.value() == 1 and step == -1: # set current value to maximum self.setValue(self.maximum()) # checking if current value is maximum -1 and step is 1 # step = 1 means Increment elif self.value() == self.maximum() - 1 and step == 1: # setting current value to 0 self.setValue(0) # calling stepBy method of QSpinBox QSpinBox.stepBy(self, step) Explanation : Inside the String spin box custom class overwrite the stepBy method which get called when increment or decrement takes place there check the that if there is decrement and current value is minimum then change its value to maximum similarly if there is increment and it is currently at maximum value then change its value to minimum -1 value. Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys # custom class for String Spin Boxclass StringBox(QSpinBox): # constructor def __init__(self, parent = None): super(StringBox, self).__init__(parent) # list of strings strings = ["a", "b", "c", "d", "e", "f", "g"] # calling set Strings method with # adding blank value in front and in end self.setStrings(["BLANK"] + strings + ["BLANK"]) # show first value from index 1 self.setValue(1) def reset_spin(self): if self.value() == len(self.strings()) - 1: self.setValue(0) # method setString # similar to set value method def setStrings(self, strings): # making strings list strings = list(strings) # making tuple from the string list self._strings = tuple(strings) # creating a dictionary self._values = dict(zip(strings, range(len(strings)))) # setting range to it the spin box self.setRange(0, len(strings)-1) # overwriting the textFromValue method def textFromValue(self, value): # returning string from index # _string = tuple return self._strings[value] # overwriting the stepBy method # method that get called when values incremented def stepBy(self, step): # checking if current value is 1 and step is -1 # step = -1 means decrement if self.value() == 1 and step == -1: # set current value to maximum self.setValue(self.maximum()) # checking if current value is maximum -1 and step is 1 # step = 1 means Increment elif self.value() == self.maximum() - 1 and step == 1: # setting current value to 0 self.setValue(0) # calling stepBy method by QSpinBox QSpinBox.stepBy(self, step) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a string spin box string_spin_box = StringBox(self) # setting geometry to the spin box string_spin_box.setGeometry(100, 100, 200, 40) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt 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 Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n17 May, 2020" }, { "code": null, "e": 24530, "s": 24212, "text": "In this article we will see how we can make the string values repeat themselves when the last value reaches it should go back to the first value similarly when value is decremented after first value it should go back to the last value. In order to do this we have to change the custom class code of the StringSpinBox." }, { "code": null, "e": 24583, "s": 24530, "text": "Below is the code for the custom StringSpinBox class" }, { "code": null, "e": 26442, "s": 24583, "text": "# custom class for String Spin Box\nclass StringBox(QSpinBox):\n\n # constructor\n def __init__(self, parent=None):\n super(StringBox, self).__init__(parent)\n\n # list of strings\n strings = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]\n\n\n # calling set Strings method with\n # adding blank value in front and in end\n self.setStrings([\"BLANK\"] + strings + [\"BLANK\"])\n\n # show first value from index 1\n self.setValue(1)\n\n def reset_spin(self):\n if self.value() == len(self.strings()) - 1:\n self.setValue(0)\n\n # method setString\n # similar to set value method\n def setStrings(self, strings):\n\n # making strings list\n strings = list(strings)\n\n # making tuple from the string list\n self._strings = tuple(strings)\n\n # creating a dictionary\n self._values = dict(zip(strings, range(len(strings))))\n\n # setting range to it the spin box\n self.setRange(0, len(strings)-1)\n\n # overwriting the textFromValue method\n def textFromValue(self, value):\n\n # returning string from index\n # _string = tuple\n return self._strings[value]\n\n # overwriting the stepBy method\n # method that get called when values get incremented or decremented\n def stepBy(self, step):\n\n # checking if current value is 1 and step is -1\n # step = -1 means decrement\n if self.value() == 1 and step == -1:\n\n # set current value to maximum\n self.setValue(self.maximum())\n\n # checking if current value is maximum -1 and step is 1\n # step = 1 means Increment\n elif self.value() == self.maximum() - 1 and step == 1:\n\n # setting current value to 0\n self.setValue(0)\n \n # calling stepBy method of QSpinBox\n QSpinBox.stepBy(self, step)\n\n" }, { "code": null, "e": 26798, "s": 26442, "text": "Explanation : Inside the String spin box custom class overwrite the stepBy method which get called when increment or decrement takes place there check the that if there is decrement and current value is minimum then change its value to maximum similarly if there is increment and it is currently at maximum value then change its value to minimum -1 value." }, { "code": null, "e": 26826, "s": 26798, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys # custom class for String Spin Boxclass StringBox(QSpinBox): # constructor def __init__(self, parent = None): super(StringBox, self).__init__(parent) # list of strings strings = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"] # calling set Strings method with # adding blank value in front and in end self.setStrings([\"BLANK\"] + strings + [\"BLANK\"]) # show first value from index 1 self.setValue(1) def reset_spin(self): if self.value() == len(self.strings()) - 1: self.setValue(0) # method setString # similar to set value method def setStrings(self, strings): # making strings list strings = list(strings) # making tuple from the string list self._strings = tuple(strings) # creating a dictionary self._values = dict(zip(strings, range(len(strings)))) # setting range to it the spin box self.setRange(0, len(strings)-1) # overwriting the textFromValue method def textFromValue(self, value): # returning string from index # _string = tuple return self._strings[value] # overwriting the stepBy method # method that get called when values incremented def stepBy(self, step): # checking if current value is 1 and step is -1 # step = -1 means decrement if self.value() == 1 and step == -1: # set current value to maximum self.setValue(self.maximum()) # checking if current value is maximum -1 and step is 1 # step = 1 means Increment elif self.value() == self.maximum() - 1 and step == 1: # setting current value to 0 self.setValue(0) # calling stepBy method by QSpinBox QSpinBox.stepBy(self, step) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a string spin box string_spin_box = StringBox(self) # setting geometry to the spin box string_spin_box.setGeometry(100, 100, 200, 40) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 29475, "s": 26826, "text": null }, { "code": null, "e": 29484, "s": 29475, "text": "Output :" }, { "code": null, "e": 29504, "s": 29484, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 29515, "s": 29504, "text": "Python-gui" }, { "code": null, "e": 29527, "s": 29515, "text": "Python-PyQt" }, { "code": null, "e": 29534, "s": 29527, "text": "Python" }, { "code": null, "e": 29632, "s": 29534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29641, "s": 29632, "text": "Comments" }, { "code": null, "e": 29654, "s": 29641, "text": "Old Comments" }, { "code": null, "e": 29686, "s": 29654, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29742, "s": 29686, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29763, "s": 29742, "text": "Python OOPs Concepts" }, { "code": null, "e": 29802, "s": 29763, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29844, "s": 29802, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29871, "s": 29844, "text": "Python Classes and Objects" }, { "code": null, "e": 29902, "s": 29871, "text": "Python | os.path.join() method" }, { "code": null, "e": 29944, "s": 29902, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29980, "s": 29944, "text": "Python | Pandas dataframe.groupby()" } ]
Continuous Genetic Algorithm From Scratch With Python | by Cahit bartu yazıcı | Towards Data Science
Genetic algorithm is a powerful optimization technique that was inspired by nature. Genetic algorithms mimic evolution to find the best solution. Unlike most optimization algorithms, genetic algorithms do not use derivatives to find the minima. One of the most significant advantages of genetic algorithms is their ability to find a global minimum without getting stuck in local minima. Randomness plays a substantial role in the structure of genetic algorithms, and it is the main reason genetic algorithms keep searching the search space. The continuous in the title means the genetic algorithm we are going to create will be using floating numbers or integers as optimization parameters instead of binary numbers. Genetic algorithms create an initial population of randomly generated candidate solutions, these candidate solutions are evaluated, and their fitness value is calculated. The fitness value of a solution is the numeric value that determines how good a solution is, higher the fitness value better the solution. The figure below shows an example generation with 8 individuals. Each individual is made up of 4 genes, which represent the optimization parameters, and each individual has a fitness value, which in this case is the sum of the values of the genes. If the initial population does not meet the requirements of the termination criteria, genetic algorithm creates the next generation. The first genetic operation is Selection; in this operation, the individuals that are going to be moving on to the next generation are selected. After the selection process, Pairing operation commences. Pairing operation pairs the selected individuals two by two for the Mating operation. The Mating operation takes the paired parent individuals and creates offsprings, which will be replacing the individuals that were not selected in the Selection operation, so the next generation has the same number of individuals as the previous generation. This process is repeated until the termination criteria is met. In this article, the genetic algorithm code was created from scratch using the Python standard library and Numpy. Each of the genetic operations discussed before are created as functions. Before we begin with the genetic algorithm code we need to import some libraries as; import numpy as npfrom numpy.random import randintfrom random import random as rndfrom random import gauss, randrange Genetic algorithms begin the optimization process by creating an initial population of candidate solutions whose genes are randomly generated. To create the initial population, a function which creates individuals must be created; def individual(number_of_genes, upper_limit, lower_limit): individual=[round(rnd()*(upper_limit-lower_limit) +lower_limit,1) for x in range(number_of_genes)] return individual The function takes number of genes, upper and lower limits for the genes as inputs and creates the individual. After the function to create individuals is created, another function is needed to create the population. The function to create a population can be written as; def population(number_of_individuals, number_of_genes, upper_limit, lower_limit): return [individual(number_of_genes, upper_limit, lower_limit) for x in range(number_of_individuals)] Using these two functions, the initial population can be created. After the genetic algorithm creates the first generation, the fitness values of the individuals are calculated. Fitness calculation function determines the fitness value of an individual, how to calculate the fitness value depends on the optimization problem. If the problem is to optimize the parameters of a function, that function should be implemented to the fitness calculation function. The optimization problem can be very complex, and using specific software may be needed to solve the problem; in that case, the fitness calculation function should run simulations and collect the results from the software that is being used. For simplicity, we will go over the generation example given at the beginning of the article. def fitness_calculation(individual); fitness_value = sum(individual) return fitness_value This is a very simple fitness function with only one parameter. Fitness function can be calculated for multiple parameters. For multiple parameters, normalizing the different parameters is vert important, the difference in magnitude between different parameters may cause one of the parameters to become obsolete for the fitness function value. Parameters can be optimized with different methods, one of the normalization methods is rescaling. Rescaling can be shown as; Where the m_s is the scaled value of the parameter, m_o is the actual value of the parameter. In this function, maximum and minimum value of the parameter should be determined according to the nature of the proplem. After the parameters are normalized, the importance of the parameters are determined by the biases given to each parameter in the fitness function. Sum of the biases given to the parameters should be 1. For multiple parameters, the fitness function can be written as; Where b represents the biases of the fitness function and p represents the normalized parameters. The Selection function takes the population of candidate solutions and their fitness values (a generation) and outputs the individuals that are going to be moving on to the next generation. Elitism can be introduced to the genetic algorithm, which will automatically select the best individual in a generation, so we do not lose the best solution. There are a few selection methods that can be used. Selection methods given in this article are; Roulette wheel selection : In roulette wheel selection, each individual has a chance to be selected. The chance of an individual to be selected is based on the fitness value of the individual. Fitter individuals have a higher chance to be selected. The function for roulette wheel selection takes the cumulative sums and the randomly generated value for the selection process and returns the number of the selected individual. By calculating the cumulative sums, each individual have a unique value between 0 and 1. To select individuals, a number between 0 and 1 is randomly generated and the individual that is closes to the randomly generated number is selected. The roulette function can be written as; def roulette(cum_sum, chance): veriable = list(cum_sum.copy()) veriable.append(chance) veriable = sorted(veriable) return veriable.index(chance) Fittest half selection : In this selection method, fittest half of the candidate solutions are selected to move to the next generation. Random Selection : In this method, individuals selected randomly. Selection function can be written as; def selection(generation, method='Fittest Half'): generation['Normalized Fitness'] = \ sorted([generation['Fitness'][x]/sum(generation['Fitness']) for x in range(len(generation['Fitness']))], reverse = True) generation['Cumulative Sum'] = np.array( generation['Normalized Fitness']).cumsum() if method == 'Roulette Wheel': selected = [] for x in range(len(generation['Individuals'])//2): selected.append(roulette(generation ['Cumulative Sum'], rnd())) while len(set(selected)) != len(selected): selected[x] = \ (roulette(generation['Cumulative Sum'], rnd())) selected = {'Individuals': [generation['Individuals'][int(selected[x])] for x in range(len(generation['Individuals'])//2)] ,'Fitness': [generation['Fitness'][int(selected[x])] for x in range( len(generation['Individuals'])//2)]} elif method == 'Fittest Half': selected_individuals = [generation['Individuals'][-x-1] for x in range(int(len(generation['Individuals'])//2))] selected_fitnesses = [generation['Fitness'][-x-1] for x in range(int(len(generation['Individuals'])//2))] selected = {'Individuals': selected_individuals, 'Fitness': selected_fitnesses} elif method == 'Random': selected_individuals = \ [generation['Individuals'] [randint(1,len(generation['Fitness']))] for x in range(int(len(generation['Individuals'])//2))] selected_fitnesses = [generation['Fitness'][-x-1] for x in range(int(len(generation['Individuals'])//2))] selected = {'Individuals': selected_individuals, 'Fitness': selected_fitnesses} return selected Pairing and mating are used as a single operation in most genetic algorithm applications, but for creating simpler functions and to be able to used different mating and paring algorithms easily, the two genetic operations are separated in this application. If there is elitism in the genetic algorithm, the elit must be an input to the function as well as the selected individuals. We are going to discuss three different pairing methods; Fittest: In this method, individuals are paired two by two, starting from the fittest individual. By doing so, fitter individuals are paired together, but less fit individuals are paired together as well. Random: In this method, individuals are paired two by two randomly. Weighted random: In this method, individuals are paired randomly two by two, but fitter individuals have a higher chance to be selected for pairing. Pairing function can be written as; def pairing(elit, selected, method = 'Fittest'): individuals = [elit['Individuals']]+selected['Individuals'] fitness = [elit['Fitness']]+selected['Fitness'] if method == 'Fittest': parents = [[individuals[x],individuals[x+1]] for x in range(len(individuals)//2)] if method == 'Random': parents = [] for x in range(len(individuals)//2): parents.append( [individuals[randint(0,(len(individuals)-1))], individuals[randint(0,(len(individuals)-1))]]) while parents[x][0] == parents[x][1]: parents[x][1] = individuals[ randint(0,(len(individuals)-1))] if method == 'Weighted Random': normalized_fitness = sorted( [fitness[x] /sum(fitness) for x in range(len(individuals)//2)], reverse = True) cummulitive_sum = np.array(normalized_fitness).cumsum() parents = [] for x in range(len(individuals)//2): parents.append( [individuals[roulette(cummulitive_sum,rnd())], individuals[roulette(cummulitive_sum,rnd())]]) while parents[x][0] == parents[x][1]: parents[x][1] = individuals[ roulette(cummulitive_sum,rnd())] return parents We will discuss two different mating methods. In the Python code given below, two selected parent individuals create two offsprings. There are two mating methods we are going to discuss. Single point: In this method, genes after a single point are replaced with the genes of the other parent to crate two offsprings. Two points: In this method, genes between two points are replaced with the genes of the other parent to create two offsprings. Mating function can be coded as; def mating(parents, method='Single Point'): if method == 'Single Point': pivot_point = randint(1, len(parents[0])) offsprings = [parents[0] \ [0:pivot_point]+parents[1][pivot_point:]] offsprings.append(parents[1] [0:pivot_point]+parents[0][pivot_point:]) if method == 'Two Pionts': pivot_point_1 = randint(1, len(parents[0]-1)) pivot_point_2 = randint(1, len(parents[0])) while pivot_point_2<pivot_point_1: pivot_point_2 = randint(1, len(parents[0])) offsprings = [parents[0][0:pivot_point_1]+ parents[1][pivot_point_1:pivot_point_2]+ [parents[0][pivot_point_2:]]] offsprings.append([parents[1][0:pivot_point_1]+ parents[0][pivot_point_1:pivot_point_2]+ [parents[1][pivot_point_2:]]]) return offsprings The final genetic operation is random mutations. Random mutations occur in the selected individuals and their offsprings to improve variety of the next generation. If there is elitism in the genetic algorithm, elit individual does not go through random mutations so we do not lose the best solution. We are going to discuss two different mutation methods. Gauss: In this method, the gene that goes through mutation is replaced with a number that is generated according to gauss distribution around the original gene. Reset: In this method, the original gene is replaced with a randomly generated gene. The mutation function can be written as; def mutation(individual, upper_limit, lower_limit, muatation_rate=2, method='Reset', standard_deviation = 0.001): gene = [randint(0, 7)] for x in range(muatation_rate-1): gene.append(randint(0, 7)) while len(set(gene)) < len(gene): gene[x] = randint(0, 7) mutated_individual = individual.copy() if method == 'Gauss': for x in range(muatation_rate): mutated_individual[x] = \ round(individual[x]+gauss(0, standard_deviation), 1) if method == 'Reset': for x in range(muatation_rate): mutated_individual[x] = round(rnd()* \ (upper_limit-lower_limit)+lower_limit,1) return mutated_individual The next generation is created using the genetic operations we discussed. Elitism can be introduced to the genetic algorithm during the creating of next generation. Elitism is the The python code to create the next generation can be written as; def next_generation(gen, upper_limit, lower_limit): elit = {} next_gen = {} elit['Individuals'] = gen['Individuals'].pop(-1) elit['Fitness'] = gen['Fitness'].pop(-1) selected = selection(gen) parents = pairing(elit, selected) offsprings = [[[mating(parents[x]) for x in range(len(parents))] [y][z] for z in range(2)] for y in range(len(parents))] offsprings1 = [offsprings[x][0] for x in range(len(parents))] offsprings2 = [offsprings[x][1] for x in range(len(parents))] unmutated = selected['Individuals']+offsprings1+offsprings2 mutated = [mutation(unmutated[x], upper_limit, lower_limit) for x in range(len(gen['Individuals']))] unsorted_individuals = mutated + [elit['Individuals']] unsorted_next_gen = \ [fitness_calculation(mutated[x]) for x in range(len(mutated))] unsorted_fitness = [unsorted_next_gen[x] for x in range(len(gen['Fitness']))] + [elit['Fitness']] sorted_next_gen = \ sorted([[unsorted_individuals[x], unsorted_fitness[x]] for x in range(len(unsorted_individuals))], key=lambda x: x[1]) next_gen['Individuals'] = [sorted_next_gen[x][0] for x in range(len(sorted_next_gen))] next_gen['Fitness'] = [sorted_next_gen[x][1] for x in range(len(sorted_next_gen))] gen['Individuals'].append(elit['Individuals']) gen['Fitness'].append(elit['Fitness']) return next_gen After a generation is created, termination criteria are used to determine if the genetic algorithm should create another generation or should it stop. Different termination criteria can be used at the same time and if the genetic algorithm satisfies one of the criteria the genetic algorithm stops. We are going to disscuss four termination criteria. Maximum fitness : This termination criteria checks if the fittest individual in the current generation satisfies our criteria. Using this termiantion method, desired results can be obtained. As seen from the figure below, maximum fitness limit can be determined to include some of the local minima. Maximum average fitness: If we are interested in a set of solutions average values of the individuals in the current generations can be checked to determine if the current generation satisfies our expectations. Maximum number of generations: We could limit the maximum number of generations created by the genetic algorithm. Maximum similar fitness number: Due to elitism best individual in a generation moves on to the next generation without mutating. This individual can be the best individual in the next generation as well. We can limit the number for the same individual to be the best individual as this can be sing that the genetic algorithm got stuck in a local minima. The function for checking if the maximum fitness value have changed can be written as; def fitness_similarity_chech(max_fitness, number_of_similarity): result = False similarity = 0 for n in range(len(max_fitness)-1): if max_fitness[n] == max_fitness[n+1]: similarity += 1 else: similarity = 0 if similarity == number_of_similarity-1: result = True return result Now that all of the function we need for the genetic algorithm is ready, we can begin the optimization process. To run the genetic algorithm with 20 individuals in each generation; # Generations and fitness values will be written to this fileResult_file = 'GA_Results.txt'# Creating the First Generationdef first_generation(pop): fitness = [fitness_calculation(pop[x]) for x in range(len(pop))] sorted_fitness = sorted([[pop[x], fitness[x]] for x in range(len(pop))], key=lambda x: x[1]) population = [sorted_fitness[x][0] for x in range(len(sorted_fitness))] fitness = [sorted_fitness[x][1] for x in range(len(sorted_fitness))] return {'Individuals': population, 'Fitness': sorted(fitness)}pop = population(20,8,1,0)gen = []gen.append(first_generation(pop))fitness_avg = np.array([sum(gen[0]['Fitness'])/ len(gen[0]['Fitness'])])fitness_max = np.array([max(gen[0]['Fitness'])])res = open(Result_file, 'a')res.write('\n'+str(gen)+'\n')res.close()finish = Falsewhile finish == False: if max(fitness_max) > 6: break if max(fitness_avg) > 5: break if fitness_similarity_chech(fitness_max, 50) == True: break gen.append(next_generation(gen[-1],1,0)) fitness_avg = np.append(fitness_avg, sum( gen[-1]['Fitness'])/len(gen[-1]['Fitness'])) fitness_max = np.append(fitness_max, max(gen[-1]['Fitness'])) res = open(Result_file, 'a') res.write('\n'+str(gen[-1])+'\n') res.close() Genetic algorithms can be used to solve multi-parameter constraint optimization problems. Like most of optimization algorithms, genetic algorithms can be implemented directly from some libraries like sklearn, but creating the algorithm from scratch gives a perspective on how it works and the algorithm can be tailored to a specific problem. Thank you for reading, I hope the article was helpful. Genetic algorithms were first proposed by John H. Holland, you can find his original work here; https://mitpress.mit.edu/books/adaptation-natural-and-artificial-systems You can check out these two books if you want to learn more about genetic algorithms as well;
[ { "code": null, "e": 889, "s": 172, "text": "Genetic algorithm is a powerful optimization technique that was inspired by nature. Genetic algorithms mimic evolution to find the best solution. Unlike most optimization algorithms, genetic algorithms do not use derivatives to find the minima. One of the most significant advantages of genetic algorithms is their ability to find a global minimum without getting stuck in local minima. Randomness plays a substantial role in the structure of genetic algorithms, and it is the main reason genetic algorithms keep searching the search space. The continuous in the title means the genetic algorithm we are going to create will be using floating numbers or integers as optimization parameters instead of binary numbers." }, { "code": null, "e": 1447, "s": 889, "text": "Genetic algorithms create an initial population of randomly generated candidate solutions, these candidate solutions are evaluated, and their fitness value is calculated. The fitness value of a solution is the numeric value that determines how good a solution is, higher the fitness value better the solution. The figure below shows an example generation with 8 individuals. Each individual is made up of 4 genes, which represent the optimization parameters, and each individual has a fitness value, which in this case is the sum of the values of the genes." }, { "code": null, "e": 2191, "s": 1447, "text": "If the initial population does not meet the requirements of the termination criteria, genetic algorithm creates the next generation. The first genetic operation is Selection; in this operation, the individuals that are going to be moving on to the next generation are selected. After the selection process, Pairing operation commences. Pairing operation pairs the selected individuals two by two for the Mating operation. The Mating operation takes the paired parent individuals and creates offsprings, which will be replacing the individuals that were not selected in the Selection operation, so the next generation has the same number of individuals as the previous generation. This process is repeated until the termination criteria is met." }, { "code": null, "e": 2464, "s": 2191, "text": "In this article, the genetic algorithm code was created from scratch using the Python standard library and Numpy. Each of the genetic operations discussed before are created as functions. Before we begin with the genetic algorithm code we need to import some libraries as;" }, { "code": null, "e": 2582, "s": 2464, "text": "import numpy as npfrom numpy.random import randintfrom random import random as rndfrom random import gauss, randrange" }, { "code": null, "e": 2813, "s": 2582, "text": "Genetic algorithms begin the optimization process by creating an initial population of candidate solutions whose genes are randomly generated. To create the initial population, a function which creates individuals must be created;" }, { "code": null, "e": 3011, "s": 2813, "text": "def individual(number_of_genes, upper_limit, lower_limit): individual=[round(rnd()*(upper_limit-lower_limit) +lower_limit,1) for x in range(number_of_genes)] return individual " }, { "code": null, "e": 3283, "s": 3011, "text": "The function takes number of genes, upper and lower limits for the genes as inputs and creates the individual. After the function to create individuals is created, another function is needed to create the population. The function to create a population can be written as;" }, { "code": null, "e": 3491, "s": 3283, "text": "def population(number_of_individuals, number_of_genes, upper_limit, lower_limit): return [individual(number_of_genes, upper_limit, lower_limit) for x in range(number_of_individuals)]" }, { "code": null, "e": 3669, "s": 3491, "text": "Using these two functions, the initial population can be created. After the genetic algorithm creates the first generation, the fitness values of the individuals are calculated." }, { "code": null, "e": 4286, "s": 3669, "text": "Fitness calculation function determines the fitness value of an individual, how to calculate the fitness value depends on the optimization problem. If the problem is to optimize the parameters of a function, that function should be implemented to the fitness calculation function. The optimization problem can be very complex, and using specific software may be needed to solve the problem; in that case, the fitness calculation function should run simulations and collect the results from the software that is being used. For simplicity, we will go over the generation example given at the beginning of the article." }, { "code": null, "e": 4382, "s": 4286, "text": "def fitness_calculation(individual); fitness_value = sum(individual) return fitness_value" }, { "code": null, "e": 4853, "s": 4382, "text": "This is a very simple fitness function with only one parameter. Fitness function can be calculated for multiple parameters. For multiple parameters, normalizing the different parameters is vert important, the difference in magnitude between different parameters may cause one of the parameters to become obsolete for the fitness function value. Parameters can be optimized with different methods, one of the normalization methods is rescaling. Rescaling can be shown as;" }, { "code": null, "e": 5069, "s": 4853, "text": "Where the m_s is the scaled value of the parameter, m_o is the actual value of the parameter. In this function, maximum and minimum value of the parameter should be determined according to the nature of the proplem." }, { "code": null, "e": 5337, "s": 5069, "text": "After the parameters are normalized, the importance of the parameters are determined by the biases given to each parameter in the fitness function. Sum of the biases given to the parameters should be 1. For multiple parameters, the fitness function can be written as;" }, { "code": null, "e": 5435, "s": 5337, "text": "Where b represents the biases of the fitness function and p represents the normalized parameters." }, { "code": null, "e": 5880, "s": 5435, "text": "The Selection function takes the population of candidate solutions and their fitness values (a generation) and outputs the individuals that are going to be moving on to the next generation. Elitism can be introduced to the genetic algorithm, which will automatically select the best individual in a generation, so we do not lose the best solution. There are a few selection methods that can be used. Selection methods given in this article are;" }, { "code": null, "e": 6129, "s": 5880, "text": "Roulette wheel selection : In roulette wheel selection, each individual has a chance to be selected. The chance of an individual to be selected is based on the fitness value of the individual. Fitter individuals have a higher chance to be selected." }, { "code": null, "e": 6587, "s": 6129, "text": "The function for roulette wheel selection takes the cumulative sums and the randomly generated value for the selection process and returns the number of the selected individual. By calculating the cumulative sums, each individual have a unique value between 0 and 1. To select individuals, a number between 0 and 1 is randomly generated and the individual that is closes to the randomly generated number is selected. The roulette function can be written as;" }, { "code": null, "e": 6744, "s": 6587, "text": "def roulette(cum_sum, chance): veriable = list(cum_sum.copy()) veriable.append(chance) veriable = sorted(veriable) return veriable.index(chance)" }, { "code": null, "e": 6880, "s": 6744, "text": "Fittest half selection : In this selection method, fittest half of the candidate solutions are selected to move to the next generation." }, { "code": null, "e": 6946, "s": 6880, "text": "Random Selection : In this method, individuals selected randomly." }, { "code": null, "e": 6984, "s": 6946, "text": "Selection function can be written as;" }, { "code": null, "e": 8834, "s": 6984, "text": "def selection(generation, method='Fittest Half'): generation['Normalized Fitness'] = \\ sorted([generation['Fitness'][x]/sum(generation['Fitness']) for x in range(len(generation['Fitness']))], reverse = True) generation['Cumulative Sum'] = np.array( generation['Normalized Fitness']).cumsum() if method == 'Roulette Wheel': selected = [] for x in range(len(generation['Individuals'])//2): selected.append(roulette(generation ['Cumulative Sum'], rnd())) while len(set(selected)) != len(selected): selected[x] = \\ (roulette(generation['Cumulative Sum'], rnd())) selected = {'Individuals': [generation['Individuals'][int(selected[x])] for x in range(len(generation['Individuals'])//2)] ,'Fitness': [generation['Fitness'][int(selected[x])] for x in range( len(generation['Individuals'])//2)]} elif method == 'Fittest Half': selected_individuals = [generation['Individuals'][-x-1] for x in range(int(len(generation['Individuals'])//2))] selected_fitnesses = [generation['Fitness'][-x-1] for x in range(int(len(generation['Individuals'])//2))] selected = {'Individuals': selected_individuals, 'Fitness': selected_fitnesses} elif method == 'Random': selected_individuals = \\ [generation['Individuals'] [randint(1,len(generation['Fitness']))] for x in range(int(len(generation['Individuals'])//2))] selected_fitnesses = [generation['Fitness'][-x-1] for x in range(int(len(generation['Individuals'])//2))] selected = {'Individuals': selected_individuals, 'Fitness': selected_fitnesses} return selected" }, { "code": null, "e": 9273, "s": 8834, "text": "Pairing and mating are used as a single operation in most genetic algorithm applications, but for creating simpler functions and to be able to used different mating and paring algorithms easily, the two genetic operations are separated in this application. If there is elitism in the genetic algorithm, the elit must be an input to the function as well as the selected individuals. We are going to discuss three different pairing methods;" }, { "code": null, "e": 9478, "s": 9273, "text": "Fittest: In this method, individuals are paired two by two, starting from the fittest individual. By doing so, fitter individuals are paired together, but less fit individuals are paired together as well." }, { "code": null, "e": 9546, "s": 9478, "text": "Random: In this method, individuals are paired two by two randomly." }, { "code": null, "e": 9695, "s": 9546, "text": "Weighted random: In this method, individuals are paired randomly two by two, but fitter individuals have a higher chance to be selected for pairing." }, { "code": null, "e": 9731, "s": 9695, "text": "Pairing function can be written as;" }, { "code": null, "e": 11033, "s": 9731, "text": "def pairing(elit, selected, method = 'Fittest'): individuals = [elit['Individuals']]+selected['Individuals'] fitness = [elit['Fitness']]+selected['Fitness'] if method == 'Fittest': parents = [[individuals[x],individuals[x+1]] for x in range(len(individuals)//2)] if method == 'Random': parents = [] for x in range(len(individuals)//2): parents.append( [individuals[randint(0,(len(individuals)-1))], individuals[randint(0,(len(individuals)-1))]]) while parents[x][0] == parents[x][1]: parents[x][1] = individuals[ randint(0,(len(individuals)-1))] if method == 'Weighted Random': normalized_fitness = sorted( [fitness[x] /sum(fitness) for x in range(len(individuals)//2)], reverse = True) cummulitive_sum = np.array(normalized_fitness).cumsum() parents = [] for x in range(len(individuals)//2): parents.append( [individuals[roulette(cummulitive_sum,rnd())], individuals[roulette(cummulitive_sum,rnd())]]) while parents[x][0] == parents[x][1]: parents[x][1] = individuals[ roulette(cummulitive_sum,rnd())] return parents" }, { "code": null, "e": 11220, "s": 11033, "text": "We will discuss two different mating methods. In the Python code given below, two selected parent individuals create two offsprings. There are two mating methods we are going to discuss." }, { "code": null, "e": 11350, "s": 11220, "text": "Single point: In this method, genes after a single point are replaced with the genes of the other parent to crate two offsprings." }, { "code": null, "e": 11477, "s": 11350, "text": "Two points: In this method, genes between two points are replaced with the genes of the other parent to create two offsprings." }, { "code": null, "e": 11510, "s": 11477, "text": "Mating function can be coded as;" }, { "code": null, "e": 12355, "s": 11510, "text": "def mating(parents, method='Single Point'): if method == 'Single Point': pivot_point = randint(1, len(parents[0])) offsprings = [parents[0] \\ [0:pivot_point]+parents[1][pivot_point:]] offsprings.append(parents[1] [0:pivot_point]+parents[0][pivot_point:]) if method == 'Two Pionts': pivot_point_1 = randint(1, len(parents[0]-1)) pivot_point_2 = randint(1, len(parents[0])) while pivot_point_2<pivot_point_1: pivot_point_2 = randint(1, len(parents[0])) offsprings = [parents[0][0:pivot_point_1]+ parents[1][pivot_point_1:pivot_point_2]+ [parents[0][pivot_point_2:]]] offsprings.append([parents[1][0:pivot_point_1]+ parents[0][pivot_point_1:pivot_point_2]+ [parents[1][pivot_point_2:]]]) return offsprings" }, { "code": null, "e": 12711, "s": 12355, "text": "The final genetic operation is random mutations. Random mutations occur in the selected individuals and their offsprings to improve variety of the next generation. If there is elitism in the genetic algorithm, elit individual does not go through random mutations so we do not lose the best solution. We are going to discuss two different mutation methods." }, { "code": null, "e": 12872, "s": 12711, "text": "Gauss: In this method, the gene that goes through mutation is replaced with a number that is generated according to gauss distribution around the original gene." }, { "code": null, "e": 12957, "s": 12872, "text": "Reset: In this method, the original gene is replaced with a randomly generated gene." }, { "code": null, "e": 12998, "s": 12957, "text": "The mutation function can be written as;" }, { "code": null, "e": 13695, "s": 12998, "text": "def mutation(individual, upper_limit, lower_limit, muatation_rate=2, method='Reset', standard_deviation = 0.001): gene = [randint(0, 7)] for x in range(muatation_rate-1): gene.append(randint(0, 7)) while len(set(gene)) < len(gene): gene[x] = randint(0, 7) mutated_individual = individual.copy() if method == 'Gauss': for x in range(muatation_rate): mutated_individual[x] = \\ round(individual[x]+gauss(0, standard_deviation), 1) if method == 'Reset': for x in range(muatation_rate): mutated_individual[x] = round(rnd()* \\ (upper_limit-lower_limit)+lower_limit,1) return mutated_individual" }, { "code": null, "e": 13940, "s": 13695, "text": "The next generation is created using the genetic operations we discussed. Elitism can be introduced to the genetic algorithm during the creating of next generation. Elitism is the The python code to create the next generation can be written as;" }, { "code": null, "e": 15454, "s": 13940, "text": "def next_generation(gen, upper_limit, lower_limit): elit = {} next_gen = {} elit['Individuals'] = gen['Individuals'].pop(-1) elit['Fitness'] = gen['Fitness'].pop(-1) selected = selection(gen) parents = pairing(elit, selected) offsprings = [[[mating(parents[x]) for x in range(len(parents))] [y][z] for z in range(2)] for y in range(len(parents))] offsprings1 = [offsprings[x][0] for x in range(len(parents))] offsprings2 = [offsprings[x][1] for x in range(len(parents))] unmutated = selected['Individuals']+offsprings1+offsprings2 mutated = [mutation(unmutated[x], upper_limit, lower_limit) for x in range(len(gen['Individuals']))] unsorted_individuals = mutated + [elit['Individuals']] unsorted_next_gen = \\ [fitness_calculation(mutated[x]) for x in range(len(mutated))] unsorted_fitness = [unsorted_next_gen[x] for x in range(len(gen['Fitness']))] + [elit['Fitness']] sorted_next_gen = \\ sorted([[unsorted_individuals[x], unsorted_fitness[x]] for x in range(len(unsorted_individuals))], key=lambda x: x[1]) next_gen['Individuals'] = [sorted_next_gen[x][0] for x in range(len(sorted_next_gen))] next_gen['Fitness'] = [sorted_next_gen[x][1] for x in range(len(sorted_next_gen))] gen['Individuals'].append(elit['Individuals']) gen['Fitness'].append(elit['Fitness']) return next_gen" }, { "code": null, "e": 15805, "s": 15454, "text": "After a generation is created, termination criteria are used to determine if the genetic algorithm should create another generation or should it stop. Different termination criteria can be used at the same time and if the genetic algorithm satisfies one of the criteria the genetic algorithm stops. We are going to disscuss four termination criteria." }, { "code": null, "e": 16104, "s": 15805, "text": "Maximum fitness : This termination criteria checks if the fittest individual in the current generation satisfies our criteria. Using this termiantion method, desired results can be obtained. As seen from the figure below, maximum fitness limit can be determined to include some of the local minima." }, { "code": null, "e": 16315, "s": 16104, "text": "Maximum average fitness: If we are interested in a set of solutions average values of the individuals in the current generations can be checked to determine if the current generation satisfies our expectations." }, { "code": null, "e": 16429, "s": 16315, "text": "Maximum number of generations: We could limit the maximum number of generations created by the genetic algorithm." }, { "code": null, "e": 16870, "s": 16429, "text": "Maximum similar fitness number: Due to elitism best individual in a generation moves on to the next generation without mutating. This individual can be the best individual in the next generation as well. We can limit the number for the same individual to be the best individual as this can be sing that the genetic algorithm got stuck in a local minima. The function for checking if the maximum fitness value have changed can be written as;" }, { "code": null, "e": 17204, "s": 16870, "text": "def fitness_similarity_chech(max_fitness, number_of_similarity): result = False similarity = 0 for n in range(len(max_fitness)-1): if max_fitness[n] == max_fitness[n+1]: similarity += 1 else: similarity = 0 if similarity == number_of_similarity-1: result = True return result" }, { "code": null, "e": 17385, "s": 17204, "text": "Now that all of the function we need for the genetic algorithm is ready, we can begin the optimization process. To run the genetic algorithm with 20 individuals in each generation;" }, { "code": null, "e": 18698, "s": 17385, "text": "# Generations and fitness values will be written to this fileResult_file = 'GA_Results.txt'# Creating the First Generationdef first_generation(pop): fitness = [fitness_calculation(pop[x]) for x in range(len(pop))] sorted_fitness = sorted([[pop[x], fitness[x]] for x in range(len(pop))], key=lambda x: x[1]) population = [sorted_fitness[x][0] for x in range(len(sorted_fitness))] fitness = [sorted_fitness[x][1] for x in range(len(sorted_fitness))] return {'Individuals': population, 'Fitness': sorted(fitness)}pop = population(20,8,1,0)gen = []gen.append(first_generation(pop))fitness_avg = np.array([sum(gen[0]['Fitness'])/ len(gen[0]['Fitness'])])fitness_max = np.array([max(gen[0]['Fitness'])])res = open(Result_file, 'a')res.write('\\n'+str(gen)+'\\n')res.close()finish = Falsewhile finish == False: if max(fitness_max) > 6: break if max(fitness_avg) > 5: break if fitness_similarity_chech(fitness_max, 50) == True: break gen.append(next_generation(gen[-1],1,0)) fitness_avg = np.append(fitness_avg, sum( gen[-1]['Fitness'])/len(gen[-1]['Fitness'])) fitness_max = np.append(fitness_max, max(gen[-1]['Fitness'])) res = open(Result_file, 'a') res.write('\\n'+str(gen[-1])+'\\n') res.close()" }, { "code": null, "e": 19040, "s": 18698, "text": "Genetic algorithms can be used to solve multi-parameter constraint optimization problems. Like most of optimization algorithms, genetic algorithms can be implemented directly from some libraries like sklearn, but creating the algorithm from scratch gives a perspective on how it works and the algorithm can be tailored to a specific problem." }, { "code": null, "e": 19095, "s": 19040, "text": "Thank you for reading, I hope the article was helpful." }, { "code": null, "e": 19191, "s": 19095, "text": "Genetic algorithms were first proposed by John H. Holland, you can find his original work here;" }, { "code": null, "e": 19264, "s": 19191, "text": "https://mitpress.mit.edu/books/adaptation-natural-and-artificial-systems" } ]
Convert an ArrayList of String to a String array in Java
At first, let us set an ArrayList of string − ArrayList<String> arrList = new ArrayList<String>(); arrList.add("Bentley"); arrList.add("Audi"); arrList.add("Jaguar"); arrList.add("Cadillac"); Now, use toArray() to convert to a string array − int size = arrList.size(); String res[] = arrList.toArray(new String[size]); Following is the program to convert an ArrayList of String to a String array in Java − import java.util.*; public class Demo { public static void main(String[] args) { ArrayList<String> arrList = new ArrayList<String>(); arrList.add("Bentley"); arrList.add("Audi"); arrList.add("Jaguar"); arrList.add("Cadillac"); arrList.add("Mazda"); arrList.add("Land Rover"); arrList.add("Porsche"); int size = arrList.size(); String res[] = arrList.toArray(new String[size]); System.out.println("String Array..."); for(String s: res) { System.out.println(s); } } } String Array... Bentley Audi Jaguar Cadillac Mazda Land Rover Porsche
[ { "code": null, "e": 1108, "s": 1062, "text": "At first, let us set an ArrayList of string −" }, { "code": null, "e": 1254, "s": 1108, "text": "ArrayList<String> arrList = new ArrayList<String>();\narrList.add(\"Bentley\");\narrList.add(\"Audi\");\narrList.add(\"Jaguar\");\narrList.add(\"Cadillac\");" }, { "code": null, "e": 1304, "s": 1254, "text": "Now, use toArray() to convert to a string array −" }, { "code": null, "e": 1381, "s": 1304, "text": "int size = arrList.size();\nString res[] = arrList.toArray(new String[size]);" }, { "code": null, "e": 1468, "s": 1381, "text": "Following is the program to convert an ArrayList of String to a String array in Java −" }, { "code": null, "e": 2027, "s": 1468, "text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<String> arrList = new ArrayList<String>();\n arrList.add(\"Bentley\");\n arrList.add(\"Audi\");\n arrList.add(\"Jaguar\");\n arrList.add(\"Cadillac\");\n arrList.add(\"Mazda\");\n arrList.add(\"Land Rover\");\n arrList.add(\"Porsche\");\n int size = arrList.size();\n String res[] = arrList.toArray(new String[size]);\n System.out.println(\"String Array...\");\n for(String s: res) {\n System.out.println(s);\n }\n }\n}" }, { "code": null, "e": 2097, "s": 2027, "text": "String Array...\nBentley\nAudi\nJaguar\nCadillac\nMazda\nLand Rover\nPorsche" } ]
Programming examples of 6800
Now, in this section, we will see how we can use the Motorola M6800 Microprocessor to add multi-Byte numbers. AddingMulti-Byte Number In this example, we are using 4-Byte numbers (56 2F 7A 89)16 and (21 FB A9 AF)16 In the memory, at first, we are storing the Byte counts, and then the numbers (from least significant Bytes to Most significant Bytes) in different segments. So after storing the data, the memory structure will be looking like this Now, we are writing a program to add these two 4-Byte number and store the result at location 5090H onwards. CLC LDX#$5050 LOOP: LDAA $0, X ADCA $20, X STAA $40, X INX DEC$5000 BNELOOP CLR$40, X BCCDONE INC$40, X DONE: WAI BlockExchange Program Now we will see how we can use the M6800 Microprocessor to Exchange the contents of each element from two different blocks. The number of items in each block is given at location 5000H, and the blocks are at position 5050H and 5070H. So before swapping the items in the memory is looking like this Now, we are writing a program to exchange the block contents. LDX#$5050 LOOP: LDAA 0, X LDAB $20 X STAA $20, X STAB $0, X INX DEC$5000 BNELOOP WAI Move block of data Let us see another example of the M6800 Microprocessor Program. Here the program is to move a block of data to another location. There is one assumption, there is sufficient distance between source and destination. So blocks are not-overlapping. Basically, the block movement is not exactly moving, itis copying the data to other locations. The number of items in the block is given at location 5000H, and the block is located at position 5050H. So before movement, the items in the memory is looking like this. Now, we are writing a program to move the block contents to other locations. LDX#$5050 LOOP: LDAA 0, X STAA $20, X INX DEC$5000 BNELOOP WAI
[ { "code": null, "e": 1172, "s": 1062, "text": "Now, in this section, we will see how we can use the Motorola M6800 Microprocessor to add multi-Byte numbers." }, { "code": null, "e": 1196, "s": 1172, "text": "AddingMulti-Byte Number" }, { "code": null, "e": 1277, "s": 1196, "text": "In this example, we are using 4-Byte numbers (56 2F 7A 89)16 and (21 FB A9 AF)16" }, { "code": null, "e": 1509, "s": 1277, "text": "In the memory, at first, we are storing the Byte counts, and then the numbers (from least significant Bytes to Most significant Bytes) in different segments. So after storing the data, the memory structure will be looking like this" }, { "code": null, "e": 1618, "s": 1509, "text": "Now, we are writing a program to add these two 4-Byte number and store the result at location 5090H onwards." }, { "code": null, "e": 1797, "s": 1618, "text": " CLC\n LDX#$5050\n\nLOOP: LDAA $0, X\n ADCA $20, X\n STAA $40, X\n\n\n INX\n DEC$5000\n BNELOOP\n\n CLR$40, X\n BCCDONE\n INC$40, X\nDONE: WAI\n" }, { "code": null, "e": 1819, "s": 1797, "text": "BlockExchange Program" }, { "code": null, "e": 1943, "s": 1819, "text": "Now we will see how we can use the M6800 Microprocessor to Exchange the contents of each element from two different blocks." }, { "code": null, "e": 2053, "s": 1943, "text": "The number of items in each block is given at location 5000H, and the blocks are at position 5050H and 5070H." }, { "code": null, "e": 2117, "s": 2053, "text": "So before swapping the items in the memory is looking like this" }, { "code": null, "e": 2179, "s": 2117, "text": "Now, we are writing a program to exchange the block contents." }, { "code": null, "e": 2320, "s": 2179, "text": " LDX#$5050\n \nLOOP: LDAA 0, X\n LDAB $20 X\n\n STAA $20, X\n STAB $0, X\n\n INX\n DEC$5000\n BNELOOP\n WAI" }, { "code": null, "e": 2339, "s": 2320, "text": "Move block of data" }, { "code": null, "e": 2680, "s": 2339, "text": "Let us see another example of the M6800 Microprocessor Program. Here the program is to move a block of data to another location. There is one assumption, there is sufficient distance between source and destination. So blocks are not-overlapping. Basically, the block movement is not exactly moving, itis copying the data to other locations." }, { "code": null, "e": 2785, "s": 2680, "text": "The number of items in the block is given at location 5000H, and the block is located at position 5050H." }, { "code": null, "e": 2851, "s": 2785, "text": "So before movement, the items in the memory is looking like this." }, { "code": null, "e": 2928, "s": 2851, "text": "Now, we are writing a program to move the block contents to other locations." }, { "code": null, "e": 2998, "s": 2928, "text": "LDX#$5050\nLOOP: LDAA 0, X\nSTAA $20, X\nINX\nDEC$5000\nBNELOOP\n\n WAI" } ]
Create a BigDecimal via string in Java
Let us see how we can create BigDecimal values via string. Here, we have set string as a parameter to the BigDecimal constructor. BigDecimal val1 = new BigDecimal("375789755.345778656"); BigDecimal val2 = new BigDecimal("525678755.155778656"); We can also perform mathematical operations on it − val2 = val2.subtract(val1); The following is an example − Live Demo import java.math.BigDecimal; public class Demo { public static void main(String[] argv) throws Exception { BigDecimal val1 = new BigDecimal("375789755.345778656"); BigDecimal val2 = new BigDecimal("525678755.155778656"); System.out.println("Value 1 : "+val1); System.out.println("Value 2 : "+val2); val2 = val2.subtract(val1); System.out.println("Result (Subtraction) = "+val2); } } Value 1 : 375789755.345778656 Value 2 : 525678755.155778656 Result (Subtraction) = 149888999.810000000
[ { "code": null, "e": 1192, "s": 1062, "text": "Let us see how we can create BigDecimal values via string. Here, we have set string as a parameter to the BigDecimal constructor." }, { "code": null, "e": 1306, "s": 1192, "text": "BigDecimal val1 = new BigDecimal(\"375789755.345778656\");\nBigDecimal val2 = new BigDecimal(\"525678755.155778656\");" }, { "code": null, "e": 1358, "s": 1306, "text": "We can also perform mathematical operations on it −" }, { "code": null, "e": 1386, "s": 1358, "text": "val2 = val2.subtract(val1);" }, { "code": null, "e": 1416, "s": 1386, "text": "The following is an example −" }, { "code": null, "e": 1427, "s": 1416, "text": " Live Demo" }, { "code": null, "e": 1852, "s": 1427, "text": "import java.math.BigDecimal;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n BigDecimal val1 = new BigDecimal(\"375789755.345778656\");\n BigDecimal val2 = new BigDecimal(\"525678755.155778656\");\n System.out.println(\"Value 1 : \"+val1);\n System.out.println(\"Value 2 : \"+val2);\n val2 = val2.subtract(val1);\n System.out.println(\"Result (Subtraction) = \"+val2);\n }\n}" }, { "code": null, "e": 1955, "s": 1852, "text": "Value 1 : 375789755.345778656\nValue 2 : 525678755.155778656\nResult (Subtraction) = 149888999.810000000" } ]
Electron - Packaging Apps
Packaging and distributing apps is an integral part of the development process of a desktop application. Since Electron is a cross-platform desktop application development framework, packaging and distribution of apps for all the platforms should also be a seamless experience. The electron community has created a project, electron-packager that takes care of the same for us. It allows us to package and distribute our Electron app with OS-specific bundles (.app, .exe etc) via JS or CLI. Electron Packager runs on the following host platforms − Windows (32/64 bit) OS X Linux (x86/x86_64) It generates executables/bundles for the following target platforms − Windows (also known as win32, for both 32/64 bit) OS X (also known as darwin) / Mac App Store (also known as mas) Linux (for x86, x86_64, and armv7l architectures) Install the electron packager using − # for use in npm scripts $ npm install electron-packager --save-dev # for use from cli $ npm install electron-packager -g In this section, we will see how to run the packager from the command line. The basic form of the command is − electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...] This will − Find or download the correct release of Electron. Find or download the correct release of Electron. Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>. Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>. --platform and --arch can be omitted, in two cases. If you specify --all instead, bundles for all valid combinations of target platforms/architectures will be created. Otherwise, a single bundle for the host platform/architecture will be created. 251 Lectures 35.5 hours Gowthami Swarna 9 Lectures 41 mins Ashraf Said 8 Lectures 32 mins Ashraf Said 25 Lectures 1 hours Ashraf Said 17 Lectures 1 hours Ashraf Said 8 Lectures 25 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2343, "s": 2065, "text": "Packaging and distributing apps is an integral part of the development process of a desktop application. Since Electron is a cross-platform desktop application development framework, packaging and distribution of apps for all the platforms should also be a seamless experience." }, { "code": null, "e": 2556, "s": 2343, "text": "The electron community has created a project, electron-packager that takes care of the same for us. It allows us to package and distribute our Electron app with OS-specific bundles (.app, .exe etc) via JS or CLI." }, { "code": null, "e": 2613, "s": 2556, "text": "Electron Packager runs on the following host platforms −" }, { "code": null, "e": 2633, "s": 2613, "text": "Windows (32/64 bit)" }, { "code": null, "e": 2638, "s": 2633, "text": "OS X" }, { "code": null, "e": 2657, "s": 2638, "text": "Linux (x86/x86_64)" }, { "code": null, "e": 2727, "s": 2657, "text": "It generates executables/bundles for the following target platforms −" }, { "code": null, "e": 2777, "s": 2727, "text": "Windows (also known as win32, for both 32/64 bit)" }, { "code": null, "e": 2841, "s": 2777, "text": "OS X (also known as darwin) / Mac App Store (also known as mas)" }, { "code": null, "e": 2891, "s": 2841, "text": "Linux (for x86, x86_64, and armv7l architectures)" }, { "code": null, "e": 2929, "s": 2891, "text": "Install the electron packager using −" }, { "code": null, "e": 3053, "s": 2929, "text": "# for use in npm scripts\n$ npm install electron-packager --save-dev\n\n# for use from cli\n$ npm install electron-packager -g\n" }, { "code": null, "e": 3164, "s": 3053, "text": "In this section, we will see how to run the packager from the command line. The basic form of the command is −" }, { "code": null, "e": 3261, "s": 3164, "text": "electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]\n" }, { "code": null, "e": 3273, "s": 3261, "text": "This will −" }, { "code": null, "e": 3323, "s": 3273, "text": "Find or download the correct release of Electron." }, { "code": null, "e": 3373, "s": 3323, "text": "Find or download the correct release of Electron." }, { "code": null, "e": 3466, "s": 3373, "text": "Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>." }, { "code": null, "e": 3559, "s": 3466, "text": "Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>." }, { "code": null, "e": 3806, "s": 3559, "text": "--platform and --arch can be omitted, in two cases. If you specify --all instead, bundles for all valid combinations of target platforms/architectures will be created. Otherwise, a single bundle for the host platform/architecture will be created." }, { "code": null, "e": 3843, "s": 3806, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 3860, "s": 3843, "text": " Gowthami Swarna" }, { "code": null, "e": 3891, "s": 3860, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 3904, "s": 3891, "text": " Ashraf Said" }, { "code": null, "e": 3935, "s": 3904, "text": "\n 8 Lectures \n 32 mins\n" }, { "code": null, "e": 3948, "s": 3935, "text": " Ashraf Said" }, { "code": null, "e": 3981, "s": 3948, "text": "\n 25 Lectures \n 1 hours \n" }, { "code": null, "e": 3994, "s": 3981, "text": " Ashraf Said" }, { "code": null, "e": 4027, "s": 3994, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4040, "s": 4027, "text": " Ashraf Said" }, { "code": null, "e": 4071, "s": 4040, "text": "\n 8 Lectures \n 25 mins\n" }, { "code": null, "e": 4084, "s": 4071, "text": " Ashraf Said" }, { "code": null, "e": 4091, "s": 4084, "text": " Print" }, { "code": null, "e": 4102, "s": 4091, "text": " Add Notes" } ]
Explain the difference between undefined and not defined in JavaScript - GeeksforGeeks
18 Aug, 2021 In JavaScript, they both are related to memory space and there is a very simple difference between them. If the variable name which is being accessed doesn’t exist in memory space then it would be not defined, and if exists in memory space but hasn’t been assigned any value till now, then it would be undefined. undefined: It is a JavaScript keyword that has a special meaning. Everything which gets a space in memory will contain undefined until we assign a value to that memory space. Let’s understand how the JavaScript code is being executed to see a more clear picture. Everything in JavaScript happens inside the execution context. Execution context is the little separate section where code is being executed and variables get their memory space.The JavaScript code is being executed in two-phase, The first one is the memory allocation phase during this all the variables and function definitions get stored inside the memory heap. The JavaScript assigns undefined to each variable in this phase.The second one is a thread of the execution phase, during this the code written inside the JavaScript file is being executed.Each variable holds the value undefined till the program reaches the line where we have assigned that variable. After that line, the variable’s undefined value gets replaced by the original value. The first one is the memory allocation phase during this all the variables and function definitions get stored inside the memory heap. The JavaScript assigns undefined to each variable in this phase. The second one is a thread of the execution phase, during this the code written inside the JavaScript file is being executed.Each variable holds the value undefined till the program reaches the line where we have assigned that variable. After that line, the variable’s undefined value gets replaced by the original value. Example 1: The global execution context will be created and in the memory allocation phase, the var a will get space in memory, and JavaScript will assign undefined to it. During the thread of execution, the JavaScript will encounter the first line console.log(a) and as we haven’t assigned the value for a, undefined will be printed on the console. In the next line, we have assigned 5 to a, hence the variable a is no more undefined. Now it contains the value 5. So next time whenever we access the variable a, it won’t be evaluated as undefined. So it will print the actual value of a. HTML <script> console.log(a); var a = 5; console.log(a);</script> Output (In console): undefined 5 Additional Points: If you are assigning a function call to a variable, and that function doesn’t return anything, the variable will become undefined.You can explicitly assign undefined to any variable but it is not good practice to use language keywords in the way it is not expected. If you are assigning a function call to a variable, and that function doesn’t return anything, the variable will become undefined. You can explicitly assign undefined to any variable but it is not good practice to use language keywords in the way it is not expected. not defined: In JavaScript, it is one of the reference errors that JavaScript will throw when someone accesses the variable which is not inside the memory heap. Example 2: First of all, global execution context will be created and in the memory allocation phase, the variable “a” will get space in memory, and by default, JavaScript assigns undefined to “a”. During the thread of execution, the “console.log(a)” will be printed as undefined. In the next line, we have assigned 5 to variable a. In the console, 5 will be printed. At the last line when JavaScript encounters the “console.log(b)” it searches for “b” inside the memory heap of execution context but it is not available, the JS engine will throw the “Reference Error” with a message of “b is not defined“. The JavaScript will stop execution when it encounters a reference error. HTML <script> console.log(a); var a = 5; console.log(a); console.log(b);</script> Output: Difference between undefined and not defined JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n18 Aug, 2021" }, { "code": null, "e": 25222, "s": 24909, "text": "In JavaScript, they both are related to memory space and there is a very simple difference between them. If the variable name which is being accessed doesn’t exist in memory space then it would be not defined, and if exists in memory space but hasn’t been assigned any value till now, then it would be undefined." }, { "code": null, "e": 25397, "s": 25222, "text": "undefined: It is a JavaScript keyword that has a special meaning. Everything which gets a space in memory will contain undefined until we assign a value to that memory space." }, { "code": null, "e": 25716, "s": 25397, "text": "Let’s understand how the JavaScript code is being executed to see a more clear picture. Everything in JavaScript happens inside the execution context. Execution context is the little separate section where code is being executed and variables get their memory space.The JavaScript code is being executed in two-phase, " }, { "code": null, "e": 26237, "s": 25716, "text": "The first one is the memory allocation phase during this all the variables and function definitions get stored inside the memory heap. The JavaScript assigns undefined to each variable in this phase.The second one is a thread of the execution phase, during this the code written inside the JavaScript file is being executed.Each variable holds the value undefined till the program reaches the line where we have assigned that variable. After that line, the variable’s undefined value gets replaced by the original value." }, { "code": null, "e": 26437, "s": 26237, "text": "The first one is the memory allocation phase during this all the variables and function definitions get stored inside the memory heap. The JavaScript assigns undefined to each variable in this phase." }, { "code": null, "e": 26759, "s": 26437, "text": "The second one is a thread of the execution phase, during this the code written inside the JavaScript file is being executed.Each variable holds the value undefined till the program reaches the line where we have assigned that variable. After that line, the variable’s undefined value gets replaced by the original value." }, { "code": null, "e": 27348, "s": 26759, "text": "Example 1: The global execution context will be created and in the memory allocation phase, the var a will get space in memory, and JavaScript will assign undefined to it. During the thread of execution, the JavaScript will encounter the first line console.log(a) and as we haven’t assigned the value for a, undefined will be printed on the console. In the next line, we have assigned 5 to a, hence the variable a is no more undefined. Now it contains the value 5. So next time whenever we access the variable a, it won’t be evaluated as undefined. So it will print the actual value of a." }, { "code": null, "e": 27353, "s": 27348, "text": "HTML" }, { "code": "<script> console.log(a); var a = 5; console.log(a);</script>", "e": 27417, "s": 27353, "text": null }, { "code": null, "e": 27440, "s": 27419, "text": "Output (In console):" }, { "code": null, "e": 27452, "s": 27440, "text": "undefined\n5" }, { "code": null, "e": 27471, "s": 27452, "text": "Additional Points:" }, { "code": null, "e": 27737, "s": 27471, "text": "If you are assigning a function call to a variable, and that function doesn’t return anything, the variable will become undefined.You can explicitly assign undefined to any variable but it is not good practice to use language keywords in the way it is not expected." }, { "code": null, "e": 27868, "s": 27737, "text": "If you are assigning a function call to a variable, and that function doesn’t return anything, the variable will become undefined." }, { "code": null, "e": 28004, "s": 27868, "text": "You can explicitly assign undefined to any variable but it is not good practice to use language keywords in the way it is not expected." }, { "code": null, "e": 28165, "s": 28004, "text": "not defined: In JavaScript, it is one of the reference errors that JavaScript will throw when someone accesses the variable which is not inside the memory heap." }, { "code": null, "e": 28845, "s": 28165, "text": "Example 2: First of all, global execution context will be created and in the memory allocation phase, the variable “a” will get space in memory, and by default, JavaScript assigns undefined to “a”. During the thread of execution, the “console.log(a)” will be printed as undefined. In the next line, we have assigned 5 to variable a. In the console, 5 will be printed. At the last line when JavaScript encounters the “console.log(b)” it searches for “b” inside the memory heap of execution context but it is not available, the JS engine will throw the “Reference Error” with a message of “b is not defined“. The JavaScript will stop execution when it encounters a reference error." }, { "code": null, "e": 28850, "s": 28845, "text": "HTML" }, { "code": "<script> console.log(a); var a = 5; console.log(a); console.log(b);</script>", "e": 28931, "s": 28850, "text": null }, { "code": null, "e": 28939, "s": 28931, "text": "Output:" }, { "code": null, "e": 28984, "s": 28939, "text": "Difference between undefined and not defined" }, { "code": null, "e": 29005, "s": 28984, "text": "JavaScript-Questions" }, { "code": null, "e": 29012, "s": 29005, "text": "Picked" }, { "code": null, "e": 29023, "s": 29012, "text": "JavaScript" }, { "code": null, "e": 29040, "s": 29023, "text": "Web Technologies" }, { "code": null, "e": 29138, "s": 29040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29147, "s": 29138, "text": "Comments" }, { "code": null, "e": 29160, "s": 29147, "text": "Old Comments" }, { "code": null, "e": 29221, "s": 29160, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29262, "s": 29221, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29302, "s": 29262, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29356, "s": 29302, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29418, "s": 29356, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 29474, "s": 29418, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29507, "s": 29474, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29569, "s": 29507, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29612, "s": 29569, "text": "How to fetch data from an API in ReactJS ?" } ]
Perl substr Function
This function returns a substring of EXPR, starting at OFFSET within the string. If OFFSET is negative, starts that many characters from the end of the string. If LEN is specified, returns that number of bytes, or all bytes up until end-of-string if not specified. If LEN is negative, leaves that many characters off the end of the string. If REPLACEMENT is specified, replaces the substring with the REPLACEMENT string. If you specify a substring that passes beyond the end of the string, it returns only the valid element of the original string. Following is the simple syntax for this function − substr EXPR, OFFSET, LEN, REPLACEMENT substr EXPR, OFFSET, LEN substr EXPR, OFFSET This function returns string. Following is the example code showing its basic usage − #!/usr/bin/perl -w $temp = substr("okay", 2); print "Substring valuye is $temp\n"; $temp = substr("okay", 1,2); print "Substring valuye is $temp\n"; When above code is executed, it produces the following result − Substring valuye is ay Substring valuye is ka 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2560, "s": 2220, "text": "This function returns a substring of EXPR, starting at OFFSET within the string. If OFFSET is negative, starts that many characters from the end of the string. If LEN is specified, returns that number of bytes, or all bytes up until end-of-string if not specified. If LEN is negative, leaves that many characters off the end of the string." }, { "code": null, "e": 2641, "s": 2560, "text": "If REPLACEMENT is specified, replaces the substring with the REPLACEMENT string." }, { "code": null, "e": 2768, "s": 2641, "text": "If you specify a substring that passes beyond the end of the string, it returns only the valid element of the original string." }, { "code": null, "e": 2819, "s": 2768, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2905, "s": 2819, "text": "substr EXPR, OFFSET, LEN, REPLACEMENT\n\nsubstr EXPR, OFFSET, LEN\n\nsubstr EXPR, OFFSET\n" }, { "code": null, "e": 2935, "s": 2905, "text": "This function returns string." }, { "code": null, "e": 2991, "s": 2935, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 3142, "s": 2991, "text": "#!/usr/bin/perl -w\n\n$temp = substr(\"okay\", 2);\nprint \"Substring valuye is $temp\\n\";\n\n$temp = substr(\"okay\", 1,2);\nprint \"Substring valuye is $temp\\n\";" }, { "code": null, "e": 3206, "s": 3142, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 3253, "s": 3206, "text": "Substring valuye is ay\nSubstring valuye is ka\n" }, { "code": null, "e": 3288, "s": 3253, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3302, "s": 3288, "text": " Devi Killada" }, { "code": null, "e": 3337, "s": 3302, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3357, "s": 3337, "text": " Harshit Srivastava" }, { "code": null, "e": 3390, "s": 3357, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3406, "s": 3390, "text": " TELCOMA Global" }, { "code": null, "e": 3439, "s": 3406, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3456, "s": 3439, "text": " Mohammad Nauman" }, { "code": null, "e": 3489, "s": 3456, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3512, "s": 3489, "text": " Stone River ELearning" }, { "code": null, "e": 3547, "s": 3512, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3570, "s": 3547, "text": " Stone River ELearning" }, { "code": null, "e": 3577, "s": 3570, "text": " Print" }, { "code": null, "e": 3588, "s": 3577, "text": " Add Notes" } ]
Data Link Layer in OSI Model - GeeksforGeeks
28 Jun, 2021 Below are some common GATE CS topics of data link layer. Carrier Sense Multiple Access (CSMA) Carrier Sense Multiple Access or CSMA method was developed to minimize the probability of collision and thus, to increase the performance. The probability of collision can be minimized if a station senses or reads the medium before trying to use it for sending data. CSMA is based on the principle of sensing before transmitting. CSMA/CD (Carrier sense multiple access with collision detection)The CSMA method does not tells us what to do in case there is a collision. Carrier sense multiple access with collision detection (CSMA/CD) adds on to the CSMA algorithm to deal with collision. For CSMA/CD to work, we need a particular frame size. Before sending the last bit of the frame, the sending station must detect a collision, if any, and abort the transmission because the station, once the entire frame is sent, does not keep a copy of the frame and does not monitor the channel for collision detection. In CSMA/CD, the size of a frame must be large enough so that collision can be detected by sender while sending the frame. So, the frame transmission delay must be at least two times the maximum propagation delay. Tt >= 2*Tp Here Tt is transmission delay and Tp is propagation delay. Tt = S/B Here S is size of frame and B is bandwidth or transmission speed. Tp = L/P Here L is distance between the farthest nodes and P is propagation speed, putting above values we get S/B >= 2*(L/P) Frame size 'S' should be S >= 2BL/P Or cable length 'L' should be L <= SP/2B Example: A network using CSMA/CD has a bandwidth of 10 Mbps. If the maximum propagation time including the device delays is 25.6 μs, what is the minimum size of the frame?Solution: Frame Transmission Time, Tt = 2 * Tp = 2 * 25.6 = 51.2 μsMinimum frame size, S = 10 Mbps * 51.2 μs = 512 bits = 64 bytes Below questions have been asked in previous GATE exam on above topic. GATE | GATE CS 2003 | Question 90 GATE | GATE-CS-2005 | Question 74GATE | GATE CS 2013 | Question 65 GATE | GATE CS 2015 Set 3 | Question 65 CRC (Cyclic Redundancy Check)Please refer this for examples and detailed explanation. GATE | GATE-CS-2007 | Question 68GATE | GATE CS 2009 | Question 48 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GTest Framework How to use gotoxy() in codeblocks? Asymptotic Notations and how to calculate them File globbing in Linux Print all subsequences of a string using ArrayList HQL | Introduction Construct an array from its pair-sum array Draw a circle without floating point arithmetic MAQ Software most Frequently Asked Questions What's difference between Microcontroller (μC) and Microprocessor (μP)?
[ { "code": null, "e": 24543, "s": 24515, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24600, "s": 24543, "text": "Below are some common GATE CS topics of data link layer." }, { "code": null, "e": 24637, "s": 24600, "text": "Carrier Sense Multiple Access (CSMA)" }, { "code": null, "e": 24967, "s": 24637, "text": "Carrier Sense Multiple Access or CSMA method was developed to minimize the probability of collision and thus, to increase the performance. The probability of collision can be minimized if a station senses or reads the medium before trying to use it for sending data. CSMA is based on the principle of sensing before transmitting." }, { "code": null, "e": 25545, "s": 24967, "text": "CSMA/CD (Carrier sense multiple access with collision detection)The CSMA method does not tells us what to do in case there is a collision. Carrier sense multiple access with collision detection (CSMA/CD) adds on to the CSMA algorithm to deal with collision. For CSMA/CD to work, we need a particular frame size. Before sending the last bit of the frame, the sending station must detect a collision, if any, and abort the transmission because the station, once the entire frame is sent, does not keep a copy of the frame and does not monitor the channel for collision detection." }, { "code": null, "e": 25758, "s": 25545, "text": "In CSMA/CD, the size of a frame must be large enough so that collision can be detected by sender while sending the frame. So, the frame transmission delay must be at least two times the maximum propagation delay." }, { "code": null, "e": 25774, "s": 25758, "text": " \n\n Tt >= 2*Tp" }, { "code": null, "e": 25833, "s": 25774, "text": "Here Tt is transmission delay and Tp is propagation delay." }, { "code": null, "e": 25846, "s": 25833, "text": " \nTt = S/B" }, { "code": null, "e": 25912, "s": 25846, "text": "Here S is size of frame and B is bandwidth or transmission speed." }, { "code": null, "e": 25925, "s": 25912, "text": " \n Tp = L/P" }, { "code": null, "e": 26027, "s": 25925, "text": "Here L is distance between the farthest nodes and P is propagation speed, putting above values we get" }, { "code": null, "e": 26132, "s": 26027, "text": " \nS/B >= 2*(L/P)\n\nFrame size 'S' should be \n S >= 2BL/P \n\nOr cable length 'L' should be\n L <= SP/2B" }, { "code": null, "e": 26434, "s": 26132, "text": "Example: A network using CSMA/CD has a bandwidth of 10 Mbps. If the maximum propagation time including the device delays is 25.6 μs, what is the minimum size of the frame?Solution: Frame Transmission Time, Tt = 2 * Tp = 2 * 25.6 = 51.2 μsMinimum frame size, S = 10 Mbps * 51.2 μs = 512 bits = 64 bytes" }, { "code": null, "e": 26504, "s": 26434, "text": "Below questions have been asked in previous GATE exam on above topic." }, { "code": null, "e": 26538, "s": 26504, "text": "GATE | GATE CS 2003 | Question 90" }, { "code": null, "e": 26605, "s": 26538, "text": "GATE | GATE-CS-2005 | Question 74GATE | GATE CS 2013 | Question 65" }, { "code": null, "e": 26645, "s": 26605, "text": "GATE | GATE CS 2015 Set 3 | Question 65" }, { "code": null, "e": 26733, "s": 26647, "text": "CRC (Cyclic Redundancy Check)Please refer this for examples and detailed explanation." }, { "code": null, "e": 26800, "s": 26733, "text": "GATE | GATE-CS-2007 | Question 68GATE | GATE CS 2009 | Question 48" }, { "code": null, "e": 26924, "s": 26800, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 26933, "s": 26924, "text": "Articles" }, { "code": null, "e": 27031, "s": 26933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27040, "s": 27031, "text": "Comments" }, { "code": null, "e": 27053, "s": 27040, "text": "Old Comments" }, { "code": null, "e": 27069, "s": 27053, "text": "GTest Framework" }, { "code": null, "e": 27104, "s": 27069, "text": "How to use gotoxy() in codeblocks?" }, { "code": null, "e": 27151, "s": 27104, "text": "Asymptotic Notations and how to calculate them" }, { "code": null, "e": 27174, "s": 27151, "text": "File globbing in Linux" }, { "code": null, "e": 27225, "s": 27174, "text": "Print all subsequences of a string using ArrayList" }, { "code": null, "e": 27244, "s": 27225, "text": "HQL | Introduction" }, { "code": null, "e": 27287, "s": 27244, "text": "Construct an array from its pair-sum array" }, { "code": null, "e": 27335, "s": 27287, "text": "Draw a circle without floating point arithmetic" }, { "code": null, "e": 27380, "s": 27335, "text": "MAQ Software most Frequently Asked Questions" } ]
3 Ways To Create Tables With Apache Spark | by AnBento | Towards Data Science
A few of my readers have contacted me asking for on-demand courses to learn more about Apache Spark. These are 3 great resources I would recommend: Data Streaming With Apache Kafka & Apache Spark Nanodegree (Udacity) Data Engineering Nanodegree (Udacity) Distributed Computing With Spark SQL (Coursera) Apache Spark is a distributed data processing engine that allows you to create two main types of tables: Managed (or Internal) Tables: for these tables, Spark manages both the data and the metadata. In particular, data is usually saved in the Spark SQL warehouse directory - that is the default for managed tables - whereas metadata is saved in a meta-store of relational entities (including databases, tables, temporary views) and can be accessed through an interface known as the “catalog”.Unmanaged (or External) Tables: for these tables, Spark only manages the metadata, but requires you to specify the exact location where you wish to save the table or, alternatively, the source directory from which data will be pulled to create a table. Managed (or Internal) Tables: for these tables, Spark manages both the data and the metadata. In particular, data is usually saved in the Spark SQL warehouse directory - that is the default for managed tables - whereas metadata is saved in a meta-store of relational entities (including databases, tables, temporary views) and can be accessed through an interface known as the “catalog”. Unmanaged (or External) Tables: for these tables, Spark only manages the metadata, but requires you to specify the exact location where you wish to save the table or, alternatively, the source directory from which data will be pulled to create a table. Moreover, because of their different purpose: if you delete a managed table, Spark will delete both the table data in the warehouse and the metadata in the meta-store, meaning that you will neither be able to query the table directly or to retrieve data into it. if you delete an unmanaged table, Spark will just delete the metadata, meaning that you won’t be able to query the table anymore, as your query won’t be resolved against the catalog in the execution analysis phase; but you will still find the tables you created in the external location. In this tutorial, I will share three methods to create managed and unmanaged tables and explain the cases when it make sense to use one or the other. medium.com towardsdatascience.com If you wish to follow along, but are relatively new to Spark and don’t have a better option, I would strongly suggest to use Databrick’s community edition as it gives you access to a cluster with 15GB of memory and 2 Cores to execute Spark code. The sales_redords dataset I am going to use, is quite big (600MB) as it includes 5 million rows and 14 columns - you can download it here. I chose a sizable dataset to - at least partially - replicate the volume of data you will have to deal with in the real world. Because the dataset comes in a semi-structured CSV format, in order to create a DataFrame in your SparkSession, make sure to upload the original file in the /FileStore/ directory in the DataBricks File System (DBFS) first, then run the following code: To simulate the cleaning process that raw data would undergo as part of a daily ETL pipeline, let’s suppose that you wished to: Convert the original column names to lowercase and replace blanks “ ” with and underscore “_”; Convert the original “Order Date” from STRING to DATE and the original “Units Sold”, “Unit Price” and “Total Revenue” from STRING to FLOAT ; Drop the following columns as they are not required by your stakeholders: [“Region”, “Country”, “Order Priority”, “Ship Date”, “Total Profit”, “Total Cost”, “Unit Cost”]; Remove duplicates in the original “Order ID” field. This can be achieved executing the code below, that creates a new DataFrame named df_final that only includes 7 columns and 2M rows.( first 5 rows are also displayed ): The df_final has been manipulated to obtain the preferred result and it’s now ready to be used as a source to create tables. However, in order to show you all 3 different methods, I also had to make df_final available as a temporary view and as parquet file (split in 2 partitions) in the DBFS : As mentioned, when you create a managed table, Spark will manage both the table data and the metadata (information about the table itself). In particular data is written to the default Hive warehouse, that is set in the /user/hive/warehouse location. You can change this behavior, using the spark.sql.warehouse.dir configuration while generating a SparkSession . towardsdatascience.com The most straightforward way to create a managed table is to write the df_final through the Structured API saveAsTable() method, without specifying any paths: You can check that the command successfully created a permanent table named salesTable_manag1 with tableType = 'MANAGED' by running: spark.catalog.listTables()Out[1]: [Table(name=’salestable_manag1', database=’default’, description=None, tableType=’MANAGED’, isTemporary=False) You should prefer this method in most cases, as its syntax is very compact and readable and avoids you the additional step of creating a temp view in memory. An alternative way to create a managed table is to run a SQL command that queries all the records in the temp df_final_View: In this case I used the %sql magic in Databricks to run a SQL command directly, without wrapping it into spark.sql() . However, you can achieve the exact same result with the syntax: spark.sql(“CREATE TABLE IF NOT EXISTS salesTable_manag2 AS SELECT * FROM df_final_View”) If you have a SQL background, this method is probably the most familiar, as you don’t need to bother with the “standard” Structured API syntax and can even perform additional manipulation on the fly. However, while working with big data, you should take into account the extra space required to create a temp view on your cluster. The last method you can use, is similar to the previous one, but it involves two steps as you first create a the table salesTable_manag3 and then insert data into it by querying the temp view: You should opt for this method when you wish to change the column types, or if you already created a table and want to replace or append data into it instead of deleting it and start from scratch. Unmanaged tables provide much more flexibility, as the table data can be stored in a location of your choice, or the table can be built directly on top of data available in an external directory. In turn, this means that in Spark, a location is mandatory for external tables. Metadata is again saved in the meta-store and accessible through the catalog. Unmanaged tables provide much more flexibility, as the table data can be stored in a location of your choice, or the table can be built directly on top of data available in an external directory. In the example below, I am going to use Databricks File System to to simulate an external location with respect to the default Spark SQL warehouse, but of course, it is possible to save unmanaged tables (or create them on top of) every file system compatible with Spark, including cloud data warehouses. To create an unmanaged (external) table you can simply specify a path before the saveAsTable() method: When you run this code, Spark will: Shuffle data in the df_final DataFrame to create 2 partitions and write these to the/FileStore/tables/salesTable_unmanag1 directory. Create an external table named salesTable_unmanag1 using the partitions stored at that location and save relevant information in the meta-store. As similar result can be obtained by specifying the location as part of a SQL query. In this case your will need to use the temp view as a data source: Also remember to use the CREATE EXTERNAL TABLE syntax instead of CREATE TABLE . Finally, if the data you intend to use to create the table, is already available in an external location, you can simply build the table on the top of it by pointing to the location through the USING format OPTIONS (path 'path to location') syntax: In this case, the table is created on the top of the df_final.parquet file that I saved in the FileStore after manipulating the original dataset. Note that if you use this method, you will need to specify the type of each column. If you try to list the tables in the catalog again: spark.catalog.listTables() You can see that now the output includes 6 tables of which 3 managed and 3 unmanaged, together with the temp view created at the beginning: Executing the following code will delete metadata from both type of tables and data from managed tables only, whereas data will be preserved in the external locations you specified: However, after erasing metadata you won’t be able to run queries against any of the tables. By now, you should have a solid grasp of the differences between these two types of table and should be ready to apply the code above to your specific use cases. However, perhaps you are still a bit confused when it comes to choose between one of the two, while working on a real project. In general, you should store data in a MANAGED table: When you wish to use Spark as a database to perform ad hoc or interactive queries to explore and visualize data sets → for instance, you could devise an ETL pipeline in Spark that eventually stores data in a managed table and then use a JDBC-ODBC connector to query this table via Looker, Tableau, Power BI and other BI Tools.When you are working on a project and wish to temporarily save data in Spark for additional manipulation or testing, before writing it to the final location → for instance, managed tables could be handy while building, training and evaluating machine learning models in Spark, as they remove the need for an external storage to save partial iterations.When you wish for Spark to take care of the complete lifecycle of the table data including its deletion or are concerned about security in the external file system → if data does not need to be shared with other clients immediately or there are security concerns, then saving data in the Spark warehouse could be a valid temporary solution.When you are not worried about data reproducibility → if data can easily be retrieved from other sources or the computational effort that takes to transform it is not too extensive, then the risk of erroneously drop a managed table is more contained. When you wish to use Spark as a database to perform ad hoc or interactive queries to explore and visualize data sets → for instance, you could devise an ETL pipeline in Spark that eventually stores data in a managed table and then use a JDBC-ODBC connector to query this table via Looker, Tableau, Power BI and other BI Tools. When you are working on a project and wish to temporarily save data in Spark for additional manipulation or testing, before writing it to the final location → for instance, managed tables could be handy while building, training and evaluating machine learning models in Spark, as they remove the need for an external storage to save partial iterations. When you wish for Spark to take care of the complete lifecycle of the table data including its deletion or are concerned about security in the external file system → if data does not need to be shared with other clients immediately or there are security concerns, then saving data in the Spark warehouse could be a valid temporary solution. When you are not worried about data reproducibility → if data can easily be retrieved from other sources or the computational effort that takes to transform it is not too extensive, then the risk of erroneously drop a managed table is more contained. You should instead store data in an EXTERNAL table: When you cannot create a table based on an existing DataFrame or view already available in your SparkSession, that comes with an inferred schema → in this case you must provide a preferred location and specify the correct field types.When Spark is mainly employed to process large data sets in parallel, by distributing them across a cluster, or to implement end-to-end data pipelines through batches or streams→ in this case Spark is generally used for the computational heavy lifting, but data is eventually stored into an external data-lake or written to the final cloud data warehouse.When data needs to remain in the specified external location even after deleting the unmanaged table in Spark→ this is often the case when there are multiple tables or schemas that are built on the top of the same data and you don’t wish to jeopardize their integrity.When Spark should not own data lifecycle, like controlling settings, directories and schemas → for example you might already have another solution in place to cover these tasks. When you cannot create a table based on an existing DataFrame or view already available in your SparkSession, that comes with an inferred schema → in this case you must provide a preferred location and specify the correct field types. When Spark is mainly employed to process large data sets in parallel, by distributing them across a cluster, or to implement end-to-end data pipelines through batches or streams→ in this case Spark is generally used for the computational heavy lifting, but data is eventually stored into an external data-lake or written to the final cloud data warehouse. When data needs to remain in the specified external location even after deleting the unmanaged table in Spark→ this is often the case when there are multiple tables or schemas that are built on the top of the same data and you don’t wish to jeopardize their integrity. When Spark should not own data lifecycle, like controlling settings, directories and schemas → for example you might already have another solution in place to cover these tasks. This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase. Spark - The Definitive Guide - By Bill Chamber & Matei Zaharia Learning Spark - By Patrick Wendell & Matei Zaharia Types of Apache Spark tables and views | by Subash Sivaji | Medium Using Spark as a Database — Knoldus Blogs Internal & external tables in Hadoop- HIVE (the big data island) | LinkedIn
[ { "code": null, "e": 320, "s": 172, "text": "A few of my readers have contacted me asking for on-demand courses to learn more about Apache Spark. These are 3 great resources I would recommend:" }, { "code": null, "e": 389, "s": 320, "text": "Data Streaming With Apache Kafka & Apache Spark Nanodegree (Udacity)" }, { "code": null, "e": 427, "s": 389, "text": "Data Engineering Nanodegree (Udacity)" }, { "code": null, "e": 475, "s": 427, "text": "Distributed Computing With Spark SQL (Coursera)" }, { "code": null, "e": 580, "s": 475, "text": "Apache Spark is a distributed data processing engine that allows you to create two main types of tables:" }, { "code": null, "e": 1220, "s": 580, "text": "Managed (or Internal) Tables: for these tables, Spark manages both the data and the metadata. In particular, data is usually saved in the Spark SQL warehouse directory - that is the default for managed tables - whereas metadata is saved in a meta-store of relational entities (including databases, tables, temporary views) and can be accessed through an interface known as the “catalog”.Unmanaged (or External) Tables: for these tables, Spark only manages the metadata, but requires you to specify the exact location where you wish to save the table or, alternatively, the source directory from which data will be pulled to create a table." }, { "code": null, "e": 1608, "s": 1220, "text": "Managed (or Internal) Tables: for these tables, Spark manages both the data and the metadata. In particular, data is usually saved in the Spark SQL warehouse directory - that is the default for managed tables - whereas metadata is saved in a meta-store of relational entities (including databases, tables, temporary views) and can be accessed through an interface known as the “catalog”." }, { "code": null, "e": 1861, "s": 1608, "text": "Unmanaged (or External) Tables: for these tables, Spark only manages the metadata, but requires you to specify the exact location where you wish to save the table or, alternatively, the source directory from which data will be pulled to create a table." }, { "code": null, "e": 1907, "s": 1861, "text": "Moreover, because of their different purpose:" }, { "code": null, "e": 2124, "s": 1907, "text": "if you delete a managed table, Spark will delete both the table data in the warehouse and the metadata in the meta-store, meaning that you will neither be able to query the table directly or to retrieve data into it." }, { "code": null, "e": 2412, "s": 2124, "text": "if you delete an unmanaged table, Spark will just delete the metadata, meaning that you won’t be able to query the table anymore, as your query won’t be resolved against the catalog in the execution analysis phase; but you will still find the tables you created in the external location." }, { "code": null, "e": 2562, "s": 2412, "text": "In this tutorial, I will share three methods to create managed and unmanaged tables and explain the cases when it make sense to use one or the other." }, { "code": null, "e": 2573, "s": 2562, "text": "medium.com" }, { "code": null, "e": 2596, "s": 2573, "text": "towardsdatascience.com" }, { "code": null, "e": 2842, "s": 2596, "text": "If you wish to follow along, but are relatively new to Spark and don’t have a better option, I would strongly suggest to use Databrick’s community edition as it gives you access to a cluster with 15GB of memory and 2 Cores to execute Spark code." }, { "code": null, "e": 3108, "s": 2842, "text": "The sales_redords dataset I am going to use, is quite big (600MB) as it includes 5 million rows and 14 columns - you can download it here. I chose a sizable dataset to - at least partially - replicate the volume of data you will have to deal with in the real world." }, { "code": null, "e": 3360, "s": 3108, "text": "Because the dataset comes in a semi-structured CSV format, in order to create a DataFrame in your SparkSession, make sure to upload the original file in the /FileStore/ directory in the DataBricks File System (DBFS) first, then run the following code:" }, { "code": null, "e": 3488, "s": 3360, "text": "To simulate the cleaning process that raw data would undergo as part of a daily ETL pipeline, let’s suppose that you wished to:" }, { "code": null, "e": 3583, "s": 3488, "text": "Convert the original column names to lowercase and replace blanks “ ” with and underscore “_”;" }, { "code": null, "e": 3724, "s": 3583, "text": "Convert the original “Order Date” from STRING to DATE and the original “Units Sold”, “Unit Price” and “Total Revenue” from STRING to FLOAT ;" }, { "code": null, "e": 3895, "s": 3724, "text": "Drop the following columns as they are not required by your stakeholders: [“Region”, “Country”, “Order Priority”, “Ship Date”, “Total Profit”, “Total Cost”, “Unit Cost”];" }, { "code": null, "e": 3947, "s": 3895, "text": "Remove duplicates in the original “Order ID” field." }, { "code": null, "e": 4116, "s": 3947, "text": "This can be achieved executing the code below, that creates a new DataFrame named df_final that only includes 7 columns and 2M rows.( first 5 rows are also displayed ):" }, { "code": null, "e": 4241, "s": 4116, "text": "The df_final has been manipulated to obtain the preferred result and it’s now ready to be used as a source to create tables." }, { "code": null, "e": 4412, "s": 4241, "text": "However, in order to show you all 3 different methods, I also had to make df_final available as a temporary view and as parquet file (split in 2 partitions) in the DBFS :" }, { "code": null, "e": 4775, "s": 4412, "text": "As mentioned, when you create a managed table, Spark will manage both the table data and the metadata (information about the table itself). In particular data is written to the default Hive warehouse, that is set in the /user/hive/warehouse location. You can change this behavior, using the spark.sql.warehouse.dir configuration while generating a SparkSession ." }, { "code": null, "e": 4798, "s": 4775, "text": "towardsdatascience.com" }, { "code": null, "e": 4957, "s": 4798, "text": "The most straightforward way to create a managed table is to write the df_final through the Structured API saveAsTable() method, without specifying any paths:" }, { "code": null, "e": 5090, "s": 4957, "text": "You can check that the command successfully created a permanent table named salesTable_manag1 with tableType = 'MANAGED' by running:" }, { "code": null, "e": 5235, "s": 5090, "text": "spark.catalog.listTables()Out[1]: [Table(name=’salestable_manag1', database=’default’, description=None, tableType=’MANAGED’, isTemporary=False)" }, { "code": null, "e": 5393, "s": 5235, "text": "You should prefer this method in most cases, as its syntax is very compact and readable and avoids you the additional step of creating a temp view in memory." }, { "code": null, "e": 5518, "s": 5393, "text": "An alternative way to create a managed table is to run a SQL command that queries all the records in the temp df_final_View:" }, { "code": null, "e": 5701, "s": 5518, "text": "In this case I used the %sql magic in Databricks to run a SQL command directly, without wrapping it into spark.sql() . However, you can achieve the exact same result with the syntax:" }, { "code": null, "e": 5790, "s": 5701, "text": "spark.sql(“CREATE TABLE IF NOT EXISTS salesTable_manag2 AS SELECT * FROM df_final_View”)" }, { "code": null, "e": 6121, "s": 5790, "text": "If you have a SQL background, this method is probably the most familiar, as you don’t need to bother with the “standard” Structured API syntax and can even perform additional manipulation on the fly. However, while working with big data, you should take into account the extra space required to create a temp view on your cluster." }, { "code": null, "e": 6314, "s": 6121, "text": "The last method you can use, is similar to the previous one, but it involves two steps as you first create a the table salesTable_manag3 and then insert data into it by querying the temp view:" }, { "code": null, "e": 6511, "s": 6314, "text": "You should opt for this method when you wish to change the column types, or if you already created a table and want to replace or append data into it instead of deleting it and start from scratch." }, { "code": null, "e": 6865, "s": 6511, "text": "Unmanaged tables provide much more flexibility, as the table data can be stored in a location of your choice, or the table can be built directly on top of data available in an external directory. In turn, this means that in Spark, a location is mandatory for external tables. Metadata is again saved in the meta-store and accessible through the catalog." }, { "code": null, "e": 7061, "s": 6865, "text": "Unmanaged tables provide much more flexibility, as the table data can be stored in a location of your choice, or the table can be built directly on top of data available in an external directory." }, { "code": null, "e": 7365, "s": 7061, "text": "In the example below, I am going to use Databricks File System to to simulate an external location with respect to the default Spark SQL warehouse, but of course, it is possible to save unmanaged tables (or create them on top of) every file system compatible with Spark, including cloud data warehouses." }, { "code": null, "e": 7468, "s": 7365, "text": "To create an unmanaged (external) table you can simply specify a path before the saveAsTable() method:" }, { "code": null, "e": 7504, "s": 7468, "text": "When you run this code, Spark will:" }, { "code": null, "e": 7637, "s": 7504, "text": "Shuffle data in the df_final DataFrame to create 2 partitions and write these to the/FileStore/tables/salesTable_unmanag1 directory." }, { "code": null, "e": 7782, "s": 7637, "text": "Create an external table named salesTable_unmanag1 using the partitions stored at that location and save relevant information in the meta-store." }, { "code": null, "e": 7934, "s": 7782, "text": "As similar result can be obtained by specifying the location as part of a SQL query. In this case your will need to use the temp view as a data source:" }, { "code": null, "e": 8014, "s": 7934, "text": "Also remember to use the CREATE EXTERNAL TABLE syntax instead of CREATE TABLE ." }, { "code": null, "e": 8263, "s": 8014, "text": "Finally, if the data you intend to use to create the table, is already available in an external location, you can simply build the table on the top of it by pointing to the location through the USING format OPTIONS (path 'path to location') syntax:" }, { "code": null, "e": 8493, "s": 8263, "text": "In this case, the table is created on the top of the df_final.parquet file that I saved in the FileStore after manipulating the original dataset. Note that if you use this method, you will need to specify the type of each column." }, { "code": null, "e": 8545, "s": 8493, "text": "If you try to list the tables in the catalog again:" }, { "code": null, "e": 8572, "s": 8545, "text": "spark.catalog.listTables()" }, { "code": null, "e": 8712, "s": 8572, "text": "You can see that now the output includes 6 tables of which 3 managed and 3 unmanaged, together with the temp view created at the beginning:" }, { "code": null, "e": 8894, "s": 8712, "text": "Executing the following code will delete metadata from both type of tables and data from managed tables only, whereas data will be preserved in the external locations you specified:" }, { "code": null, "e": 8986, "s": 8894, "text": "However, after erasing metadata you won’t be able to run queries against any of the tables." }, { "code": null, "e": 9275, "s": 8986, "text": "By now, you should have a solid grasp of the differences between these two types of table and should be ready to apply the code above to your specific use cases. However, perhaps you are still a bit confused when it comes to choose between one of the two, while working on a real project." }, { "code": null, "e": 9329, "s": 9275, "text": "In general, you should store data in a MANAGED table:" }, { "code": null, "e": 10598, "s": 9329, "text": "When you wish to use Spark as a database to perform ad hoc or interactive queries to explore and visualize data sets → for instance, you could devise an ETL pipeline in Spark that eventually stores data in a managed table and then use a JDBC-ODBC connector to query this table via Looker, Tableau, Power BI and other BI Tools.When you are working on a project and wish to temporarily save data in Spark for additional manipulation or testing, before writing it to the final location → for instance, managed tables could be handy while building, training and evaluating machine learning models in Spark, as they remove the need for an external storage to save partial iterations.When you wish for Spark to take care of the complete lifecycle of the table data including its deletion or are concerned about security in the external file system → if data does not need to be shared with other clients immediately or there are security concerns, then saving data in the Spark warehouse could be a valid temporary solution.When you are not worried about data reproducibility → if data can easily be retrieved from other sources or the computational effort that takes to transform it is not too extensive, then the risk of erroneously drop a managed table is more contained." }, { "code": null, "e": 10925, "s": 10598, "text": "When you wish to use Spark as a database to perform ad hoc or interactive queries to explore and visualize data sets → for instance, you could devise an ETL pipeline in Spark that eventually stores data in a managed table and then use a JDBC-ODBC connector to query this table via Looker, Tableau, Power BI and other BI Tools." }, { "code": null, "e": 11278, "s": 10925, "text": "When you are working on a project and wish to temporarily save data in Spark for additional manipulation or testing, before writing it to the final location → for instance, managed tables could be handy while building, training and evaluating machine learning models in Spark, as they remove the need for an external storage to save partial iterations." }, { "code": null, "e": 11619, "s": 11278, "text": "When you wish for Spark to take care of the complete lifecycle of the table data including its deletion or are concerned about security in the external file system → if data does not need to be shared with other clients immediately or there are security concerns, then saving data in the Spark warehouse could be a valid temporary solution." }, { "code": null, "e": 11870, "s": 11619, "text": "When you are not worried about data reproducibility → if data can easily be retrieved from other sources or the computational effort that takes to transform it is not too extensive, then the risk of erroneously drop a managed table is more contained." }, { "code": null, "e": 11922, "s": 11870, "text": "You should instead store data in an EXTERNAL table:" }, { "code": null, "e": 12957, "s": 11922, "text": "When you cannot create a table based on an existing DataFrame or view already available in your SparkSession, that comes with an inferred schema → in this case you must provide a preferred location and specify the correct field types.When Spark is mainly employed to process large data sets in parallel, by distributing them across a cluster, or to implement end-to-end data pipelines through batches or streams→ in this case Spark is generally used for the computational heavy lifting, but data is eventually stored into an external data-lake or written to the final cloud data warehouse.When data needs to remain in the specified external location even after deleting the unmanaged table in Spark→ this is often the case when there are multiple tables or schemas that are built on the top of the same data and you don’t wish to jeopardize their integrity.When Spark should not own data lifecycle, like controlling settings, directories and schemas → for example you might already have another solution in place to cover these tasks." }, { "code": null, "e": 13192, "s": 12957, "text": "When you cannot create a table based on an existing DataFrame or view already available in your SparkSession, that comes with an inferred schema → in this case you must provide a preferred location and specify the correct field types." }, { "code": null, "e": 13548, "s": 13192, "text": "When Spark is mainly employed to process large data sets in parallel, by distributing them across a cluster, or to implement end-to-end data pipelines through batches or streams→ in this case Spark is generally used for the computational heavy lifting, but data is eventually stored into an external data-lake or written to the final cloud data warehouse." }, { "code": null, "e": 13817, "s": 13548, "text": "When data needs to remain in the specified external location even after deleting the unmanaged table in Spark→ this is often the case when there are multiple tables or schemas that are built on the top of the same data and you don’t wish to jeopardize their integrity." }, { "code": null, "e": 13995, "s": 13817, "text": "When Spark should not own data lifecycle, like controlling settings, directories and schemas → for example you might already have another solution in place to cover these tasks." }, { "code": null, "e": 14123, "s": 13995, "text": "This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase." }, { "code": null, "e": 14186, "s": 14123, "text": "Spark - The Definitive Guide - By Bill Chamber & Matei Zaharia" }, { "code": null, "e": 14238, "s": 14186, "text": "Learning Spark - By Patrick Wendell & Matei Zaharia" }, { "code": null, "e": 14305, "s": 14238, "text": "Types of Apache Spark tables and views | by Subash Sivaji | Medium" }, { "code": null, "e": 14347, "s": 14305, "text": "Using Spark as a Database — Knoldus Blogs" } ]
Python | List of float to string conversion
29 Oct, 2019 Sometimes, while working with Python list, we can have a problem in which we have to transform the list elements to string. This is easier in case of integral list, as they can be joined easily with join(), and their contents can be displayed. But the case with floats is different, there are additional undesired spaces among it’s values that can cause it’s unsuccess. Let’s discuss a ways in which this error situation can be handled. Method #1 : Using list comprehension + join() + str()This task can be performed using combination of above functions. In this, we firstly convert each element of list i.e float point number to string and then join the resultant strings using the join(). # Python3 code to demonstrate working of# List of float to string conversion# using list comprehension + str() + join() # initialize listtest_list = [5.8, 9.6, 10.2, 45.3, 6.0] # printing original listprint("The original list is : " + str(test_list)) # List of float to string conversion# using list comprehension + str() + join()res = " ".join([str(i) for i in test_list]) # printing resultprint("Conversion of float list to string : " + str(res)) The original list is : [5.8, 9.6, 10.2, 45.3, 6.0] Conversion of float list to string : 5.8 9.6 10.2 45.3 6.0 Method #2 : Using join() + map() + str()The root method is similar by using the combination of join() + str(), but important function which helps to perform this task is map(). This first converts each element to string and then constructs the master string. # Python3 code to demonstrate working of# List of float to string conversion# using join() + map() + str() # initialize listtest_list = [5.8, 9.6, 10.2, 45.3, 6.0] # printing original listprint("The original list is : " + str(test_list)) # Convert float list to string# using join() + map() + str()res1 = " ".join(str(test_list)) # List of float to string conversion# using join() + map() + str()res2 = " ".join(map(str, test_list)) # printing resultprint("Conversion using join + str : " + str(res1))print("Conversion using join + str + map : " + str(res2)) The original list is : [5.8, 9.6, 10.2, 45.3, 6.0] Conversion using join + str : [ 5 . 8, 9 . 6, 1 0 . 2, 4 5 . 3, 6 . 0 ] Conversion using join + str + map : 5.8 9.6 10.2 45.3 6.0 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2019" }, { "code": null, "e": 465, "s": 28, "text": "Sometimes, while working with Python list, we can have a problem in which we have to transform the list elements to string. This is easier in case of integral list, as they can be joined easily with join(), and their contents can be displayed. But the case with floats is different, there are additional undesired spaces among it’s values that can cause it’s unsuccess. Let’s discuss a ways in which this error situation can be handled." }, { "code": null, "e": 719, "s": 465, "text": "Method #1 : Using list comprehension + join() + str()This task can be performed using combination of above functions. In this, we firstly convert each element of list i.e float point number to string and then join the resultant strings using the join()." }, { "code": "# Python3 code to demonstrate working of# List of float to string conversion# using list comprehension + str() + join() # initialize listtest_list = [5.8, 9.6, 10.2, 45.3, 6.0] # printing original listprint(\"The original list is : \" + str(test_list)) # List of float to string conversion# using list comprehension + str() + join()res = \" \".join([str(i) for i in test_list]) # printing resultprint(\"Conversion of float list to string : \" + str(res))", "e": 1172, "s": 719, "text": null }, { "code": null, "e": 1283, "s": 1172, "text": "The original list is : [5.8, 9.6, 10.2, 45.3, 6.0]\nConversion of float list to string : 5.8 9.6 10.2 45.3 6.0\n" }, { "code": null, "e": 1544, "s": 1285, "text": "Method #2 : Using join() + map() + str()The root method is similar by using the combination of join() + str(), but important function which helps to perform this task is map(). This first converts each element to string and then constructs the master string." }, { "code": "# Python3 code to demonstrate working of# List of float to string conversion# using join() + map() + str() # initialize listtest_list = [5.8, 9.6, 10.2, 45.3, 6.0] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert float list to string# using join() + map() + str()res1 = \" \".join(str(test_list)) # List of float to string conversion# using join() + map() + str()res2 = \" \".join(map(str, test_list)) # printing resultprint(\"Conversion using join + str : \" + str(res1))print(\"Conversion using join + str + map : \" + str(res2))", "e": 2108, "s": 1544, "text": null }, { "code": null, "e": 2298, "s": 2108, "text": "The original list is : [5.8, 9.6, 10.2, 45.3, 6.0]\nConversion using join + str : [ 5 . 8, 9 . 6, 1 0 . 2, 4 5 . 3, 6 . 0 ]\nConversion using join + str + map : 5.8 9.6 10.2 45.3 6.0\n" }, { "code": null, "e": 2319, "s": 2298, "text": "Python list-programs" }, { "code": null, "e": 2326, "s": 2319, "text": "Python" }, { "code": null, "e": 2342, "s": 2326, "text": "Python Programs" } ]
Median of two sorted arrays of same size
06 Jul, 2022 There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)). Note: Since the size of the set for which we are looking for the median is even (2n), we need to take the average of the middle two numbers and return the floor of the average.Method 1 (Simply count while Merging) Use the merge procedure of merge sort. Keep track of count while comparing elements of two arrays. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array. See the below implementation. C++ C Java Python3 C# PHP Javascript // A Simple Merge based O(n) // solution to find median of// two sorted arrays#include <bits/stdc++.h>using namespace std; /* This function returns median of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[] are sorted arraysBoth have n elements */int getMedian(int ar1[], int ar2[], int n){ int i = 0; /* Current index of i/p array ar1[] */ int j = 0; /* Current index of i/p array ar2[] */ int count; int m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /* Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[]*/ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /*Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[]*/ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { /* Store the prev median */ m1 = m2; m2 = ar1[i]; i++; } else { /* Store the prev median */ m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2)/2;} // Driver Codeint main(){ int ar1[] = {1, 12, 15, 26, 38}; int ar2[] = {2, 13, 17, 30, 45}; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) cout << "Median is " << getMedian(ar1, ar2, n1) ; else cout << "Doesn't work for arrays" << " of unequal size" ; getchar(); return 0;} // This code is contributed // by Shivi_Aggarwal // A Simple Merge based O(n) solution to find median of// two sorted arrays#include <stdio.h> /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */int getMedian(int ar1[], int ar2[], int n){ int i = 0; /* Current index of i/p array ar1[] */ int j = 0; /* Current index of i/p array ar2[] */ int count; int m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /*Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[]*/ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /*Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[]*/ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { m1 = m2; /* Store the prev median */ m2 = ar1[i]; i++; } else { m1 = m2; /* Store the prev median */ m2 = ar2[j]; j++; } } return (m1 + m2)/2;} /* Driver program to test above function */int main(){ int ar1[] = {1, 12, 15, 26, 38}; int ar2[] = {2, 13, 17, 30, 45}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); if (n1 == n2) printf("Median is %d", getMedian(ar1, ar2, n1)); else printf("Doesn't work for arrays of unequal size"); getchar(); return 0;} // A Simple Merge based O(n) solution // to find median of two sorted arrays class Main{ // function to calculate median static int getMedian(int ar1[], int ar2[], int n) { int i = 0; int j = 0; int count; int m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /* Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[] */ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /* Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[] */ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { /* Store the prev median */ m1 = m2; m2 = ar1[i]; i++; } else { /* Store the prev median */ m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2)/2; } /* Driver program to test above function */ public static void main (String[] args) { int ar1[] = {1, 12, 15, 26, 38}; int ar2[] = {2, 13, 17, 30, 45}; int n1 = ar1.length; int n2 = ar2.length; if (n1 == n2) System.out.println("Median is " + getMedian(ar1, ar2, n1)); else System.out.println("arrays are of unequal size"); } } # A Simple Merge based O(n) Python 3 solution # to find median of two sorted lists # This function returns median of ar1[] and ar2[].# Assumptions in this function:# Both ar1[] and ar2[] are sorted arrays# Both have n elementsdef getMedian( ar1, ar2 , n): i = 0 # Current index of i/p list ar1[] j = 0 # Current index of i/p list ar2[] m1 = -1 m2 = -1 # Since there are 2n elements, median # will be average of elements at index # n-1 and n in the array obtained after # merging ar1 and ar2 count = 0 while count < n + 1: count += 1 # Below is to handle case where all # elements of ar1[] are smaller than # smallest(or first) element of ar2[] if i == n: m1 = m2 m2 = ar2[0] break # Below is to handle case where all # elements of ar2[] are smaller than # smallest(or first) element of ar1[] elif j == n: m1 = m2 m2 = ar1[0] break # equals sign because if two # arrays have some common elements if ar1[i] <= ar2[j]: m1 = m2 # Store the prev median m2 = ar1[i] i += 1 else: m1 = m2 # Store the prev median m2 = ar2[j] j += 1 return (m1 + m2)/2 # Driver code to test above functionar1 = [1, 12, 15, 26, 38]ar2 = [2, 13, 17, 30, 45]n1 = len(ar1)n2 = len(ar2)if n1 == n2: print("Median is ", getMedian(ar1, ar2, n1))else: print("Doesn't work for arrays of unequal size") # This code is contributed by "Sharad_Bhardwaj". // A Simple Merge based O(n) solution // to find median of two sorted arraysusing System;class GFG{ // function to calculate median static int getMedian(int []ar1, int []ar2, int n) { int i = 0; int j = 0; int count; int m1 = -1, m2 = -1; // Since there are 2n elements, // median will be average of // elements at index n-1 and n in // the array obtained after // merging ar1 and ar2 for (count = 0; count <= n; count++) { // Below is to handle case // where all elements of ar1[] // are smaller than smallest // (or first) element of ar2[] if (i == n) { m1 = m2; m2 = ar2[0]; break; } /* Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[] */ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { // Store the prev median m1 = m2; m2 = ar1[i]; i++; } else { // Store the prev median m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2)/2; } // Driver Code public static void Main () { int []ar1 = {1, 12, 15, 26, 38}; int []ar2 = {2, 13, 17, 30, 45}; int n1 = ar1.Length; int n2 = ar2.Length; if (n1 == n2) Console.Write("Median is " + getMedian(ar1, ar2, n1)); else Console.Write("arrays are of unequal size"); } } <?php// A Simple Merge based O(n) solution // to find median of two sorted arrays // This function returns median of // ar1[] and ar2[]. Assumptions in // this function: Both ar1[] and ar2[] // are sorted arrays Both have n elements function getMedian($ar1, $ar2, $n){ // Current index of i/p array ar1[] $i = 0; // Current index of i/p array ar2[] $j = 0; $count; $m1 = -1; $m2 = -1; // Since there are 2n elements, // median will be average of elements // at index n-1 and n in the array // obtained after merging ar1 and ar2 for ($count = 0; $count <= $n; $count++) { // Below is to handle case where // all elements of ar1[] are smaller // than smallest(or first) element of ar2[] if ($i == $n) { $m1 = $m2; $m2 = $ar2[0]; break; } // Below is to handle case where all // elements of ar2[] are smaller than // smallest(or first) element of ar1[] else if ($j == $n) { $m1 = $m2; $m2 = $ar1[0]; break; } // equals sign because if two // arrays have some common elements if ($ar1[$i] <= $ar2[$j]) { // Store the prev median $m1 = $m2; $m2 = $ar1[$i]; $i++; } else { // Store the prev median $m1 = $m2; $m2 = $ar2[$j]; $j++; } } return ($m1 + $m2) / 2;} // Driver Code$ar1 = array(1, 12, 15, 26, 38);$ar2 = array(2, 13, 17, 30, 45); $n1 = sizeof($ar1);$n2 = sizeof($ar2);if ($n1 == $n2) echo("Median is " . getMedian($ar1, $ar2, $n1));else echo("Doesn't work for arrays". "of unequal size"); // This code is contributed by Ajit.?> <script> // A Simple Merge based O(n) solution to find median of// two sorted arrays /* This function returns median of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[] are sorted arraysBoth have n elements */function getMedian(ar1, ar2, n){ var i = 0; /* Current index of i/p array ar1[] */ var j = 0; /* Current index of i/p array ar2[] */ var count; var m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /*Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[]*/ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /*Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[]*/ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { m1 = m2; /* Store the prev median */ m2 = ar1[i]; i++; } else { m1 = m2; /* Store the prev median */ m2 = ar2[j]; j++; } } return (m1 + m2)/2;} /* Driver program to test above function */var ar1 = [1, 12, 15, 26, 38];var ar2 = [2, 13, 17, 30, 45];var n1 = ar1.length;var n2 = ar2.length;if (n1 == n2) document.write("Median is "+ getMedian(ar1, ar2, n1));else document.write("Doesn't work for arrays of unequal size"); </script> Median is 16 Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Time Complexity : O(n)Auxiliary Space: O(1) Method 2 (By comparing the medians of two arrays) This method works by first getting medians of the two sorted arrays and then comparing them.Let ar1 and ar2 be the input arrays. Algorithm : 1) Calculate the medians m1 and m2 of the input arrays ar1[] and ar2[] respectively. 2) If m1 and m2 both are equal then we are done. return m1 (or m2) 3) If m1 is greater than m2, then median is present in one of the below two subarrays. a) From first element of ar1 to m1 (ar1[0...|_n/2_|]) b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1]) 4) If m2 is greater than m1, then median is present in one of the below two subarrays. a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1]) b) From first element of ar2 to m2 (ar2[0...|_n/2_|]) 5) Repeat the above process until size of both the subarrays becomes 2. 6) If size of the two arrays is 2 then use below formula to get the median. Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2 Examples : ar1[] = {1, 12, 15, 26, 38} ar2[] = {2, 13, 17, 30, 45} For above two arrays m1 = 15 and m2 = 17For the above ar1[] and ar2[], m1 is smaller than m2. So median is present in one of the following two subarrays. [15, 26, 38] and [2, 13, 17] Let us repeat the process for above two subarrays: m1 = 26 m2 = 13. m1 is greater than m2. So the subarrays become [15, 26] and [13, 17] Now size is 2, so median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2 = (max(15, 13) + min(26, 17))/2 = (15 + 17)/2 = 16 Implementation : C C++ Java Python C# Javascript // A divide and conquer based efficient solution to find median// of two sorted arrays of same size.#include<bits/stdc++.h>using namespace std; int median(int [], int); /* to get median of a sorted array */ /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */int getMedian(int ar1[], int ar2[], int n){ /* return -1 for invalid input */ if (n <= 0) return -1; if (n == 1) return (ar1[0] + ar2[0])/2; if (n == 2) return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2; int m1 = median(ar1, n); /* get the median of the first array */ int m2 = median(ar2, n); /* get the median of the second array */ /* If medians are equal then return either m1 or m2 */ if (m1 == m2) return m1; /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ if (m1 < m2) { if (n % 2 == 0) return getMedian(ar1 + n/2 - 1, ar2, n - n/2 +1); return getMedian(ar1 + n/2, ar2, n - n/2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ if (n % 2 == 0) return getMedian(ar2 + n/2 - 1, ar1, n - n/2 + 1); return getMedian(ar2 + n/2, ar1, n - n/2);} /* Function to get median of a sorted array */int median(int arr[], int n){ if (n%2 == 0) return (arr[n/2] + arr[n/2-1])/2; else return arr[n/2];} /* Driver program to test above function */int main(){ int ar1[] = {1, 2, 3, 6}; int ar2[] = {4, 6, 8, 10}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); if (n1 == n2) printf("Median is %d", getMedian(ar1, ar2, n1)); else printf("Doesn't work for arrays of unequal size"); return 0;} // A divide and conquer based // efficient solution to find // median of two sorted arrays // of same size.#include<bits/stdc++.h>using namespace std; /* to get median of a sorted array */int median(int [], int); /* This function returns median of ar1[] and ar2[].Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */int getMedian(int ar1[], int ar2[], int n){ /* return -1 for invalid input */ if (n <= 0) return -1; if (n == 1) return (ar1[0] + ar2[0]) / 2; if (n == 2) return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2; /* get the median of the first array */ int m1 = median(ar1, n); /* get the median of the second array */ int m2 = median(ar2, n); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) return m1; /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ if (m1 < m2) { if (n % 2 == 0) return getMedian(ar1 + n / 2 - 1, ar2, n - n / 2 + 1); return getMedian(ar1 + n / 2, ar2, n - n / 2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ if (n % 2 == 0) return getMedian(ar2 + n / 2 - 1, ar1, n - n / 2 + 1); return getMedian(ar2 + n / 2, ar1, n - n / 2);} /* Function to get median of a sorted array */int median(int arr[], int n){ if (n % 2 == 0) return (arr[n / 2] + arr[n / 2 - 1]) / 2; else return arr[n / 2];} // Driver codeint main(){ int ar1[] = {1, 2, 3, 6}; int ar2[] = {4, 6, 8, 10}; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) cout << "Median is " << getMedian(ar1, ar2, n1); else cout << "Doesn't work for arrays " << "of unequal size"; return 0;} // This code is contributed// by Shivi_Aggarwal // A Java program to divide and conquer based// efficient solution to find// median of two sorted arrays// of same size.import java.util.*;class GfG { /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */ static int getMedian( int[] a, int[] b, int startA, int startB, int endA, int endB) { if (endA - startA == 1) { return ( Math.max(a[startA], b[startB]) + Math.min(a[endA], b[endB])) / 2; } /* get the median of the first array */ int m1 = median(a, startA, endA); /* get the median of the second array */ int m2 = median(b, startB, endB); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) { return m1; } /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ else if (m1 < m2) { return getMedian( a, b, (endA + startA + 1) / 2, startB, endA, (endB + startB + 1) / 2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ else { return getMedian( a, b, startA, (endB + startB + 1) / 2, (endA + startA + 1) / 2, endB); } } /* Function to get median of a sorted array */ static int median( int[] arr, int start, int end) { int n = end - start + 1; if (n % 2 == 0) { return ( arr[start + (n / 2)] + arr[start + (n / 2 - 1)]) / 2; } else { return arr[start + n / 2]; } } // Driver code public static void main(String[] args) { int ar1[] = { 1, 2, 3, 6 }; int ar2[] = { 4, 6, 8, 10 }; int n1 = ar1.length; int n2 = ar2.length; if (n1 != n2) { System.out.println( "Doesn't work for arrays " + "of unequal size"); } else if (n1 == 0) { System.out.println("Arrays are empty."); } else if (n1 == 1) { System.out.println((ar1[0] + ar2[0]) / 2); } else { System.out.println( "Median is " + getMedian( ar1, ar2, 0, 0, ar1.length - 1, ar2.length - 1)); } }} # using divide and conquer we divide# the 2 arrays accordingly recursively# till we get two elements in each # array, hence then we calculate median #condition len(arr1)=len(arr2)=ndef getMedian(arr1, arr2, n): # there is no element in any array if n == 0: return -1 # 1 element in each => median of # sorted arr made of two arrays will elif n == 1: # be sum of both elements by 2 return (arr1[0]+arr2[0])/2 # Eg. [1,4] , [6,10] => [1, 4, 6, 10] # median = (6+4)/2 elif n == 2: # which implies median = (max(arr1[0], # arr2[0])+min(arr1[1],arr2[1]))/2 return (max(arr1[0], arr2[0]) + min(arr1[1], arr2[1])) / 2 else: #calculating medians m1 = median(arr1, n) m2 = median(arr2, n) # then the elements at median # position must be between the # greater median and the first # element of respective array and # between the other median and # the last element in its respective array. if m1 > m2: if n % 2 == 0: return getMedian(arr1[:int(n / 2) + 1], arr2[int(n / 2) - 1:], int(n / 2) + 1) else: return getMedian(arr1[:int(n / 2) + 1], arr2[int(n / 2):], int(n / 2) + 1) else: if n % 2 == 0: return getMedian(arr1[int(n / 2 - 1):], arr2[:int(n / 2 + 1)], int(n / 2) + 1) else: return getMedian(arr1[int(n / 2):], arr2[0:int(n / 2) + 1], int(n / 2) + 1) # function to find median of arraydef median(arr, n): if n % 2 == 0: return (arr[int(n / 2)] + arr[int(n / 2) - 1]) / 2 else: return arr[int(n/2)] # Driver codearr1 = [1, 2, 3, 6]arr2 = [4, 6, 8, 10]n = len(arr1)print(int(getMedian(arr1,arr2,n))) # This code is contributed by# baby_gog9800 // A C# program to divide and conquer based// efficient solution to find// median of two sorted arrays// of same size.using System;class GfG{ /* This function returns medianof ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[] aresorted arraysBoth have n elements */ static int getMedian(int[] a, int[] b, int startA, int startB, int endA, int endB){ if (endA - startA == 1) { return (Math.Max(a[startA], b[startB]) + Math.Min(a[endA], b[endB])) / 2; } /* get the median of the first array */ int m1 = median(a, startA, endA); /* get the median of the second array */ int m2 = median(b, startB, endB); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) { return m1; } /*if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ else if (m1 < m2) { return getMedian(a, b, (endA + startA + 1) / 2, startB, endA, (endB + startB + 1) / 2); } /*if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ else { return getMedian(a, b, startA, (endB + startB + 1) / 2, (endA + startA + 1) / 2, endB); }} /* Function to get medianof a sorted array */static int median(int[] arr, int start, int end){ int n = end - start + 1; if (n % 2 == 0) { return (arr[start + (n / 2)] + arr[start + (n / 2 - 1)]) / 2; } else { return arr[start + n / 2]; }} // Driver codepublic static void Main(String[] args){ int []ar1 = {1, 2, 3, 6}; int []ar2 = {4, 6, 8, 10}; int n1 = ar1.Length; int n2 = ar2.Length; if (n1 != n2) { Console.WriteLine("Doesn't work for arrays " + "of unequal size"); } else if (n1 == 0) { Console.WriteLine("Arrays are empty."); } else if (n1 == 1) { Console.WriteLine((ar1[0] + ar2[0]) / 2); } else { Console.WriteLine("Median is " + getMedian(ar1, ar2, 0, 0, ar1.Length - 1, ar2.Length - 1)); }}} // This code is contributed by gauravrajput1 <script>// A Javascript program to divide and conquer based// efficient solution to find// median of two sorted arrays// of same size. /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */function getMedian(a,b,startA,startB,endA,endB){ if (endA - startA == 1) { return ( Math.max(a[startA], b[startB]) + Math.min(a[endA], b[endB])) / 2; } /* get the median of the first array */ let m1 = median(a, startA, endA); /* get the median of the second array */ let m2 = median(b, startB, endB); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) { return m1; } /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ else if (m1 < m2) { return getMedian( a, b, (endA + startA + 1) / 2, startB, endA, (endB + startB + 1) / 2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ else { return getMedian( a, b, startA, (endB + startB + 1) / 2, (endA + startA + 1) / 2, endB); }} /* Function to get median of a sorted array */function median(arr,start,end){ let n = end - start + 1; if (n % 2 == 0) { return ( arr[start + (n / 2)] + arr[start + (n / 2 - 1)]) / 2; } else { return arr[start + n / 2]; }} // Driver codelet ar1 = [ 1, 2, 3, 6 ]; let ar2 = [ 4, 6, 8, 10 ]; let n1 = ar1.length; let n2 = ar2.length; if (n1 != n2) { document.write( "Doesn't work for arrays " + "of unequal size<br>"); } else if (n1 == 0) { document.write("Arrays are empty.<br>"); } else if (n1 == 1) { document.write((ar1[0] + ar2[0]) / 2+"<br>"); } else { document.write( "Median is " + getMedian( ar1, ar2, 0, 0, ar1.length - 1, ar2.length - 1)+"<br>"); } // This code is contributed by avanitrachhadiya2155</script> Median is 5 Time Complexity : O(logn) Auxiliary Space: O(1)Algorithmic Paradigm: Divide and Conquer Method 3 (By Merging two arrays w/o extra space)This method works by merging two arrays without extra space and then sorting them. Algorithm : 1) Merge the two input arrays ar1[] and ar2[]. 2) Sort ar1[] and ar2[] respectively. 3) The median will be the last element of ar1[] + the first element of ar2[] divided by 2. [(ar1[n-1] + ar2[0])/2]. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // CPP program for the above approach#include <bits/stdc++.h>using namespace std; /* This function returnsmedian of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[]are sorted arraysBoth have n elements */int getMedian(int ar1[], int ar2[], int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) swap(ar1[i--], ar2[j++]); sort(ar1, ar1 + n); sort(ar2, ar2 + n); return (ar1[n - 1] + ar2[0]) / 2;} // Driver Codeint main(){ int ar1[] = { 1, 12, 15, 26, 38 }; int ar2[] = { 2, 13, 17, 30, 45 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) cout << "Median is " << getMedian(ar1, ar2, n1); else cout << "Doesn't work for arrays" << " of unequal size"; getchar(); return 0;} // This code is contributed// by Lakshay // C program for the above approach#include <stdio.h>#include <stdlib.h> /* This function returnsmedian of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[]are sorted arraysBoth have n elements */ // compare function, compares two elementsint compare(const void* num1, const void* num2){ if (*(int*)num1 > *(int*)num2) return 1; else return -1;} int getMedian(int ar1[], int ar2[], int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { int temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } qsort(ar1, n, sizeof(int), compare); qsort(ar2, n, sizeof(int), compare); return (ar1[n - 1] + ar2[0]) / 2;} // Driver Codeint main(){ int ar1[] = { 1, 12, 15, 26, 38 }; int ar2[] = { 2, 13, 17, 30, 45 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) printf("Median is %d ", getMedian(ar1, ar2, n1)); else printf("Doesn't work for arrays of unequal size"); return 0;} // This code is contributed by Deepthi /*package whatever //do not write package name here */import java.io.*;import java.util.*;class GFG{ /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */public static int getMedian(int ar1[], int ar2[], int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { int temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } Arrays.sort(ar1); Arrays.sort(ar2); return (ar1[n - 1] + ar2[0]) / 2;} // Driver codepublic static void main (String[] args){ int ar1[] = { 1, 12, 15, 26, 38 }; int ar2[] = { 2, 13, 17, 30, 45 }; int n1 = 5; int n2 = 5; if (n1 == n2) System.out.println("Median is "+ getMedian(ar1, ar2, n1)); else System.out.println("Doesn't work for arrays of unequal size");}} // This code is contributed by Manu Pathria # Python program for above approach # function to return median of the arrays# both are sorted & of same sizedef getMedian(ar1, ar2, n): i, j = n - 1, 0 # while loop to swap all smaller numbers to arr1 while(ar1[i] > ar2[j] and i > -1 and j < n): ar1[i], ar2[j] = ar2[j], ar1[i] i -= 1 j += 1 ar1.sort() ar2.sort() return (ar1[-1] + ar2[0]) >> 1 # Driver programif __name__ == '__main__': ar1 = [1, 12, 15, 26, 38] ar2 = [2, 13, 17, 30, 45] n1, n2 = len(ar1), len(ar2) if(n1 == n2): print('Median is', getMedian(ar1, ar2, n1)) else: print("Doesn't work for arrays of unequal size") # This code is contributed by saitejagampala /*package whatever //do not write package name here */using System;public class GFG{ /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */public static int getMedian(int []ar1, int []ar2, int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { int temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } Array.Sort(ar1); Array.Sort(ar2); return (ar1[n - 1] + ar2[0]) / 2;} // Driver codepublic static void Main(String[] args){ int []ar1 = { 1, 12, 15, 26, 38 }; int []ar2 = { 2, 13, 17, 30, 45 }; int n1 = 5; int n2 = 5; if (n1 == n2) Console.WriteLine("Median is "+ getMedian(ar1, ar2, n1)); else Console.WriteLine("Doesn't work for arrays of unequal size");}} // This code is contributed by aashish1995 <script> /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */ function getMedian(ar1, ar2, n) { let j = 0; let i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { let temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } ar1.sort(function(a, b){return a - b}); ar2.sort(function(a, b){return a - b}); return parseInt((ar1[n - 1] + ar2[0]) / 2, 10); } let ar1 = [ 1, 12, 15, 26, 38 ]; let ar2 = [ 2, 13, 17, 30, 45 ]; let n1 = 5; let n2 = 5; if (n1 == n2) document.write("Median is "+ getMedian(ar1, ar2, n1)); else document.write("Doesn't work for arrays of unequal size"); </script> Median is 16 Time Complexity: O(nlogn)Auxiliary Space: O(1) Median of two sorted arrays of different sizesReferences: http://en.wikipedia.org/wiki/Medianhttp://ocw.alfaisal.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-046JFall-2005/30C68118-E436-4FE3-8C79-6BAFBB07D935/0/ps9sol.pdf ds3etph5wnPlease write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. SaumyaBhatnagar jit_t nitin mittal Shivi_Aggarwal prerna saini lilkucfer Harshita Chaudhary MohammadOmar GauravRajput1 benjam1n manupathria saitejagampala aashish1995 rrrtnx 2435shivkant vaibhavrabadiya117 avanitrachhadiya2155 subhammahato348 souravmahato348 deepthiinduri Code_r sanyamjain10168 Accolite Amazon D-E-Shaw FactSet median-finding Samsung statistical-algorithms Arrays Divide and Conquer Mathematical Searching Accolite Amazon Samsung D-E-Shaw FactSet Arrays Searching Mathematical Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Merge Sort QuickSort Maximum and minimum of an array using minimum number of comparisons Count Inversions in an array | Set 1 (Using Merge Sort) Program for Tower of Hanoi
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 258, "s": 52, "text": "There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)). " }, { "code": null, "e": 742, "s": 258, "text": "Note: Since the size of the set for which we are looking for the median is even (2n), we need to take the average of the middle two numbers and return the floor of the average.Method 1 (Simply count while Merging) Use the merge procedure of merge sort. Keep track of count while comparing elements of two arrays. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array. See the below implementation. " }, { "code": null, "e": 746, "s": 742, "text": "C++" }, { "code": null, "e": 748, "s": 746, "text": "C" }, { "code": null, "e": 753, "s": 748, "text": "Java" }, { "code": null, "e": 761, "s": 753, "text": "Python3" }, { "code": null, "e": 764, "s": 761, "text": "C#" }, { "code": null, "e": 768, "s": 764, "text": "PHP" }, { "code": null, "e": 779, "s": 768, "text": "Javascript" }, { "code": "// A Simple Merge based O(n) // solution to find median of// two sorted arrays#include <bits/stdc++.h>using namespace std; /* This function returns median of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[] are sorted arraysBoth have n elements */int getMedian(int ar1[], int ar2[], int n){ int i = 0; /* Current index of i/p array ar1[] */ int j = 0; /* Current index of i/p array ar2[] */ int count; int m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /* Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[]*/ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /*Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[]*/ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { /* Store the prev median */ m1 = m2; m2 = ar1[i]; i++; } else { /* Store the prev median */ m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2)/2;} // Driver Codeint main(){ int ar1[] = {1, 12, 15, 26, 38}; int ar2[] = {2, 13, 17, 30, 45}; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) cout << \"Median is \" << getMedian(ar1, ar2, n1) ; else cout << \"Doesn't work for arrays\" << \" of unequal size\" ; getchar(); return 0;} // This code is contributed // by Shivi_Aggarwal", "e": 2806, "s": 779, "text": null }, { "code": "// A Simple Merge based O(n) solution to find median of// two sorted arrays#include <stdio.h> /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */int getMedian(int ar1[], int ar2[], int n){ int i = 0; /* Current index of i/p array ar1[] */ int j = 0; /* Current index of i/p array ar2[] */ int count; int m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /*Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[]*/ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /*Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[]*/ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { m1 = m2; /* Store the prev median */ m2 = ar1[i]; i++; } else { m1 = m2; /* Store the prev median */ m2 = ar2[j]; j++; } } return (m1 + m2)/2;} /* Driver program to test above function */int main(){ int ar1[] = {1, 12, 15, 26, 38}; int ar2[] = {2, 13, 17, 30, 45}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); if (n1 == n2) printf(\"Median is %d\", getMedian(ar1, ar2, n1)); else printf(\"Doesn't work for arrays of unequal size\"); getchar(); return 0;}", "e": 4640, "s": 2806, "text": null }, { "code": "// A Simple Merge based O(n) solution // to find median of two sorted arrays class Main{ // function to calculate median static int getMedian(int ar1[], int ar2[], int n) { int i = 0; int j = 0; int count; int m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /* Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[] */ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /* Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[] */ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { /* Store the prev median */ m1 = m2; m2 = ar1[i]; i++; } else { /* Store the prev median */ m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2)/2; } /* Driver program to test above function */ public static void main (String[] args) { int ar1[] = {1, 12, 15, 26, 38}; int ar2[] = {2, 13, 17, 30, 45}; int n1 = ar1.length; int n2 = ar2.length; if (n1 == n2) System.out.println(\"Median is \" + getMedian(ar1, ar2, n1)); else System.out.println(\"arrays are of unequal size\"); } }", "e": 6630, "s": 4640, "text": null }, { "code": "# A Simple Merge based O(n) Python 3 solution # to find median of two sorted lists # This function returns median of ar1[] and ar2[].# Assumptions in this function:# Both ar1[] and ar2[] are sorted arrays# Both have n elementsdef getMedian( ar1, ar2 , n): i = 0 # Current index of i/p list ar1[] j = 0 # Current index of i/p list ar2[] m1 = -1 m2 = -1 # Since there are 2n elements, median # will be average of elements at index # n-1 and n in the array obtained after # merging ar1 and ar2 count = 0 while count < n + 1: count += 1 # Below is to handle case where all # elements of ar1[] are smaller than # smallest(or first) element of ar2[] if i == n: m1 = m2 m2 = ar2[0] break # Below is to handle case where all # elements of ar2[] are smaller than # smallest(or first) element of ar1[] elif j == n: m1 = m2 m2 = ar1[0] break # equals sign because if two # arrays have some common elements if ar1[i] <= ar2[j]: m1 = m2 # Store the prev median m2 = ar1[i] i += 1 else: m1 = m2 # Store the prev median m2 = ar2[j] j += 1 return (m1 + m2)/2 # Driver code to test above functionar1 = [1, 12, 15, 26, 38]ar2 = [2, 13, 17, 30, 45]n1 = len(ar1)n2 = len(ar2)if n1 == n2: print(\"Median is \", getMedian(ar1, ar2, n1))else: print(\"Doesn't work for arrays of unequal size\") # This code is contributed by \"Sharad_Bhardwaj\".", "e": 8252, "s": 6630, "text": null }, { "code": "// A Simple Merge based O(n) solution // to find median of two sorted arraysusing System;class GFG{ // function to calculate median static int getMedian(int []ar1, int []ar2, int n) { int i = 0; int j = 0; int count; int m1 = -1, m2 = -1; // Since there are 2n elements, // median will be average of // elements at index n-1 and n in // the array obtained after // merging ar1 and ar2 for (count = 0; count <= n; count++) { // Below is to handle case // where all elements of ar1[] // are smaller than smallest // (or first) element of ar2[] if (i == n) { m1 = m2; m2 = ar2[0]; break; } /* Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[] */ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { // Store the prev median m1 = m2; m2 = ar1[i]; i++; } else { // Store the prev median m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2)/2; } // Driver Code public static void Main () { int []ar1 = {1, 12, 15, 26, 38}; int []ar2 = {2, 13, 17, 30, 45}; int n1 = ar1.Length; int n2 = ar2.Length; if (n1 == n2) Console.Write(\"Median is \" + getMedian(ar1, ar2, n1)); else Console.Write(\"arrays are of unequal size\"); } }", "e": 10246, "s": 8252, "text": null }, { "code": "<?php// A Simple Merge based O(n) solution // to find median of two sorted arrays // This function returns median of // ar1[] and ar2[]. Assumptions in // this function: Both ar1[] and ar2[] // are sorted arrays Both have n elements function getMedian($ar1, $ar2, $n){ // Current index of i/p array ar1[] $i = 0; // Current index of i/p array ar2[] $j = 0; $count; $m1 = -1; $m2 = -1; // Since there are 2n elements, // median will be average of elements // at index n-1 and n in the array // obtained after merging ar1 and ar2 for ($count = 0; $count <= $n; $count++) { // Below is to handle case where // all elements of ar1[] are smaller // than smallest(or first) element of ar2[] if ($i == $n) { $m1 = $m2; $m2 = $ar2[0]; break; } // Below is to handle case where all // elements of ar2[] are smaller than // smallest(or first) element of ar1[] else if ($j == $n) { $m1 = $m2; $m2 = $ar1[0]; break; } // equals sign because if two // arrays have some common elements if ($ar1[$i] <= $ar2[$j]) { // Store the prev median $m1 = $m2; $m2 = $ar1[$i]; $i++; } else { // Store the prev median $m1 = $m2; $m2 = $ar2[$j]; $j++; } } return ($m1 + $m2) / 2;} // Driver Code$ar1 = array(1, 12, 15, 26, 38);$ar2 = array(2, 13, 17, 30, 45); $n1 = sizeof($ar1);$n2 = sizeof($ar2);if ($n1 == $n2) echo(\"Median is \" . getMedian($ar1, $ar2, $n1));else echo(\"Doesn't work for arrays\". \"of unequal size\"); // This code is contributed by Ajit.?>", "e": 12066, "s": 10246, "text": null }, { "code": "<script> // A Simple Merge based O(n) solution to find median of// two sorted arrays /* This function returns median of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[] are sorted arraysBoth have n elements */function getMedian(ar1, ar2, n){ var i = 0; /* Current index of i/p array ar1[] */ var j = 0; /* Current index of i/p array ar2[] */ var count; var m1 = -1, m2 = -1; /* Since there are 2n elements, median will be average of elements at index n-1 and n in the array obtained after merging ar1 and ar2 */ for (count = 0; count <= n; count++) { /*Below is to handle case where all elements of ar1[] are smaller than smallest(or first) element of ar2[]*/ if (i == n) { m1 = m2; m2 = ar2[0]; break; } /*Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[]*/ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } /* equals sign because if two arrays have some common elements */ if (ar1[i] <= ar2[j]) { m1 = m2; /* Store the prev median */ m2 = ar1[i]; i++; } else { m1 = m2; /* Store the prev median */ m2 = ar2[j]; j++; } } return (m1 + m2)/2;} /* Driver program to test above function */var ar1 = [1, 12, 15, 26, 38];var ar2 = [2, 13, 17, 30, 45];var n1 = ar1.length;var n2 = ar2.length;if (n1 == n2) document.write(\"Median is \"+ getMedian(ar1, ar2, n1));else document.write(\"Doesn't work for arrays of unequal size\"); </script>", "e": 13777, "s": 12066, "text": null }, { "code": null, "e": 13790, "s": 13777, "text": "Median is 16" }, { "code": null, "e": 13799, "s": 13790, "text": "Chapters" }, { "code": null, "e": 13826, "s": 13799, "text": "descriptions off, selected" }, { "code": null, "e": 13876, "s": 13826, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 13899, "s": 13876, "text": "captions off, selected" }, { "code": null, "e": 13907, "s": 13899, "text": "English" }, { "code": null, "e": 13931, "s": 13907, "text": "This is a modal window." }, { "code": null, "e": 14000, "s": 13931, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 14022, "s": 14000, "text": "End of dialog window." }, { "code": null, "e": 14066, "s": 14022, "text": "Time Complexity : O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 14259, "s": 14066, "text": "Method 2 (By comparing the medians of two arrays) This method works by first getting medians of the two sorted arrays and then comparing them.Let ar1 and ar2 be the input arrays. Algorithm : " }, { "code": null, "e": 15057, "s": 14259, "text": "1) Calculate the medians m1 and m2 of the input arrays ar1[] \n and ar2[] respectively.\n2) If m1 and m2 both are equal then we are done.\n return m1 (or m2)\n3) If m1 is greater than m2, then median is present in one \n of the below two subarrays.\n a) From first element of ar1 to m1 (ar1[0...|_n/2_|])\n b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1])\n4) If m2 is greater than m1, then median is present in one \n of the below two subarrays.\n a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1])\n b) From first element of ar2 to m2 (ar2[0...|_n/2_|])\n5) Repeat the above process until size of both the subarrays \n becomes 2.\n6) If size of the two arrays is 2 then use below formula to get \n the median.\n Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2" }, { "code": null, "e": 15070, "s": 15057, "text": "Examples : " }, { "code": null, "e": 15132, "s": 15070, "text": " ar1[] = {1, 12, 15, 26, 38}\n ar2[] = {2, 13, 17, 30, 45}" }, { "code": null, "e": 15287, "s": 15132, "text": "For above two arrays m1 = 15 and m2 = 17For the above ar1[] and ar2[], m1 is smaller than m2. So median is present in one of the following two subarrays. " }, { "code": null, "e": 15319, "s": 15287, "text": " [15, 26, 38] and [2, 13, 17]" }, { "code": null, "e": 15372, "s": 15319, "text": "Let us repeat the process for above two subarrays: " }, { "code": null, "e": 15393, "s": 15372, "text": " m1 = 26 m2 = 13." }, { "code": null, "e": 15442, "s": 15393, "text": "m1 is greater than m2. So the subarrays become " }, { "code": null, "e": 15660, "s": 15442, "text": " [15, 26] and [13, 17]\nNow size is 2, so median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2\n = (max(15, 13) + min(26, 17))/2 \n = (15 + 17)/2\n = 16" }, { "code": null, "e": 15678, "s": 15660, "text": "Implementation : " }, { "code": null, "e": 15680, "s": 15678, "text": "C" }, { "code": null, "e": 15684, "s": 15680, "text": "C++" }, { "code": null, "e": 15689, "s": 15684, "text": "Java" }, { "code": null, "e": 15696, "s": 15689, "text": "Python" }, { "code": null, "e": 15699, "s": 15696, "text": "C#" }, { "code": null, "e": 15710, "s": 15699, "text": "Javascript" }, { "code": "// A divide and conquer based efficient solution to find median// of two sorted arrays of same size.#include<bits/stdc++.h>using namespace std; int median(int [], int); /* to get median of a sorted array */ /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */int getMedian(int ar1[], int ar2[], int n){ /* return -1 for invalid input */ if (n <= 0) return -1; if (n == 1) return (ar1[0] + ar2[0])/2; if (n == 2) return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2; int m1 = median(ar1, n); /* get the median of the first array */ int m2 = median(ar2, n); /* get the median of the second array */ /* If medians are equal then return either m1 or m2 */ if (m1 == m2) return m1; /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ if (m1 < m2) { if (n % 2 == 0) return getMedian(ar1 + n/2 - 1, ar2, n - n/2 +1); return getMedian(ar1 + n/2, ar2, n - n/2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ if (n % 2 == 0) return getMedian(ar2 + n/2 - 1, ar1, n - n/2 + 1); return getMedian(ar2 + n/2, ar1, n - n/2);} /* Function to get median of a sorted array */int median(int arr[], int n){ if (n%2 == 0) return (arr[n/2] + arr[n/2-1])/2; else return arr[n/2];} /* Driver program to test above function */int main(){ int ar1[] = {1, 2, 3, 6}; int ar2[] = {4, 6, 8, 10}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); if (n1 == n2) printf(\"Median is %d\", getMedian(ar1, ar2, n1)); else printf(\"Doesn't work for arrays of unequal size\"); return 0;}", "e": 17511, "s": 15710, "text": null }, { "code": "// A divide and conquer based // efficient solution to find // median of two sorted arrays // of same size.#include<bits/stdc++.h>using namespace std; /* to get median of a sorted array */int median(int [], int); /* This function returns median of ar1[] and ar2[].Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */int getMedian(int ar1[], int ar2[], int n){ /* return -1 for invalid input */ if (n <= 0) return -1; if (n == 1) return (ar1[0] + ar2[0]) / 2; if (n == 2) return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2; /* get the median of the first array */ int m1 = median(ar1, n); /* get the median of the second array */ int m2 = median(ar2, n); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) return m1; /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ if (m1 < m2) { if (n % 2 == 0) return getMedian(ar1 + n / 2 - 1, ar2, n - n / 2 + 1); return getMedian(ar1 + n / 2, ar2, n - n / 2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ if (n % 2 == 0) return getMedian(ar2 + n / 2 - 1, ar1, n - n / 2 + 1); return getMedian(ar2 + n / 2, ar1, n - n / 2);} /* Function to get median of a sorted array */int median(int arr[], int n){ if (n % 2 == 0) return (arr[n / 2] + arr[n / 2 - 1]) / 2; else return arr[n / 2];} // Driver codeint main(){ int ar1[] = {1, 2, 3, 6}; int ar2[] = {4, 6, 8, 10}; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) cout << \"Median is \" << getMedian(ar1, ar2, n1); else cout << \"Doesn't work for arrays \" << \"of unequal size\"; return 0;} // This code is contributed// by Shivi_Aggarwal", "e": 19676, "s": 17511, "text": null }, { "code": "// A Java program to divide and conquer based// efficient solution to find// median of two sorted arrays// of same size.import java.util.*;class GfG { /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */ static int getMedian( int[] a, int[] b, int startA, int startB, int endA, int endB) { if (endA - startA == 1) { return ( Math.max(a[startA], b[startB]) + Math.min(a[endA], b[endB])) / 2; } /* get the median of the first array */ int m1 = median(a, startA, endA); /* get the median of the second array */ int m2 = median(b, startB, endB); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) { return m1; } /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ else if (m1 < m2) { return getMedian( a, b, (endA + startA + 1) / 2, startB, endA, (endB + startB + 1) / 2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ else { return getMedian( a, b, startA, (endB + startB + 1) / 2, (endA + startA + 1) / 2, endB); } } /* Function to get median of a sorted array */ static int median( int[] arr, int start, int end) { int n = end - start + 1; if (n % 2 == 0) { return ( arr[start + (n / 2)] + arr[start + (n / 2 - 1)]) / 2; } else { return arr[start + n / 2]; } } // Driver code public static void main(String[] args) { int ar1[] = { 1, 2, 3, 6 }; int ar2[] = { 4, 6, 8, 10 }; int n1 = ar1.length; int n2 = ar2.length; if (n1 != n2) { System.out.println( \"Doesn't work for arrays \" + \"of unequal size\"); } else if (n1 == 0) { System.out.println(\"Arrays are empty.\"); } else if (n1 == 1) { System.out.println((ar1[0] + ar2[0]) / 2); } else { System.out.println( \"Median is \" + getMedian( ar1, ar2, 0, 0, ar1.length - 1, ar2.length - 1)); } }}", "e": 22280, "s": 19676, "text": null }, { "code": "# using divide and conquer we divide# the 2 arrays accordingly recursively# till we get two elements in each # array, hence then we calculate median #condition len(arr1)=len(arr2)=ndef getMedian(arr1, arr2, n): # there is no element in any array if n == 0: return -1 # 1 element in each => median of # sorted arr made of two arrays will elif n == 1: # be sum of both elements by 2 return (arr1[0]+arr2[0])/2 # Eg. [1,4] , [6,10] => [1, 4, 6, 10] # median = (6+4)/2 elif n == 2: # which implies median = (max(arr1[0], # arr2[0])+min(arr1[1],arr2[1]))/2 return (max(arr1[0], arr2[0]) + min(arr1[1], arr2[1])) / 2 else: #calculating medians m1 = median(arr1, n) m2 = median(arr2, n) # then the elements at median # position must be between the # greater median and the first # element of respective array and # between the other median and # the last element in its respective array. if m1 > m2: if n % 2 == 0: return getMedian(arr1[:int(n / 2) + 1], arr2[int(n / 2) - 1:], int(n / 2) + 1) else: return getMedian(arr1[:int(n / 2) + 1], arr2[int(n / 2):], int(n / 2) + 1) else: if n % 2 == 0: return getMedian(arr1[int(n / 2 - 1):], arr2[:int(n / 2 + 1)], int(n / 2) + 1) else: return getMedian(arr1[int(n / 2):], arr2[0:int(n / 2) + 1], int(n / 2) + 1) # function to find median of arraydef median(arr, n): if n % 2 == 0: return (arr[int(n / 2)] + arr[int(n / 2) - 1]) / 2 else: return arr[int(n/2)] # Driver codearr1 = [1, 2, 3, 6]arr2 = [4, 6, 8, 10]n = len(arr1)print(int(getMedian(arr1,arr2,n))) # This code is contributed by# baby_gog9800", "e": 24316, "s": 22280, "text": null }, { "code": "// A C# program to divide and conquer based// efficient solution to find// median of two sorted arrays// of same size.using System;class GfG{ /* This function returns medianof ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[] aresorted arraysBoth have n elements */ static int getMedian(int[] a, int[] b, int startA, int startB, int endA, int endB){ if (endA - startA == 1) { return (Math.Max(a[startA], b[startB]) + Math.Min(a[endA], b[endB])) / 2; } /* get the median of the first array */ int m1 = median(a, startA, endA); /* get the median of the second array */ int m2 = median(b, startB, endB); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) { return m1; } /*if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ else if (m1 < m2) { return getMedian(a, b, (endA + startA + 1) / 2, startB, endA, (endB + startB + 1) / 2); } /*if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ else { return getMedian(a, b, startA, (endB + startB + 1) / 2, (endA + startA + 1) / 2, endB); }} /* Function to get medianof a sorted array */static int median(int[] arr, int start, int end){ int n = end - start + 1; if (n % 2 == 0) { return (arr[start + (n / 2)] + arr[start + (n / 2 - 1)]) / 2; } else { return arr[start + n / 2]; }} // Driver codepublic static void Main(String[] args){ int []ar1 = {1, 2, 3, 6}; int []ar2 = {4, 6, 8, 10}; int n1 = ar1.Length; int n2 = ar2.Length; if (n1 != n2) { Console.WriteLine(\"Doesn't work for arrays \" + \"of unequal size\"); } else if (n1 == 0) { Console.WriteLine(\"Arrays are empty.\"); } else if (n1 == 1) { Console.WriteLine((ar1[0] + ar2[0]) / 2); } else { Console.WriteLine(\"Median is \" + getMedian(ar1, ar2, 0, 0, ar1.Length - 1, ar2.Length - 1)); }}} // This code is contributed by gauravrajput1", "e": 26546, "s": 24316, "text": null }, { "code": "<script>// A Javascript program to divide and conquer based// efficient solution to find// median of two sorted arrays// of same size. /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */function getMedian(a,b,startA,startB,endA,endB){ if (endA - startA == 1) { return ( Math.max(a[startA], b[startB]) + Math.min(a[endA], b[endB])) / 2; } /* get the median of the first array */ let m1 = median(a, startA, endA); /* get the median of the second array */ let m2 = median(b, startB, endB); /* If medians are equal then return either m1 or m2 */ if (m1 == m2) { return m1; } /* if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] */ else if (m1 < m2) { return getMedian( a, b, (endA + startA + 1) / 2, startB, endA, (endB + startB + 1) / 2); } /* if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] */ else { return getMedian( a, b, startA, (endB + startB + 1) / 2, (endA + startA + 1) / 2, endB); }} /* Function to get median of a sorted array */function median(arr,start,end){ let n = end - start + 1; if (n % 2 == 0) { return ( arr[start + (n / 2)] + arr[start + (n / 2 - 1)]) / 2; } else { return arr[start + n / 2]; }} // Driver codelet ar1 = [ 1, 2, 3, 6 ]; let ar2 = [ 4, 6, 8, 10 ]; let n1 = ar1.length; let n2 = ar2.length; if (n1 != n2) { document.write( \"Doesn't work for arrays \" + \"of unequal size<br>\"); } else if (n1 == 0) { document.write(\"Arrays are empty.<br>\"); } else if (n1 == 1) { document.write((ar1[0] + ar2[0]) / 2+\"<br>\"); } else { document.write( \"Median is \" + getMedian( ar1, ar2, 0, 0, ar1.length - 1, ar2.length - 1)+\"<br>\"); } // This code is contributed by avanitrachhadiya2155</script>", "e": 29020, "s": 26546, "text": null }, { "code": null, "e": 29032, "s": 29020, "text": "Median is 5" }, { "code": null, "e": 29121, "s": 29032, "text": "Time Complexity : O(logn) Auxiliary Space: O(1)Algorithmic Paradigm: Divide and Conquer " }, { "code": null, "e": 29252, "s": 29121, "text": "Method 3 (By Merging two arrays w/o extra space)This method works by merging two arrays without extra space and then sorting them." }, { "code": null, "e": 29265, "s": 29252, "text": "Algorithm : " }, { "code": null, "e": 29469, "s": 29265, "text": "1) Merge the two input arrays ar1[] and ar2[].\n2) Sort ar1[] and ar2[] respectively.\n3) The median will be the last element of ar1[] + the first\n element of ar2[] divided by 2. [(ar1[n-1] + ar2[0])/2]." }, { "code": null, "e": 29520, "s": 29469, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29524, "s": 29520, "text": "C++" }, { "code": null, "e": 29526, "s": 29524, "text": "C" }, { "code": null, "e": 29531, "s": 29526, "text": "Java" }, { "code": null, "e": 29539, "s": 29531, "text": "Python3" }, { "code": null, "e": 29542, "s": 29539, "text": "C#" }, { "code": null, "e": 29553, "s": 29542, "text": "Javascript" }, { "code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; /* This function returnsmedian of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[]are sorted arraysBoth have n elements */int getMedian(int ar1[], int ar2[], int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) swap(ar1[i--], ar2[j++]); sort(ar1, ar1 + n); sort(ar2, ar2 + n); return (ar1[n - 1] + ar2[0]) / 2;} // Driver Codeint main(){ int ar1[] = { 1, 12, 15, 26, 38 }; int ar2[] = { 2, 13, 17, 30, 45 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) cout << \"Median is \" << getMedian(ar1, ar2, n1); else cout << \"Doesn't work for arrays\" << \" of unequal size\"; getchar(); return 0;} // This code is contributed// by Lakshay", "e": 30429, "s": 29553, "text": null }, { "code": "// C program for the above approach#include <stdio.h>#include <stdlib.h> /* This function returnsmedian of ar1[] and ar2[].Assumptions in this function:Both ar1[] and ar2[]are sorted arraysBoth have n elements */ // compare function, compares two elementsint compare(const void* num1, const void* num2){ if (*(int*)num1 > *(int*)num2) return 1; else return -1;} int getMedian(int ar1[], int ar2[], int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { int temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } qsort(ar1, n, sizeof(int), compare); qsort(ar2, n, sizeof(int), compare); return (ar1[n - 1] + ar2[0]) / 2;} // Driver Codeint main(){ int ar1[] = { 1, 12, 15, 26, 38 }; int ar2[] = { 2, 13, 17, 30, 45 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); if (n1 == n2) printf(\"Median is %d \", getMedian(ar1, ar2, n1)); else printf(\"Doesn't work for arrays of unequal size\"); return 0;} // This code is contributed by Deepthi", "e": 31544, "s": 30429, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*;import java.util.*;class GFG{ /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */public static int getMedian(int ar1[], int ar2[], int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { int temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } Arrays.sort(ar1); Arrays.sort(ar2); return (ar1[n - 1] + ar2[0]) / 2;} // Driver codepublic static void main (String[] args){ int ar1[] = { 1, 12, 15, 26, 38 }; int ar2[] = { 2, 13, 17, 30, 45 }; int n1 = 5; int n2 = 5; if (n1 == n2) System.out.println(\"Median is \"+ getMedian(ar1, ar2, n1)); else System.out.println(\"Doesn't work for arrays of unequal size\");}} // This code is contributed by Manu Pathria", "e": 32495, "s": 31544, "text": null }, { "code": "# Python program for above approach # function to return median of the arrays# both are sorted & of same sizedef getMedian(ar1, ar2, n): i, j = n - 1, 0 # while loop to swap all smaller numbers to arr1 while(ar1[i] > ar2[j] and i > -1 and j < n): ar1[i], ar2[j] = ar2[j], ar1[i] i -= 1 j += 1 ar1.sort() ar2.sort() return (ar1[-1] + ar2[0]) >> 1 # Driver programif __name__ == '__main__': ar1 = [1, 12, 15, 26, 38] ar2 = [2, 13, 17, 30, 45] n1, n2 = len(ar1), len(ar2) if(n1 == n2): print('Median is', getMedian(ar1, ar2, n1)) else: print(\"Doesn't work for arrays of unequal size\") # This code is contributed by saitejagampala", "e": 33205, "s": 32495, "text": null }, { "code": "/*package whatever //do not write package name here */using System;public class GFG{ /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */public static int getMedian(int []ar1, int []ar2, int n){ int j = 0; int i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { int temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } Array.Sort(ar1); Array.Sort(ar2); return (ar1[n - 1] + ar2[0]) / 2;} // Driver codepublic static void Main(String[] args){ int []ar1 = { 1, 12, 15, 26, 38 }; int []ar2 = { 2, 13, 17, 30, 45 }; int n1 = 5; int n2 = 5; if (n1 == n2) Console.WriteLine(\"Median is \"+ getMedian(ar1, ar2, n1)); else Console.WriteLine(\"Doesn't work for arrays of unequal size\");}} // This code is contributed by aashish1995", "e": 34134, "s": 33205, "text": null }, { "code": "<script> /* This function returns median of ar1[] and ar2[]. Assumptions in this function: Both ar1[] and ar2[] are sorted arrays Both have n elements */ function getMedian(ar1, ar2, n) { let j = 0; let i = n - 1; while (ar1[i] > ar2[j] && j < n && i > -1) { let temp = ar1[i]; ar1[i] = ar2[j]; ar2[j] = temp; i--; j++; } ar1.sort(function(a, b){return a - b}); ar2.sort(function(a, b){return a - b}); return parseInt((ar1[n - 1] + ar2[0]) / 2, 10); } let ar1 = [ 1, 12, 15, 26, 38 ]; let ar2 = [ 2, 13, 17, 30, 45 ]; let n1 = 5; let n2 = 5; if (n1 == n2) document.write(\"Median is \"+ getMedian(ar1, ar2, n1)); else document.write(\"Doesn't work for arrays of unequal size\"); </script>", "e": 34937, "s": 34134, "text": null }, { "code": null, "e": 34950, "s": 34937, "text": "Median is 16" }, { "code": null, "e": 34997, "s": 34950, "text": "Time Complexity: O(nlogn)Auxiliary Space: O(1)" }, { "code": null, "e": 35365, "s": 34997, "text": "Median of two sorted arrays of different sizesReferences: http://en.wikipedia.org/wiki/Medianhttp://ocw.alfaisal.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-046JFall-2005/30C68118-E436-4FE3-8C79-6BAFBB07D935/0/ps9sol.pdf ds3etph5wnPlease write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem." }, { "code": null, "e": 35381, "s": 35365, "text": "SaumyaBhatnagar" }, { "code": null, "e": 35387, "s": 35381, "text": "jit_t" }, { "code": null, "e": 35400, "s": 35387, "text": "nitin mittal" }, { "code": null, "e": 35415, "s": 35400, "text": "Shivi_Aggarwal" }, { "code": null, "e": 35428, "s": 35415, "text": "prerna saini" }, { "code": null, "e": 35438, "s": 35428, "text": "lilkucfer" }, { "code": null, "e": 35457, "s": 35438, "text": "Harshita Chaudhary" }, { "code": null, "e": 35470, "s": 35457, "text": "MohammadOmar" }, { "code": null, "e": 35484, "s": 35470, "text": "GauravRajput1" }, { "code": null, "e": 35493, "s": 35484, "text": "benjam1n" }, { "code": null, "e": 35505, "s": 35493, "text": "manupathria" }, { "code": null, "e": 35520, "s": 35505, "text": "saitejagampala" }, { "code": null, "e": 35532, "s": 35520, "text": "aashish1995" }, { "code": null, "e": 35539, "s": 35532, "text": "rrrtnx" }, { "code": null, "e": 35552, "s": 35539, "text": "2435shivkant" }, { "code": null, "e": 35571, "s": 35552, "text": "vaibhavrabadiya117" }, { "code": null, "e": 35592, "s": 35571, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35608, "s": 35592, "text": "subhammahato348" }, { "code": null, "e": 35624, "s": 35608, "text": "souravmahato348" }, { "code": null, "e": 35638, "s": 35624, "text": "deepthiinduri" }, { "code": null, "e": 35645, "s": 35638, "text": "Code_r" }, { "code": null, "e": 35661, "s": 35645, "text": "sanyamjain10168" }, { "code": null, "e": 35670, "s": 35661, "text": "Accolite" }, { "code": null, "e": 35677, "s": 35670, "text": "Amazon" }, { "code": null, "e": 35686, "s": 35677, "text": "D-E-Shaw" }, { "code": null, "e": 35694, "s": 35686, "text": "FactSet" }, { "code": null, "e": 35709, "s": 35694, "text": "median-finding" }, { "code": null, "e": 35717, "s": 35709, "text": "Samsung" }, { "code": null, "e": 35740, "s": 35717, "text": "statistical-algorithms" }, { "code": null, "e": 35747, "s": 35740, "text": "Arrays" }, { "code": null, "e": 35766, "s": 35747, "text": "Divide and Conquer" }, { "code": null, "e": 35779, "s": 35766, "text": "Mathematical" }, { "code": null, "e": 35789, "s": 35779, "text": "Searching" }, { "code": null, "e": 35798, "s": 35789, "text": "Accolite" }, { "code": null, "e": 35805, "s": 35798, "text": "Amazon" }, { "code": null, "e": 35813, "s": 35805, "text": "Samsung" }, { "code": null, "e": 35822, "s": 35813, "text": "D-E-Shaw" }, { "code": null, "e": 35830, "s": 35822, "text": "FactSet" }, { "code": null, "e": 35837, "s": 35830, "text": "Arrays" }, { "code": null, "e": 35847, "s": 35837, "text": "Searching" }, { "code": null, "e": 35860, "s": 35847, "text": "Mathematical" }, { "code": null, "e": 35879, "s": 35860, "text": "Divide and Conquer" }, { "code": null, "e": 35977, "s": 35879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35992, "s": 35977, "text": "Arrays in Java" }, { "code": null, "e": 36038, "s": 35992, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 36106, "s": 36038, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36150, "s": 36106, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36182, "s": 36150, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 36193, "s": 36182, "text": "Merge Sort" }, { "code": null, "e": 36203, "s": 36193, "text": "QuickSort" }, { "code": null, "e": 36271, "s": 36203, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36327, "s": 36271, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" } ]
Pyscaffold module in Python
19 Nov, 2021 Starting off with a Python project is usually quite complex and complicated as it involves setting up and configuring some files. This is where Pyscaffold comes in. It is a tool to set up a new python project, is very easy to use and sets up your project in less than 10 seconds! To use Pyscaffold, Git is a must, especially Windows users should have “Git Bash” installed. Additionally, the installation of PyScaffold also requires a recent version of “setup tools”.Each Python package project is internally represented by PyScaffold as a tree data structure that directly relates to a directory entry in the file system. This tree is implemented as a simple dictionary in which keys indicate the path where files will be generated, while values indicate their content. To install Pyscaffold using pip, carry out the following command which installs the latest Pyscaffold version: pip install --upgrade pyscaffold In case you do not have pip installed, refer to this article: How to install pip commandPyScaffold can also be installed with conda by carrying out the following on Anaconda Command Prompt: conda install -c conda-forge pyscaffold If you see anything like this, then this means Pyscaffold has been installed successfully! PyScaffold comes with a lot of characteristics and configuration defaults to make the frequent tasks in developing, maintaining and distributing your own Python package as easy as possible. To set up a new python project, use the putup command: putup Your_Project This creates a folder Your_Project with the project layout of a Python project and it has a Your_Project package folder along with documents and tests folders and the files setup.py, setup.cfg, AUTHORS.txt, README.txt, and LICENSE.txt. All configuration is done in “setup.cfg” instead of setup.py. Here, you can change all the settings related to the package (i.e., author, URL, license, etc.). Also, to add additional data files, we can add their names in the setup.cfg and they’ll be automatically added. PyScaffold is designed to cover the essentials of authoring and distributing Python packages. Most of the time, setting up putup options is enough to ensure the proper configuration of a project. PyScaffold can be extended at runtime by other Python packages. It is also possible to write an external script or program that embeds PyScaffold and use it to perform some user-defined actions.Example: Python3 # Temporarily adjust padding# while executing a context.from pyscaffold.log import logger logger.report('invoke', 'custom_action')with logger.indent(): logger.report('create', 'some / file / path') # Expected logs:# --------------------------------------# invoke custom_action# create some / file / path# --------------------------------------# Note how the spacing between activity and# subject in the# second entry is greater than the equivalent# in the first one. Updates: Whenever a new update of PyScaffold gets released, you can use this command to update the structure/scaffold of your project: output --update my_project An update will only update files that are not usually used or modified by the user, therefore, to update all the files, use force update: --update --force Note: If you are updating from a PyScaffold version before 2.0, you must manually remove the files versioneer.py and MANIFEST.in.If you are updating from a version before 2.2, you must remove ${PACKAGE}/_version.py. If you are updating from a PyScaffold version before 2.0, you must manually remove the files versioneer.py and MANIFEST.in. If you are updating from a version before 2.2, you must remove ${PACKAGE}/_version.py. Initially, the project (let’s say my_project) has to be on a Git repository and includes a package (let’s say my_package) along with your python modules.Note: Your working tree is not dirty, i.e. all changes are committed and all important files are under version control. Start by changing into the parent folder of my_project and type the following command in order to deploy the new project structure in your repository. putup my_project --force --no-skeleton -p my_package Change into my_project and move your old package folder into src with this command and use the same technique if the project has a test folder other than tests or a documentation folder other than docs. git mv my_package/* src/my_package/ Use git status to check for untracked files and add them with git add. . Eventually, use git difftool to check all overwritten files for changes that need to be transferred. All configuration that you may have done in setup.py, need to be moved to setup.cfg. In most cases you will not need to make changes to the new setup.py file provided by PyScaffold. Run these commands to check everything works: run python setup.py install and python setup.pysdist Also run python setup.py docs and python setup.py test to check that Sphinx and PyTest runs correctly. prachisoda1234 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Nov, 2021" }, { "code": null, "e": 824, "s": 52, "text": "Starting off with a Python project is usually quite complex and complicated as it involves setting up and configuring some files. This is where Pyscaffold comes in. It is a tool to set up a new python project, is very easy to use and sets up your project in less than 10 seconds! To use Pyscaffold, Git is a must, especially Windows users should have “Git Bash” installed. Additionally, the installation of PyScaffold also requires a recent version of “setup tools”.Each Python package project is internally represented by PyScaffold as a tree data structure that directly relates to a directory entry in the file system. This tree is implemented as a simple dictionary in which keys indicate the path where files will be generated, while values indicate their content. " }, { "code": null, "e": 936, "s": 824, "text": "To install Pyscaffold using pip, carry out the following command which installs the latest Pyscaffold version: " }, { "code": null, "e": 969, "s": 936, "text": "pip install --upgrade pyscaffold" }, { "code": null, "e": 1160, "s": 969, "text": "In case you do not have pip installed, refer to this article: How to install pip commandPyScaffold can also be installed with conda by carrying out the following on Anaconda Command Prompt: " }, { "code": null, "e": 1200, "s": 1160, "text": "conda install -c conda-forge pyscaffold" }, { "code": null, "e": 1292, "s": 1200, "text": "If you see anything like this, then this means Pyscaffold has been installed successfully! " }, { "code": null, "e": 1539, "s": 1292, "text": "PyScaffold comes with a lot of characteristics and configuration defaults to make the frequent tasks in developing, maintaining and distributing your own Python package as easy as possible. To set up a new python project, use the putup command: " }, { "code": null, "e": 1558, "s": 1539, "text": "putup Your_Project" }, { "code": null, "e": 2465, "s": 1558, "text": "This creates a folder Your_Project with the project layout of a Python project and it has a Your_Project package folder along with documents and tests folders and the files setup.py, setup.cfg, AUTHORS.txt, README.txt, and LICENSE.txt. All configuration is done in “setup.cfg” instead of setup.py. Here, you can change all the settings related to the package (i.e., author, URL, license, etc.). Also, to add additional data files, we can add their names in the setup.cfg and they’ll be automatically added. PyScaffold is designed to cover the essentials of authoring and distributing Python packages. Most of the time, setting up putup options is enough to ensure the proper configuration of a project. PyScaffold can be extended at runtime by other Python packages. It is also possible to write an external script or program that embeds PyScaffold and use it to perform some user-defined actions.Example: " }, { "code": null, "e": 2473, "s": 2465, "text": "Python3" }, { "code": "# Temporarily adjust padding# while executing a context.from pyscaffold.log import logger logger.report('invoke', 'custom_action')with logger.indent(): logger.report('create', 'some / file / path') # Expected logs:# --------------------------------------# invoke custom_action# create some / file / path# --------------------------------------# Note how the spacing between activity and# subject in the# second entry is greater than the equivalent# in the first one.", "e": 2948, "s": 2473, "text": null }, { "code": null, "e": 2958, "s": 2948, "text": "Updates: " }, { "code": null, "e": 3085, "s": 2958, "text": "Whenever a new update of PyScaffold gets released, you can use this command to update the structure/scaffold of your project: " }, { "code": null, "e": 3112, "s": 3085, "text": "output --update my_project" }, { "code": null, "e": 3251, "s": 3112, "text": "An update will only update files that are not usually used or modified by the user, therefore, to update all the files, use force update: " }, { "code": null, "e": 3268, "s": 3251, "text": "--update --force" }, { "code": null, "e": 3484, "s": 3268, "text": "Note: If you are updating from a PyScaffold version before 2.0, you must manually remove the files versioneer.py and MANIFEST.in.If you are updating from a version before 2.2, you must remove ${PACKAGE}/_version.py." }, { "code": null, "e": 3608, "s": 3484, "text": "If you are updating from a PyScaffold version before 2.0, you must manually remove the files versioneer.py and MANIFEST.in." }, { "code": null, "e": 3695, "s": 3608, "text": "If you are updating from a version before 2.2, you must remove ${PACKAGE}/_version.py." }, { "code": null, "e": 3970, "s": 3697, "text": "Initially, the project (let’s say my_project) has to be on a Git repository and includes a package (let’s say my_package) along with your python modules.Note: Your working tree is not dirty, i.e. all changes are committed and all important files are under version control." }, { "code": null, "e": 4122, "s": 3970, "text": "Start by changing into the parent folder of my_project and type the following command in order to deploy the new project structure in your repository. " }, { "code": null, "e": 4175, "s": 4122, "text": "putup my_project --force --no-skeleton -p my_package" }, { "code": null, "e": 4379, "s": 4175, "text": "Change into my_project and move your old package folder into src with this command and use the same technique if the project has a test folder other than tests or a documentation folder other than docs. " }, { "code": null, "e": 4415, "s": 4379, "text": "git mv my_package/* src/my_package/" }, { "code": null, "e": 4486, "s": 4415, "text": "Use git status to check for untracked files and add them with git add." }, { "code": null, "e": 4771, "s": 4486, "text": ". Eventually, use git difftool to check all overwritten files for changes that need to be transferred. All configuration that you may have done in setup.py, need to be moved to setup.cfg. In most cases you will not need to make changes to the new setup.py file provided by PyScaffold." }, { "code": null, "e": 4818, "s": 4771, "text": "Run these commands to check everything works: " }, { "code": null, "e": 4871, "s": 4818, "text": "run python setup.py install and python setup.pysdist" }, { "code": null, "e": 4974, "s": 4871, "text": "Also run python setup.py docs and python setup.py test to check that Sphinx and PyTest runs correctly." }, { "code": null, "e": 4989, "s": 4974, "text": "prachisoda1234" }, { "code": null, "e": 5004, "s": 4989, "text": "python-modules" }, { "code": null, "e": 5011, "s": 5004, "text": "Python" } ]
The OFFSETOF() macro
21 Jun, 2022 We know that the elements in a structure will be stored in sequential order of their declaration. How to extract the displacement of an element in a structure? We can make use of offsetof macro. Usually we call structure and union types (or classes with trivial constructors) as plain old data (POD) types, which will be used to aggregate other data types. The following non-standard macro can be used to get the displacement of an element in bytes from the base address of the structure variable. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) Zero is casted to type of structure and required element’s address is accessed, which is casted to size_t. As per standard size_t is of type unsigned int. The overall expression results in the number of bytes after which the ELEMENT being placed in the structure. For example, the following code returns 16 bytes (padding is considered on 32 bit machine) as displacement of the character variable c in the structure Pod. C++ C #include <iostream>using namespace std; #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) typedef struct PodTag{ int i; double d; char c;} PodType; int main(){ cout << OFFSETOF(PodType, c); return 0;} // This code is contributed by sarajadhav12052009 #include <stdio.h> #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) typedef struct PodTag{ int i; double d; char c;} PodType; int main(){ printf("%lu", OFFSETOF(PodType, c)); getchar(); return 0;} In the above code, the following expression will return the displacement of element c in the structure PodType. OFFSETOF(PodType, c); After preprocessing stage the above macro expands to c ((size_t)&(((PodType *)0)->c)) Since we are considering 0 as address of the structure variable, c will be placed after 16 bytes of its base address i.e. 0x00 + 0x10. Applying & on the structure element (in this case it is c) returns the address of the element which is 0x10. Casting the address to unsigned int (size_t) results in number of bytes the element is placed in the structure. Note: We may consider the address operator & is redundant. Without address operator in macro, the code de-references the element of structure placed at NULL address. It causes an access violation exception (segmentation fault) at runtime. Note that there are other ways to implement offsetof macro according to compiler behaviour. The ultimate goal is to extract displacement of the element. We will see practical usage of offsetof macro in liked lists to connect similar objects (for example thread pool) in another article. Article compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. References: 1. Linux Kernel code. 2. http://msdn.microsoft.com/en-us/library/dz4y9b9a.aspx 3. GNU C/C++ Compiler Documentation sarajadhav12052009 C-Macro & Preprocessor 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 Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Vector in C++ STL 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++
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 550, "s": 52, "text": "We know that the elements in a structure will be stored in sequential order of their declaration. How to extract the displacement of an element in a structure? We can make use of offsetof macro. Usually we call structure and union types (or classes with trivial constructors) as plain old data (POD) types, which will be used to aggregate other data types. The following non-standard macro can be used to get the displacement of an element in bytes from the base address of the structure variable." }, { "code": null, "e": 616, "s": 550, "text": "#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))" }, { "code": null, "e": 1038, "s": 616, "text": "Zero is casted to type of structure and required element’s address is accessed, which is casted to size_t. As per standard size_t is of type unsigned int. The overall expression results in the number of bytes after which the ELEMENT being placed in the structure. For example, the following code returns 16 bytes (padding is considered on 32 bit machine) as displacement of the character variable c in the structure Pod. " }, { "code": null, "e": 1042, "s": 1038, "text": "C++" }, { "code": null, "e": 1044, "s": 1042, "text": "C" }, { "code": "#include <iostream>using namespace std; #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) typedef struct PodTag{ int i; double d; char c;} PodType; int main(){ cout << OFFSETOF(PodType, c); return 0;} // This code is contributed by sarajadhav12052009", "e": 1322, "s": 1044, "text": null }, { "code": "#include <stdio.h> #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) typedef struct PodTag{ int i; double d; char c;} PodType; int main(){ printf(\"%lu\", OFFSETOF(PodType, c)); getchar(); return 0;}", "e": 1552, "s": 1322, "text": null }, { "code": null, "e": 1664, "s": 1552, "text": "In the above code, the following expression will return the displacement of element c in the structure PodType." }, { "code": null, "e": 1686, "s": 1664, "text": "OFFSETOF(PodType, c);" }, { "code": null, "e": 1740, "s": 1686, "text": "After preprocessing stage the above macro expands to " }, { "code": null, "e": 1742, "s": 1740, "text": "c" }, { "code": "((size_t)&(((PodType *)0)->c))", "e": 1773, "s": 1742, "text": null }, { "code": null, "e": 2934, "s": 1773, "text": "Since we are considering 0 as address of the structure variable, c will be placed after 16 bytes of its base address i.e. 0x00 + 0x10. Applying & on the structure element (in this case it is c) returns the address of the element which is 0x10. Casting the address to unsigned int (size_t) results in number of bytes the element is placed in the structure. Note: We may consider the address operator & is redundant. Without address operator in macro, the code de-references the element of structure placed at NULL address. It causes an access violation exception (segmentation fault) at runtime. Note that there are other ways to implement offsetof macro according to compiler behaviour. The ultimate goal is to extract displacement of the element. We will see practical usage of offsetof macro in liked lists to connect similar objects (for example thread pool) in another article. Article compiled by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. References: 1. Linux Kernel code. 2. http://msdn.microsoft.com/en-us/library/dz4y9b9a.aspx 3. GNU C/C++ Compiler Documentation" }, { "code": null, "e": 2953, "s": 2934, "text": "sarajadhav12052009" }, { "code": null, "e": 2976, "s": 2953, "text": "C-Macro & Preprocessor" }, { "code": null, "e": 2987, "s": 2976, "text": "C Language" }, { "code": null, "e": 2991, "s": 2987, "text": "C++" }, { "code": null, "e": 2995, "s": 2991, "text": "CPP" }, { "code": null, "e": 3093, "s": 2995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3110, "s": 3093, "text": "Substring in C++" }, { "code": null, "e": 3132, "s": 3110, "text": "Function Pointer in C" }, { "code": null, "e": 3177, "s": 3132, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3202, "s": 3177, "text": "std::string class in C++" }, { "code": null, "e": 3250, "s": 3202, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3268, "s": 3250, "text": "Vector in C++ STL" }, { "code": null, "e": 3311, "s": 3268, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 3357, "s": 3311, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3400, "s": 3357, "text": "Set in C++ Standard Template Library (STL)" } ]
HTML frameset Tag
17 Mar, 2022 The <frameset> tag in HTML is used to define the frameset. The <frameset> element contains one or more frame elements. It is used to specify the number of rows and columns in frameset with their pixel of spaces. Each element can hold a separate document. Note: The <frameset> tag is not supported in HTML5. Syntax: <frameset cols = "pixels|%|*"> Attributes: The list of frameset attributes are given below: cols: The cols attribute is used to create vertical frames in a web browser. This attribute is basically used to define the no. of columns and their size inside the frameset tag. rows: The rows attribute is used to create horizontal frames in the web browser. This attribute is used to define the no. of rows and their size inside the frameset tag. border: This attribute of frameset tag defines the width of the border of each frame in pixels. Zero value is used for no border. frameborder: This attribute of frameset tag is used to specify whether a three-dimensional border should be displayed between the frames or not for this use two values 0 and 1, where 0 defines no border and value 1 signifies for yes there will be a border. framespacing: This attribute of frameset tag is used to specify the amount of spacing between the frames in a frameset. This can take any integer value as a parameter which basically denotes the value in pixel. Below examples illustrate the <frameset> element in HTML:Example 1: HTML <!DOCTYPE html><html> <head> <title>frameset attribute</title> </head> <!-- frameset attribute starts here --> <frameset rows = "20%, 60%, 20%"> <frame name = "top" src = "attr1.png" /> <frame name = "main" src = "gradient3.png" /> <frame name = "bottom" src = "col_last.png" /> <noframes> <body>The browser you are working does not support frames.</body> </noframes> </frameset> <!-- frameset attribute ends here --></html> Output: The above example basically used to create three horizontal frames: top, middle, and bottom using row attribute of frameset tag, and the noframe tag is used for that browser that doesn’t support noframe. Example 2: HTML <!DOCTYPE html><html> <head> <title>frameset attribute</title> </head> <frameset cols = "30%, 40%, 30%"> <frame name = "top" src = "attr1.png" /> <frame name = "main" src = "gradient3.png" /> <frame name = "bottom" src = "col_last.png" /> <noframes> <body>The browser you are working does not support frames.</body> </noframes> </frameset></html> Output: The above example basically used to create three vertical frames: left, center, and right using col attribute of frameset tag. Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari shubhamyadav4 HTML-Tags Picked Technical Scripter 2018 HTML Technical Scripter HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Mar, 2022" }, { "code": null, "e": 308, "s": 52, "text": "The <frameset> tag in HTML is used to define the frameset. The <frameset> element contains one or more frame elements. It is used to specify the number of rows and columns in frameset with their pixel of spaces. Each element can hold a separate document. " }, { "code": null, "e": 360, "s": 308, "text": "Note: The <frameset> tag is not supported in HTML5." }, { "code": null, "e": 369, "s": 360, "text": "Syntax: " }, { "code": null, "e": 400, "s": 369, "text": "<frameset cols = \"pixels|%|*\">" }, { "code": null, "e": 463, "s": 400, "text": "Attributes: The list of frameset attributes are given below: " }, { "code": null, "e": 642, "s": 463, "text": "cols: The cols attribute is used to create vertical frames in a web browser. This attribute is basically used to define the no. of columns and their size inside the frameset tag." }, { "code": null, "e": 812, "s": 642, "text": "rows: The rows attribute is used to create horizontal frames in the web browser. This attribute is used to define the no. of rows and their size inside the frameset tag." }, { "code": null, "e": 942, "s": 812, "text": "border: This attribute of frameset tag defines the width of the border of each frame in pixels. Zero value is used for no border." }, { "code": null, "e": 1199, "s": 942, "text": "frameborder: This attribute of frameset tag is used to specify whether a three-dimensional border should be displayed between the frames or not for this use two values 0 and 1, where 0 defines no border and value 1 signifies for yes there will be a border." }, { "code": null, "e": 1410, "s": 1199, "text": "framespacing: This attribute of frameset tag is used to specify the amount of spacing between the frames in a frameset. This can take any integer value as a parameter which basically denotes the value in pixel." }, { "code": null, "e": 1479, "s": 1410, "text": "Below examples illustrate the <frameset> element in HTML:Example 1: " }, { "code": null, "e": 1484, "s": 1479, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>frameset attribute</title> </head> <!-- frameset attribute starts here --> <frameset rows = \"20%, 60%, 20%\"> <frame name = \"top\" src = \"attr1.png\" /> <frame name = \"main\" src = \"gradient3.png\" /> <frame name = \"bottom\" src = \"col_last.png\" /> <noframes> <body>The browser you are working does not support frames.</body> </noframes> </frameset> <!-- frameset attribute ends here --></html> ", "e": 2052, "s": 1484, "text": null }, { "code": null, "e": 2266, "s": 2052, "text": "Output: The above example basically used to create three horizontal frames: top, middle, and bottom using row attribute of frameset tag, and the noframe tag is used for that browser that doesn’t support noframe. " }, { "code": null, "e": 2279, "s": 2266, "text": "Example 2: " }, { "code": null, "e": 2284, "s": 2279, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>frameset attribute</title> </head> <frameset cols = \"30%, 40%, 30%\"> <frame name = \"top\" src = \"attr1.png\" /> <frame name = \"main\" src = \"gradient3.png\" /> <frame name = \"bottom\" src = \"col_last.png\" /> <noframes> <body>The browser you are working does not support frames.</body> </noframes> </frameset></html>", "e": 2728, "s": 2284, "text": null }, { "code": null, "e": 2865, "s": 2728, "text": "Output: The above example basically used to create three vertical frames: left, center, and right using col attribute of frameset tag. " }, { "code": null, "e": 2886, "s": 2865, "text": "Supported Browsers: " }, { "code": null, "e": 2900, "s": 2886, "text": "Google Chrome" }, { "code": null, "e": 2918, "s": 2900, "text": "Internet Explorer" }, { "code": null, "e": 2926, "s": 2918, "text": "Firefox" }, { "code": null, "e": 2932, "s": 2926, "text": "Opera" }, { "code": null, "e": 2939, "s": 2932, "text": "Safari" }, { "code": null, "e": 2955, "s": 2941, "text": "shubhamyadav4" }, { "code": null, "e": 2965, "s": 2955, "text": "HTML-Tags" }, { "code": null, "e": 2972, "s": 2965, "text": "Picked" }, { "code": null, "e": 2996, "s": 2972, "text": "Technical Scripter 2018" }, { "code": null, "e": 3001, "s": 2996, "text": "HTML" }, { "code": null, "e": 3020, "s": 3001, "text": "Technical Scripter" }, { "code": null, "e": 3025, "s": 3020, "text": "HTML" } ]
UGC-NET | UGC NET CS 2016 Aug – II | Question 38
11 Apr, 2018 Consider a system having ‘m’ resources of the same type. These resources are shared by three processes P1, P2and P3 which have peak demands of 2, 5 and 7 resources respectively. For what value of ‘m’ deadlock will not occur ?(A) 70(B) 14(C) 13(D) 7Answer: (B)Explanation: To avoid deadlock ‘m’ >= peak demands(P1 + P2 + P3)i.e. m >= peak demands(2 + 5 + 7)m >= peak demands(14)So, option (B) is correct.Quiz of this Question UGC-NET Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Apr, 2018" }, { "code": null, "e": 453, "s": 28, "text": "Consider a system having ‘m’ resources of the same type. These resources are shared by three processes P1, P2and P3 which have peak demands of 2, 5 and 7 resources respectively. For what value of ‘m’ deadlock will not occur ?(A) 70(B) 14(C) 13(D) 7Answer: (B)Explanation: To avoid deadlock ‘m’ >= peak demands(P1 + P2 + P3)i.e. m >= peak demands(2 + 5 + 7)m >= peak demands(14)So, option (B) is correct.Quiz of this Question" }, { "code": null, "e": 461, "s": 453, "text": "UGC-NET" } ]
Python time gmtime() Method
Pythom time method gmtime() converts a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. Following is the syntax for gmtime() method − time.gmtime([ sec ]) sec − These are the number of seconds to be converted into structure struct_time representation. sec − These are the number of seconds to be converted into structure struct_time representation. This method does not return any value. The following example shows the usage of gmtime() method. #!/usr/bin/python import time print "time.gmtime() : %s" % time.gmtime() When we run above program, it produces following result − time.gmtime() : (2009, 2, 17, 17, 3, 38, 1, 48, 0)
[ { "code": null, "e": 2602, "s": 2378, "text": "Pythom time method gmtime() converts a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used." }, { "code": null, "e": 2648, "s": 2602, "text": "Following is the syntax for gmtime() method −" }, { "code": null, "e": 2670, "s": 2648, "text": "time.gmtime([ sec ])\n" }, { "code": null, "e": 2767, "s": 2670, "text": "sec − These are the number of seconds to be converted into structure struct_time representation." }, { "code": null, "e": 2864, "s": 2767, "text": "sec − These are the number of seconds to be converted into structure struct_time representation." }, { "code": null, "e": 2903, "s": 2864, "text": "This method does not return any value." }, { "code": null, "e": 2961, "s": 2903, "text": "The following example shows the usage of gmtime() method." }, { "code": null, "e": 3035, "s": 2961, "text": "#!/usr/bin/python\nimport time\n\nprint \"time.gmtime() : %s\" % time.gmtime()" }, { "code": null, "e": 3093, "s": 3035, "text": "When we run above program, it produces following result −" } ]
Deadlock in Java Multithreading
28 Jun, 2021 synchronized keyword is used to make the class or method thread-safe which means only one thread can have lock of synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock. It is important to use if our program is running in multi-threaded environment where two or more threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock. Below is a simple example of Deadlock condition. Java // Java program to illustrate Deadlock// in multithreading.class Util{ // Util class to sleep a thread static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } }} // This class is shared by both threadsclass Shared{ // first synchronized method synchronized void test1(Shared s2) { System.out.println("test1-begin"); Util.sleep(1000); // taking object lock of s2 enters // into test2 method s2.test2(); System.out.println("test1-end"); } // second synchronized method synchronized void test2() { System.out.println("test2-begin"); Util.sleep(1000); // taking object lock of s1 enters // into test1 method System.out.println("test2-end"); }} class Thread1 extends Thread{ private Shared s1; private Shared s2; // constructor to initialize fields public Thread1(Shared s1, Shared s2) { this.s1 = s1; this.s2 = s2; } // run method to start a thread @Override public void run() { // taking object lock of s1 enters // into test1 method s1.test1(s2); }} class Thread2 extends Thread{ private Shared s1; private Shared s2; // constructor to initialize fields public Thread2(Shared s1, Shared s2) { this.s1 = s1; this.s2 = s2; } // run method to start a thread @Override public void run() { // taking object lock of s2 // enters into test2 method s2.test1(s1); }} public class Deadlock{ public static void main(String[] args) { // creating one object Shared s1 = new Shared(); // creating second object Shared s2 = new Shared(); // creating first thread and starting it Thread1 t1 = new Thread1(s1, s2); t1.start(); // creating second thread and starting it Thread2 t2 = new Thread2(s1, s2); t2.start(); // sleeping main thread Util.sleep(2000); }} Output : test1-begin test2-begin It is not recommended to run the above program with online IDE. We can copy the source code and run it on our local machine. We can see that it runs for indefinite time, because threads are in deadlock condition and doesn’t let code to execute. Now let’s see step by step what is happening there. Thread t1 starts and calls test1 method by taking the object lock of s1.Thread t2 starts and calls test1 method by taking the object lock of s2.t1 prints test1-begin and t2 prints test-2 begin and both waits for 1 second, so that both threads can be started if any of them is not.t1 tries to take object lock of s2 and call method test2 but as it is already acquired by t2 so it waits till it become free. It will not release lock of s1 until it gets lock of s2.Same happens with t2. It tries to take object lock of s1 and call method test1 but it is already acquired by t1, so it has to wait till t1 release the lock. t2 will also not release lock of s2 until it gets lock of s1.Now, both threads are in wait state, waiting for each other to release locks. Now there is a race around condition that who will release the lock first.As none of them is ready to release lock, so this is the Dead Lock condition.When you will run this program, it will be look like execution is paused. Thread t1 starts and calls test1 method by taking the object lock of s1. Thread t2 starts and calls test1 method by taking the object lock of s2. t1 prints test1-begin and t2 prints test-2 begin and both waits for 1 second, so that both threads can be started if any of them is not. t1 tries to take object lock of s2 and call method test2 but as it is already acquired by t2 so it waits till it become free. It will not release lock of s1 until it gets lock of s2. Same happens with t2. It tries to take object lock of s1 and call method test1 but it is already acquired by t1, so it has to wait till t1 release the lock. t2 will also not release lock of s2 until it gets lock of s1. Now, both threads are in wait state, waiting for each other to release locks. Now there is a race around condition that who will release the lock first. As none of them is ready to release lock, so this is the Dead Lock condition. When you will run this program, it will be look like execution is paused. Detect Dead Lock condition We can also detect deadlock by running this program on cmd. We have to collect Thread Dump. Command to collect depends on OS type. If we are using Windows and Java 8, command is jcmd $PID Thread.print We can get PID by running jps command. Thread dump for above program is below: jcmd 18692 Thread.print 18692: 2020-06-08 19:03:10 Full thread dump OpenJDK 64-Bit Server VM (11.0.4+10-b304.69 mixed mode, sharing): Threads class SMR info: _java_thread_list=0x0000017f44b69f20, length=13, elements={ 0x0000017f43f77000, 0x0000017f43f79800, 0x0000017f43f90000, 0x0000017f43f91000, 0x0000017f43f95000, 0x0000017f43fa5000, 0x0000017f43fb0800, 0x0000017f43f5b800, 0x0000017f44bc9000, 0x0000017f44afb000, 0x0000017f44bd7800, 0x0000017f44bd8800, 0x0000017f298c9000 } "Reference Handler" #2 daemon prio=10 os_prio=2 cpu=0.00ms elapsed=57.48s tid=0x0000017f43f77000 nid=0x6050 waiting on condition [0x0000005f800ff000] java.lang.Thread.State: RUNNABLE at java.lang.ref.Reference.waitForReferencePendingList(java.base@11.0.4/Native Method) at java.lang.ref.Reference.processPendingReferences(java.base@11.0.4/Reference.java:241) at java.lang.ref.Reference$ReferenceHandler.run(java.base@11.0.4/Reference.java:213) "Finalizer" #3 daemon prio=8 os_prio=1 cpu=0.00ms elapsed=57.48s tid=0x0000017f43f79800 nid=0x2824 in Object.wait() [0x0000005f801fe000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(java.base@11.0.4/Native Method) - waiting on (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(java.base@11.0.4/ReferenceQueue.java:155) - waiting to re-lock in wait() (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(java.base@11.0.4/ReferenceQueue.java:176) at java.lang.ref.Finalizer$FinalizerThread.run(java.base@11.0.4/Finalizer.java:170) "Signal Dispatcher" #4 daemon prio=9 os_prio=2 cpu=0.00ms elapsed=57.47s tid=0x0000017f43f90000 nid=0x1710 runnable [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Attach Listener" #5 daemon prio=5 os_prio=2 cpu=31.25ms elapsed=57.47s tid=0x0000017f43f91000 nid=0x4ff4 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "C2 CompilerThread0" #6 daemon prio=9 os_prio=2 cpu=46.88ms elapsed=57.47s tid=0x0000017f43f95000 nid=0x350c waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE No compile task "C1 CompilerThread0" #9 daemon prio=9 os_prio=2 cpu=93.75ms elapsed=57.47s tid=0x0000017f43fa5000 nid=0x4900 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE No compile task "Sweeper thread" #10 daemon prio=9 os_prio=2 cpu=0.00ms elapsed=57.47s tid=0x0000017f43fb0800 nid=0x6120 runnable [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Common-Cleaner" #11 daemon prio=8 os_prio=1 cpu=0.00ms elapsed=57.44s tid=0x0000017f43f5b800 nid=0x5a4 in Object.wait() [0x0000005f807fe000] java.lang.Thread.State: TIMED_WAITING (on object monitor) at java.lang.Object.wait(java.base@11.0.4/Native Method) - waiting on (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(java.base@11.0.4/ReferenceQueue.java:155) - waiting to re-lock in wait() (a java.lang.ref.ReferenceQueue$Lock) at jdk.internal.ref.CleanerImpl.run(java.base@11.0.4/CleanerImpl.java:148) at java.lang.Thread.run(java.base@11.0.4/Thread.java:834) at jdk.internal.misc.InnocuousThread.run(java.base@11.0.4/InnocuousThread.java:134) "Monitor Ctrl-Break" #12 daemon prio=5 os_prio=0 cpu=15.63ms elapsed=57.36s tid=0x0000017f44bc9000 nid=0x5954 runnable [0x0000005f809fe000] java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(java.base@11.0.4/Native Method) at java.net.SocketInputStream.socketRead(java.base@11.0.4/SocketInputStream.java:115) at java.net.SocketInputStream.read(java.base@11.0.4/SocketInputStream.java:168) at java.net.SocketInputStream.read(java.base@11.0.4/SocketInputStream.java:140) at sun.nio.cs.StreamDecoder.readBytes(java.base@11.0.4/StreamDecoder.java:284) at sun.nio.cs.StreamDecoder.implRead(java.base@11.0.4/StreamDecoder.java:326) at sun.nio.cs.StreamDecoder.read(java.base@11.0.4/StreamDecoder.java:178) - locked (a java.io.InputStreamReader) at java.io.InputStreamReader.read(java.base@11.0.4/InputStreamReader.java:185) at java.io.BufferedReader.fill(java.base@11.0.4/BufferedReader.java:161) at java.io.BufferedReader.readLine(java.base@11.0.4/BufferedReader.java:326) - locked (a java.io.InputStreamReader) at java.io.BufferedReader.readLine(java.base@11.0.4/BufferedReader.java:392) at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64) "Service Thread" #13 daemon prio=9 os_prio=0 cpu=0.00ms elapsed=57.36s tid=0x0000017f44afb000 nid=0x6394 runnable [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Thread-0" #14 prio=5 os_prio=0 cpu=0.00ms elapsed=57.35s tid=0x0000017f44bd7800 nid=0x5304 waiting for monitor entry [0x0000005f80cfe000] java.lang.Thread.State: BLOCKED (on object monitor) at com.company.threads.Shared.test2(Deadlock.java:40) - waiting to lock (a com.company.threads.Shared) at com.company.threads.Shared.test1(Deadlock.java:33) - locked (a com.company.threads.Shared) at com.company.threads.Thread1.run(Deadlock.java:67) "Thread-1" #15 prio=5 os_prio=0 cpu=0.00ms elapsed=57.35s tid=0x0000017f44bd8800 nid=0xfa4 waiting for monitor entry [0x0000005f80dfe000] java.lang.Thread.State: BLOCKED (on object monitor) at com.company.threads.Shared.test2(Deadlock.java:40) - waiting to lock (a com.company.threads.Shared) at com.company.threads.Shared.test1(Deadlock.java:33) - locked (a com.company.threads.Shared) at com.company.threads.Thread2.run(Deadlock.java:90) "DestroyJavaVM" #16 prio=5 os_prio=0 cpu=171.88ms elapsed=55.35s tid=0x0000017f298c9000 nid=0x38ec waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "VM Thread" os_prio=2 cpu=0.00ms elapsed=57.49s tid=0x0000017f43f73800 nid=0x52c4 runnable "GC Thread#0" os_prio=2 cpu=0.00ms elapsed=57.51s tid=0x0000017f298e1000 nid=0x47dc runnable "G1 Main Marker" os_prio=2 cpu=0.00ms elapsed=57.51s tid=0x0000017f29911000 nid=0x61c4 runnable "G1 Conc#0" os_prio=2 cpu=0.00ms elapsed=57.51s tid=0x0000017f29912000 nid=0x61c0 runnable "G1 Refine#0" os_prio=2 cpu=0.00ms elapsed=57.50s tid=0x0000017f43e0a800 nid=0x1fa8 runnable "G1 Young RemSet Sampling" os_prio=2 cpu=0.00ms elapsed=57.50s tid=0x0000017f43e0b000 nid=0x47a4 runnable "VM Periodic Task Thread" os_prio=2 cpu=0.00ms elapsed=57.36s tid=0x0000017f44b03800 nid=0x2408 waiting on condition JNI global refs: 15, weak refs: 0 Found one Java-level deadlock: ============================= "Thread-0": waiting to lock monitor 0x0000017f43f87980 (object 0x000000008a2e9ce0, a com.company.threads.Shared), which is held by "Thread-1" "Thread-1": waiting to lock monitor 0x0000017f43f87780 (object 0x000000008a2e9cd0, a com.company.threads.Shared), which is held by "Thread-0" Java stack information for the threads listed above: =================================================== "Thread-0": at com.company.threads.Shared.test2(Deadlock.java:40) - waiting to lock (a com.company.threads.Shared) at com.company.threads.Shared.test1(Deadlock.java:33) - locked (a com.company.threads.Shared) at com.company.threads.Thread1.run(Deadlock.java:67) "Thread-1": at com.company.threads.Shared.test2(Deadlock.java:40) - waiting to lock (a com.company.threads.Shared) at com.company.threads.Shared.test1(Deadlock.java:33) - locked (a com.company.threads.Shared) at com.company.threads.Thread2.run(Deadlock.java:90) Found 1 deadlock. As we can see there is clearly mentioned that found 1 deadlock. It is possible that the same message appears when you try on your machine. Avoid Dead Lock condition We can avoid dead lock condition by knowing its possibilities. It’s a very complex process and not easy to catch. But still if we try, we can avoid this. There are some methods by which we can avoid this condition. We can’t completely remove its possibility but we can reduce. Avoid Nested Locks : This is the main reason for dead lock. Dead Lock mainly happens when we give locks to multiple threads. Avoid giving lock to multiple threads if we already have given to one. Avoid Unnecessary Locks : We should have lock only those members which are required. Having lock on unnecessarily can lead to dead lock. Using thread join : Dead lock condition appears when one thread is waiting other to finish. If this condition occurs we can use Thread.join with maximum time you think the execution will take. Important Points : If threads are waiting for each other to finish, then the condition is known as Deadlock. Deadlock condition is a complex condition which occurs only in case of multiple threads. Deadlock condition can break our code at run time and can destroy business logic. We should avoid this condition as much as we can. This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. adityac9254 niharjain mahtuag91 Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 531, "s": 52, "text": "synchronized keyword is used to make the class or method thread-safe which means only one thread can have lock of synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock. It is important to use if our program is running in multi-threaded environment where two or more threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock. Below is a simple example of Deadlock condition. " }, { "code": null, "e": 538, "s": 533, "text": "Java" }, { "code": "// Java program to illustrate Deadlock// in multithreading.class Util{ // Util class to sleep a thread static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } }} // This class is shared by both threadsclass Shared{ // first synchronized method synchronized void test1(Shared s2) { System.out.println(\"test1-begin\"); Util.sleep(1000); // taking object lock of s2 enters // into test2 method s2.test2(); System.out.println(\"test1-end\"); } // second synchronized method synchronized void test2() { System.out.println(\"test2-begin\"); Util.sleep(1000); // taking object lock of s1 enters // into test1 method System.out.println(\"test2-end\"); }} class Thread1 extends Thread{ private Shared s1; private Shared s2; // constructor to initialize fields public Thread1(Shared s1, Shared s2) { this.s1 = s1; this.s2 = s2; } // run method to start a thread @Override public void run() { // taking object lock of s1 enters // into test1 method s1.test1(s2); }} class Thread2 extends Thread{ private Shared s1; private Shared s2; // constructor to initialize fields public Thread2(Shared s1, Shared s2) { this.s1 = s1; this.s2 = s2; } // run method to start a thread @Override public void run() { // taking object lock of s2 // enters into test2 method s2.test1(s1); }} public class Deadlock{ public static void main(String[] args) { // creating one object Shared s1 = new Shared(); // creating second object Shared s2 = new Shared(); // creating first thread and starting it Thread1 t1 = new Thread1(s1, s2); t1.start(); // creating second thread and starting it Thread2 t2 = new Thread2(s1, s2); t2.start(); // sleeping main thread Util.sleep(2000); }}", "e": 2661, "s": 538, "text": null }, { "code": null, "e": 2694, "s": 2661, "text": "Output : test1-begin\ntest2-begin" }, { "code": null, "e": 2993, "s": 2694, "text": "It is not recommended to run the above program with online IDE. We can copy the source code and run it on our local machine. We can see that it runs for indefinite time, because threads are in deadlock condition and doesn’t let code to execute. Now let’s see step by step what is happening there. " }, { "code": null, "e": 3976, "s": 2993, "text": "Thread t1 starts and calls test1 method by taking the object lock of s1.Thread t2 starts and calls test1 method by taking the object lock of s2.t1 prints test1-begin and t2 prints test-2 begin and both waits for 1 second, so that both threads can be started if any of them is not.t1 tries to take object lock of s2 and call method test2 but as it is already acquired by t2 so it waits till it become free. It will not release lock of s1 until it gets lock of s2.Same happens with t2. It tries to take object lock of s1 and call method test1 but it is already acquired by t1, so it has to wait till t1 release the lock. t2 will also not release lock of s2 until it gets lock of s1.Now, both threads are in wait state, waiting for each other to release locks. Now there is a race around condition that who will release the lock first.As none of them is ready to release lock, so this is the Dead Lock condition.When you will run this program, it will be look like execution is paused." }, { "code": null, "e": 4049, "s": 3976, "text": "Thread t1 starts and calls test1 method by taking the object lock of s1." }, { "code": null, "e": 4122, "s": 4049, "text": "Thread t2 starts and calls test1 method by taking the object lock of s2." }, { "code": null, "e": 4259, "s": 4122, "text": "t1 prints test1-begin and t2 prints test-2 begin and both waits for 1 second, so that both threads can be started if any of them is not." }, { "code": null, "e": 4442, "s": 4259, "text": "t1 tries to take object lock of s2 and call method test2 but as it is already acquired by t2 so it waits till it become free. It will not release lock of s1 until it gets lock of s2." }, { "code": null, "e": 4661, "s": 4442, "text": "Same happens with t2. It tries to take object lock of s1 and call method test1 but it is already acquired by t1, so it has to wait till t1 release the lock. t2 will also not release lock of s2 until it gets lock of s1." }, { "code": null, "e": 4814, "s": 4661, "text": "Now, both threads are in wait state, waiting for each other to release locks. Now there is a race around condition that who will release the lock first." }, { "code": null, "e": 4892, "s": 4814, "text": "As none of them is ready to release lock, so this is the Dead Lock condition." }, { "code": null, "e": 4966, "s": 4892, "text": "When you will run this program, it will be look like execution is paused." }, { "code": null, "e": 4995, "s": 4968, "text": "Detect Dead Lock condition" }, { "code": null, "e": 5276, "s": 4995, "text": "We can also detect deadlock by running this program on cmd. We have to collect Thread Dump. Command to collect depends on OS type. If we are using Windows and Java 8, command is jcmd $PID Thread.print We can get PID by running jps command. Thread dump for above program is below: " }, { "code": null, "e": 13030, "s": 5276, "text": "jcmd 18692 Thread.print\n18692:\n2020-06-08 19:03:10\nFull thread dump OpenJDK 64-Bit Server VM (11.0.4+10-b304.69 mixed mode, sharing):\n\nThreads class SMR info:\n_java_thread_list=0x0000017f44b69f20, length=13, elements={\n0x0000017f43f77000, 0x0000017f43f79800, 0x0000017f43f90000, 0x0000017f43f91000,\n0x0000017f43f95000, 0x0000017f43fa5000, 0x0000017f43fb0800, 0x0000017f43f5b800,\n0x0000017f44bc9000, 0x0000017f44afb000, 0x0000017f44bd7800, 0x0000017f44bd8800,\n0x0000017f298c9000\n}\n\n\"Reference Handler\" #2 daemon prio=10 os_prio=2 cpu=0.00ms elapsed=57.48s tid=0x0000017f43f77000 nid=0x6050 waiting on condition [0x0000005f800ff000]\n java.lang.Thread.State: RUNNABLE\n at java.lang.ref.Reference.waitForReferencePendingList(java.base@11.0.4/Native Method)\n at java.lang.ref.Reference.processPendingReferences(java.base@11.0.4/Reference.java:241)\n at java.lang.ref.Reference$ReferenceHandler.run(java.base@11.0.4/Reference.java:213)\n\n\"Finalizer\" #3 daemon prio=8 os_prio=1 cpu=0.00ms elapsed=57.48s tid=0x0000017f43f79800 nid=0x2824 in Object.wait() [0x0000005f801fe000]\n java.lang.Thread.State: WAITING (on object monitor)\n at java.lang.Object.wait(java.base@11.0.4/Native Method)\n - waiting on (a java.lang.ref.ReferenceQueue$Lock)\n at java.lang.ref.ReferenceQueue.remove(java.base@11.0.4/ReferenceQueue.java:155)\n - waiting to re-lock in wait() (a java.lang.ref.ReferenceQueue$Lock)\n at java.lang.ref.ReferenceQueue.remove(java.base@11.0.4/ReferenceQueue.java:176)\n at java.lang.ref.Finalizer$FinalizerThread.run(java.base@11.0.4/Finalizer.java:170)\n\n\"Signal Dispatcher\" #4 daemon prio=9 os_prio=2 cpu=0.00ms elapsed=57.47s tid=0x0000017f43f90000 nid=0x1710 runnable [0x0000000000000000]\n java.lang.Thread.State: RUNNABLE\n\n\"Attach Listener\" #5 daemon prio=5 os_prio=2 cpu=31.25ms elapsed=57.47s tid=0x0000017f43f91000 nid=0x4ff4 waiting on condition [0x0000000000000000]\n java.lang.Thread.State: RUNNABLE\n\n\"C2 CompilerThread0\" #6 daemon prio=9 os_prio=2 cpu=46.88ms elapsed=57.47s tid=0x0000017f43f95000 nid=0x350c waiting on condition [0x0000000000000000]\n java.lang.Thread.State: RUNNABLE\n No compile task\n\n\"C1 CompilerThread0\" #9 daemon prio=9 os_prio=2 cpu=93.75ms elapsed=57.47s tid=0x0000017f43fa5000 nid=0x4900 waiting on condition [0x0000000000000000]\n java.lang.Thread.State: RUNNABLE\n No compile task\n\n\"Sweeper thread\" #10 daemon prio=9 os_prio=2 cpu=0.00ms elapsed=57.47s tid=0x0000017f43fb0800 nid=0x6120 runnable [0x0000000000000000]\n java.lang.Thread.State: RUNNABLE\n\n\"Common-Cleaner\" #11 daemon prio=8 os_prio=1 cpu=0.00ms elapsed=57.44s tid=0x0000017f43f5b800 nid=0x5a4 in Object.wait() [0x0000005f807fe000]\n java.lang.Thread.State: TIMED_WAITING (on object monitor)\n at java.lang.Object.wait(java.base@11.0.4/Native Method)\n - waiting on (a java.lang.ref.ReferenceQueue$Lock)\n at java.lang.ref.ReferenceQueue.remove(java.base@11.0.4/ReferenceQueue.java:155)\n - waiting to re-lock in wait() (a java.lang.ref.ReferenceQueue$Lock)\n at jdk.internal.ref.CleanerImpl.run(java.base@11.0.4/CleanerImpl.java:148)\n at java.lang.Thread.run(java.base@11.0.4/Thread.java:834)\n at jdk.internal.misc.InnocuousThread.run(java.base@11.0.4/InnocuousThread.java:134)\n\n\"Monitor Ctrl-Break\" #12 daemon prio=5 os_prio=0 cpu=15.63ms elapsed=57.36s tid=0x0000017f44bc9000 nid=0x5954 runnable [0x0000005f809fe000]\n java.lang.Thread.State: RUNNABLE\n at java.net.SocketInputStream.socketRead0(java.base@11.0.4/Native Method)\n at java.net.SocketInputStream.socketRead(java.base@11.0.4/SocketInputStream.java:115)\n at java.net.SocketInputStream.read(java.base@11.0.4/SocketInputStream.java:168)\n at java.net.SocketInputStream.read(java.base@11.0.4/SocketInputStream.java:140)\n at sun.nio.cs.StreamDecoder.readBytes(java.base@11.0.4/StreamDecoder.java:284)\n at sun.nio.cs.StreamDecoder.implRead(java.base@11.0.4/StreamDecoder.java:326)\n at sun.nio.cs.StreamDecoder.read(java.base@11.0.4/StreamDecoder.java:178)\n - locked (a java.io.InputStreamReader)\n at java.io.InputStreamReader.read(java.base@11.0.4/InputStreamReader.java:185)\n at java.io.BufferedReader.fill(java.base@11.0.4/BufferedReader.java:161)\n at java.io.BufferedReader.readLine(java.base@11.0.4/BufferedReader.java:326)\n - locked (a java.io.InputStreamReader)\n at java.io.BufferedReader.readLine(java.base@11.0.4/BufferedReader.java:392)\n at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)\n\n\"Service Thread\" #13 daemon prio=9 os_prio=0 cpu=0.00ms elapsed=57.36s tid=0x0000017f44afb000 nid=0x6394 runnable [0x0000000000000000]\n java.lang.Thread.State: RUNNABLE\n\n\"Thread-0\" #14 prio=5 os_prio=0 cpu=0.00ms elapsed=57.35s tid=0x0000017f44bd7800 nid=0x5304 waiting for monitor entry [0x0000005f80cfe000]\n java.lang.Thread.State: BLOCKED (on object monitor)\n at com.company.threads.Shared.test2(Deadlock.java:40)\n - waiting to lock (a com.company.threads.Shared)\n at com.company.threads.Shared.test1(Deadlock.java:33)\n - locked (a com.company.threads.Shared)\n at com.company.threads.Thread1.run(Deadlock.java:67)\n\n\"Thread-1\" #15 prio=5 os_prio=0 cpu=0.00ms elapsed=57.35s tid=0x0000017f44bd8800 nid=0xfa4 waiting for monitor entry [0x0000005f80dfe000]\n java.lang.Thread.State: BLOCKED (on object monitor)\n at com.company.threads.Shared.test2(Deadlock.java:40)\n - waiting to lock (a com.company.threads.Shared)\n at com.company.threads.Shared.test1(Deadlock.java:33)\n - locked (a com.company.threads.Shared)\n at com.company.threads.Thread2.run(Deadlock.java:90)\n\n\"DestroyJavaVM\" #16 prio=5 os_prio=0 cpu=171.88ms elapsed=55.35s tid=0x0000017f298c9000 nid=0x38ec waiting on condition [0x0000000000000000]\n java.lang.Thread.State: RUNNABLE\n\n\"VM Thread\" os_prio=2 cpu=0.00ms elapsed=57.49s tid=0x0000017f43f73800 nid=0x52c4 runnable\n\n\"GC Thread#0\" os_prio=2 cpu=0.00ms elapsed=57.51s tid=0x0000017f298e1000 nid=0x47dc runnable\n\n\"G1 Main Marker\" os_prio=2 cpu=0.00ms elapsed=57.51s tid=0x0000017f29911000 nid=0x61c4 runnable\n\n\"G1 Conc#0\" os_prio=2 cpu=0.00ms elapsed=57.51s tid=0x0000017f29912000 nid=0x61c0 runnable\n\n\"G1 Refine#0\" os_prio=2 cpu=0.00ms elapsed=57.50s tid=0x0000017f43e0a800 nid=0x1fa8 runnable\n\n\"G1 Young RemSet Sampling\" os_prio=2 cpu=0.00ms elapsed=57.50s tid=0x0000017f43e0b000 nid=0x47a4 runnable\n\"VM Periodic Task Thread\" os_prio=2 cpu=0.00ms elapsed=57.36s tid=0x0000017f44b03800 nid=0x2408 waiting on condition\n\nJNI global refs: 15, weak refs: 0\n\n\nFound one Java-level deadlock:\n=============================\n\"Thread-0\":\n waiting to lock monitor 0x0000017f43f87980 (object 0x000000008a2e9ce0, a com.company.threads.Shared),\n which is held by \"Thread-1\"\n\"Thread-1\":\n waiting to lock monitor 0x0000017f43f87780 (object 0x000000008a2e9cd0, a com.company.threads.Shared),\n which is held by \"Thread-0\"\n\nJava stack information for the threads listed above:\n===================================================\n\"Thread-0\":\n at com.company.threads.Shared.test2(Deadlock.java:40)\n - waiting to lock (a com.company.threads.Shared)\n at com.company.threads.Shared.test1(Deadlock.java:33)\n - locked (a com.company.threads.Shared)\n at com.company.threads.Thread1.run(Deadlock.java:67)\n\"Thread-1\":\n at com.company.threads.Shared.test2(Deadlock.java:40)\n - waiting to lock (a com.company.threads.Shared)\n at com.company.threads.Shared.test1(Deadlock.java:33)\n - locked (a com.company.threads.Shared)\n at com.company.threads.Thread2.run(Deadlock.java:90)\n\nFound 1 deadlock." }, { "code": null, "e": 13170, "s": 13030, "text": "As we can see there is clearly mentioned that found 1 deadlock. It is possible that the same message appears when you try on your machine. " }, { "code": null, "e": 13196, "s": 13170, "text": "Avoid Dead Lock condition" }, { "code": null, "e": 13474, "s": 13196, "text": "We can avoid dead lock condition by knowing its possibilities. It’s a very complex process and not easy to catch. But still if we try, we can avoid this. There are some methods by which we can avoid this condition. We can’t completely remove its possibility but we can reduce. " }, { "code": null, "e": 13670, "s": 13474, "text": "Avoid Nested Locks : This is the main reason for dead lock. Dead Lock mainly happens when we give locks to multiple threads. Avoid giving lock to multiple threads if we already have given to one." }, { "code": null, "e": 13807, "s": 13670, "text": "Avoid Unnecessary Locks : We should have lock only those members which are required. Having lock on unnecessarily can lead to dead lock." }, { "code": null, "e": 14000, "s": 13807, "text": "Using thread join : Dead lock condition appears when one thread is waiting other to finish. If this condition occurs we can use Thread.join with maximum time you think the execution will take." }, { "code": null, "e": 14021, "s": 14000, "text": "Important Points : " }, { "code": null, "e": 14111, "s": 14021, "text": "If threads are waiting for each other to finish, then the condition is known as Deadlock." }, { "code": null, "e": 14200, "s": 14111, "text": "Deadlock condition is a complex condition which occurs only in case of multiple threads." }, { "code": null, "e": 14282, "s": 14200, "text": "Deadlock condition can break our code at run time and can destroy business logic." }, { "code": null, "e": 14332, "s": 14282, "text": "We should avoid this condition as much as we can." }, { "code": null, "e": 14752, "s": 14332, "text": "This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 14764, "s": 14752, "text": "adityac9254" }, { "code": null, "e": 14774, "s": 14764, "text": "niharjain" }, { "code": null, "e": 14784, "s": 14774, "text": "mahtuag91" }, { "code": null, "e": 14804, "s": 14784, "text": "Java-Multithreading" }, { "code": null, "e": 14809, "s": 14804, "text": "Java" }, { "code": null, "e": 14814, "s": 14809, "text": "Java" }, { "code": null, "e": 14912, "s": 14814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14927, "s": 14912, "text": "Arrays in Java" }, { "code": null, "e": 14971, "s": 14927, "text": "Split() String method in Java with examples" }, { "code": null, "e": 15007, "s": 14971, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 15058, "s": 15007, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 15083, "s": 15058, "text": "Reverse a string in Java" }, { "code": null, "e": 15105, "s": 15083, "text": "For-each loop in Java" }, { "code": null, "e": 15136, "s": 15105, "text": "How to iterate any Map in Java" }, { "code": null, "e": 15155, "s": 15136, "text": "Interfaces in Java" }, { "code": null, "e": 15185, "s": 15155, "text": "HashMap in Java with Examples" } ]
How to Set Java Path in Windows and Linux?
02 Feb, 2021 PATH is an environment variable that is used by Operating System to locate the exe files (.exe) or java binaries ( java or javac command). The path once it is set, cannot be overridden. The PATH variable prevents us from having to write out the entire path to a program on the Command Line Interface every time we run it. Moreover, the path is just a variable that stores a bunch of shortcuts. To execute java console-based programs in windows or Linux environments we have to use java and javac commands. The commands java, javac are not known to the operating system as we don’t specify where the executables reside. Hence, we need to specify the path where the executables are located. This is the reason we set the path and specify the path of the bin folder because the bin contains all binary executable files. After setting the path it can load all necessary items in the program including the compiler or interpreter itself. Below is the procedure for setting the path for both Windows and Linux: 1. Go to the Search box and type advanced system settings in it. Now click on the View advanced system settings. 2. Select the Advanced tab and then click environment variables. 3. In the system, variables click the New button. Now in the edit system variable, type variable name as JAVA_PATH and variable path as the path where the JDK folder is saved and click on OK button Usually the path of the JDK file will be C:\Program Files\Java\jdk1.8.0_60. 4. Now in the system variables go to the path and click the edit button. 5. Click the New button. 6. Now add the following path: %JAVA_HOME%\bin Open the terminal and enter the following command: sudo nano /etc/environment. A file will be opened and add the following command to that file: JAVA_HOME = "YOUR_PATH". Replace YOUR_PATH with the JDK bin file path. Now restart your computer or virtual machine that you are using (or) reload the file: source /etc/environment You can test the path by executing echo $JAVA_HOME If you get the output without any error, then you’ve set the path correctly. If you get any errors, try repeating the procedure again. Picked Technical Scripter 2020 How To Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Feb, 2021" }, { "code": null, "e": 446, "s": 52, "text": "PATH is an environment variable that is used by Operating System to locate the exe files (.exe) or java binaries ( java or javac command). The path once it is set, cannot be overridden. The PATH variable prevents us from having to write out the entire path to a program on the Command Line Interface every time we run it. Moreover, the path is just a variable that stores a bunch of shortcuts." }, { "code": null, "e": 986, "s": 446, "text": "To execute java console-based programs in windows or Linux environments we have to use java and javac commands. The commands java, javac are not known to the operating system as we don’t specify where the executables reside. Hence, we need to specify the path where the executables are located. This is the reason we set the path and specify the path of the bin folder because the bin contains all binary executable files. After setting the path it can load all necessary items in the program including the compiler or interpreter itself. " }, { "code": null, "e": 1058, "s": 986, "text": "Below is the procedure for setting the path for both Windows and Linux:" }, { "code": null, "e": 1171, "s": 1058, "text": "1. Go to the Search box and type advanced system settings in it. Now click on the View advanced system settings." }, { "code": null, "e": 1236, "s": 1171, "text": "2. Select the Advanced tab and then click environment variables." }, { "code": null, "e": 1510, "s": 1236, "text": "3. In the system, variables click the New button. Now in the edit system variable, type variable name as JAVA_PATH and variable path as the path where the JDK folder is saved and click on OK button Usually the path of the JDK file will be C:\\Program Files\\Java\\jdk1.8.0_60." }, { "code": null, "e": 1583, "s": 1510, "text": "4. Now in the system variables go to the path and click the edit button." }, { "code": null, "e": 1608, "s": 1583, "text": "5. Click the New button." }, { "code": null, "e": 1655, "s": 1608, "text": "6. Now add the following path: %JAVA_HOME%\\bin" }, { "code": null, "e": 1707, "s": 1655, "text": "Open the terminal and enter the following command: " }, { "code": null, "e": 1735, "s": 1707, "text": "sudo nano /etc/environment." }, { "code": null, "e": 1801, "s": 1735, "text": "A file will be opened and add the following command to that file:" }, { "code": null, "e": 1827, "s": 1801, "text": "JAVA_HOME = \"YOUR_PATH\". " }, { "code": null, "e": 1873, "s": 1827, "text": "Replace YOUR_PATH with the JDK bin file path." }, { "code": null, "e": 1983, "s": 1873, "text": "Now restart your computer or virtual machine that you are using (or) reload the file: source /etc/environment" }, { "code": null, "e": 2018, "s": 1983, "text": "You can test the path by executing" }, { "code": null, "e": 2035, "s": 2018, "text": " echo $JAVA_HOME" }, { "code": null, "e": 2112, "s": 2035, "text": "If you get the output without any error, then you’ve set the path correctly." }, { "code": null, "e": 2170, "s": 2112, "text": "If you get any errors, try repeating the procedure again." }, { "code": null, "e": 2177, "s": 2170, "text": "Picked" }, { "code": null, "e": 2201, "s": 2177, "text": "Technical Scripter 2020" }, { "code": null, "e": 2208, "s": 2201, "text": "How To" }, { "code": null, "e": 2213, "s": 2208, "text": "Java" }, { "code": null, "e": 2232, "s": 2213, "text": "Technical Scripter" }, { "code": null, "e": 2237, "s": 2232, "text": "Java" } ]
Signal Processing and Time Series (Data Analysis)
05 Mar, 2020 Signal processing is a field of engineering that focuses on analyzing analog and digital signals with respect to time. Time Series Analysis is one of the categories of signal processing. A time series is a sequence of data points recorded at regular intervals of time. Time series analysis is an important step before you develop a forecast of the series, and the order of the values is important in time series analysis. This process helps to extract meaningful statistics and other characteristics of data which helps to create an accurate forecast. Time series are widely used for data like weather, stock price, retail sales, etc... We will cover the following topics in this section: 1. Moving Average 2. Autoregressive Models 3. ARMA Models These are explained as following below. 1. Moving Average:A moving average (MA) is a widely used calculation to analyze time series. This specifies a window of data for a particular time period which is averaged each time by one period when new data is available. The two commonly used moving averages are: Simple Moving Average (SMA) –SMA’s calculation provides the average data for a defined number of time periods. The mathematical formula as follows:Where, = parameter of the modeln = total no of daysExponential Moving Average (EMA) –Exponential moving average gives more priority to recent data. The mathematical formula as follows:Where, = current closing price = previous periods EMA [SMA for first calculation]k = 2 / (N+1) [exponential or smoothing constant]N = Total no of days considered for EMA calculation Simple Moving Average (SMA) –SMA’s calculation provides the average data for a defined number of time periods. The mathematical formula as follows:Where, = parameter of the modeln = total no of days Where, = parameter of the modeln = total no of days Exponential Moving Average (EMA) –Exponential moving average gives more priority to recent data. The mathematical formula as follows:Where, = current closing price = previous periods EMA [SMA for first calculation]k = 2 / (N+1) [exponential or smoothing constant]N = Total no of days considered for EMA calculation Where, = current closing price = previous periods EMA [SMA for first calculation]k = 2 / (N+1) [exponential or smoothing constant]N = Total no of days considered for EMA calculation EMA Calculation:Here we calculate EMA for 5 days. Normally for the first case either we take the current close price or previous 5 days SMA value to get the first EMA. For the below example, the current close price ($22.81) is taken as the first EMA value. The next step is to calculate the k value. Since the calculation is based on 5 days, N = 5 and k value is calculated as follows: k = 2/(5+1) = 0.3 EMA for 2nd day is calculated as follows: Current closing price = 23.09 Previous period EMA = 22.81 k = 0.3 EMA = 22.81 + 0.3 * (23.09 - 22.81) = 22.81 + 0.3 * 0.28 = 22.81 + 0.084 = 22.894 EMA for 3rd day is calculated as follows: Current closing price = 22.91 Previous period EMA = 22.89 k = 0.3 EMA = 22.89 + 0.3 * (22.91 - 22.89) = 22.89 + 0.3 * .02 = 22.89 + .006 = 22.896 SMA Calculation:Since we considered total days (N) as 5, the SMA is calculated as the average of 5 latest close price. SMA for 5 days is calculated as follows: SMA = (22.81 + 23.09 + 22.91 + 23.23 + 22.83) / 5 = 114.87 / 5 = 22.97 2. Autoregressive Models:An autoregressive model can be used to predict future data based on past data. In this model, data is assumed to depend on its previous data. Since autoregressive models totally depend on past data to generate future models, there are chances of generating inaccurate data under certain conditions such as financial crises or sudden technological changes.The mathematical formula as follows: AR Calculation:The below data provide the stock price of today(t), one day before (t-1), two days before (t-2) and three days before (t-3). With the above stock price data, you need to perform the linear regression to get the parameters required for AR model. For this, you can use data analysis feature from excel. For regression, you can provide t data as Y input and (t-1), (t-2), (t-3) as X input. Microsoft excel will provide you the below result. Regression Statistics: Multiple R: 0.786903932 R Square: 0.619217798 Adjusted R Square: 0.537621612 Standard Error: 0.398415364 Observations: 18 Let’s look into how to use the output values from regression. Previous Stock Data: Coefficient of t-1 = 0.840795074 and Close price = 22.8 Coefficient of t-2 = 0.100511124 and Close price = 23.12 Coefficient of t-3 = -0.308260596 and Close price = 23.25 Value of Constant: Coefficient of Intercept = 8.59250239 = 8.6 Standard Error: t-1 = 0.249566271 t-2 = 0.331626753 t-3 = -0.250400704 Standard Error = 0.25 + 0.33 - 0.25 = 0.33 AR = 8.6 + [ (0.84*22.8) + (0.1*23.12) + (-0.31*23.25) ] + 0.33 = 8.6 + [ 19.15 + 2.31 - 7.20] + 0.33 = 8.6 + 14.26 + 0.33 = 23.19 Rather than going through the entire calculation, you can predict tomorrow stock price with today stock price and R square value (refer regression statistics output above). Suppose that, the stock price of today is $22.84, then tomorrow’s stock price is calculated as: AR(t+1) = Coefficient of Intercept + (R square * Today's Price) + Standard Error R Square = 0.619217798 Standard Error (from regression statistics) = 0.398415364 AR = 8.6 + (0.619*22.84) + 0.39 = 8.6 + 14.14 + 0.39 = 23.13 3. ARMA Models:ARMA model is another tool used to forecast a time series. These models are based on the combination of both autoregressive and moving average models. In the AR model, we use past data for regressing the variable and in the MA model, we use the sum of the mean of the time series for a forecast. Since the ARMA model is the combination of both AR part and MA part, this model is referred to as ARMA(p, q) model where p is the AR part and q is the MA part. The mathematical formula is as follows: Where, = the autoregressive model’s parameter = the moving average model’s parameterc = a constant = error term’s [White Noise] Digital Electronics & Logic Design Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shift Registers in Digital Logic Flip-flop types, their Conversion and Applications IEEE Standard 754 Floating Point Numbers Counters in Digital Logic Encoder in Digital Logic Overview of Data Structures | Set 1 (Linear Data Structures) vector::push_back() and vector::pop_back() in C++ STL Virtualization In Cloud Computing and Types Program for nth Catalan Number How to write Regular Expressions?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Mar, 2020" }, { "code": null, "e": 215, "s": 28, "text": "Signal processing is a field of engineering that focuses on analyzing analog and digital signals with respect to time. Time Series Analysis is one of the categories of signal processing." }, { "code": null, "e": 665, "s": 215, "text": "A time series is a sequence of data points recorded at regular intervals of time. Time series analysis is an important step before you develop a forecast of the series, and the order of the values is important in time series analysis. This process helps to extract meaningful statistics and other characteristics of data which helps to create an accurate forecast. Time series are widely used for data like weather, stock price, retail sales, etc..." }, { "code": null, "e": 717, "s": 665, "text": "We will cover the following topics in this section:" }, { "code": null, "e": 776, "s": 717, "text": "1. Moving Average\n2. Autoregressive Models\n3. ARMA Models " }, { "code": null, "e": 816, "s": 776, "text": "These are explained as following below." }, { "code": null, "e": 1040, "s": 816, "text": "1. Moving Average:A moving average (MA) is a widely used calculation to analyze time series. This specifies a window of data for a particular time period which is averaged each time by one period when new data is available." }, { "code": null, "e": 1083, "s": 1040, "text": "The two commonly used moving averages are:" }, { "code": null, "e": 1596, "s": 1083, "text": "Simple Moving Average (SMA) –SMA’s calculation provides the average data for a defined number of time periods. The mathematical formula as follows:Where, = parameter of the modeln = total no of daysExponential Moving Average (EMA) –Exponential moving average gives more priority to recent data. The mathematical formula as follows:Where, = current closing price = previous periods EMA [SMA for first calculation]k = 2 / (N+1) [exponential or smoothing constant]N = Total no of days considered for EMA calculation" }, { "code": null, "e": 1795, "s": 1596, "text": "Simple Moving Average (SMA) –SMA’s calculation provides the average data for a defined number of time periods. The mathematical formula as follows:Where, = parameter of the modeln = total no of days" }, { "code": null, "e": 1847, "s": 1795, "text": "Where, = parameter of the modeln = total no of days" }, { "code": null, "e": 2162, "s": 1847, "text": "Exponential Moving Average (EMA) –Exponential moving average gives more priority to recent data. The mathematical formula as follows:Where, = current closing price = previous periods EMA [SMA for first calculation]k = 2 / (N+1) [exponential or smoothing constant]N = Total no of days considered for EMA calculation" }, { "code": null, "e": 2344, "s": 2162, "text": "Where, = current closing price = previous periods EMA [SMA for first calculation]k = 2 / (N+1) [exponential or smoothing constant]N = Total no of days considered for EMA calculation" }, { "code": null, "e": 2601, "s": 2344, "text": "EMA Calculation:Here we calculate EMA for 5 days. Normally for the first case either we take the current close price or previous 5 days SMA value to get the first EMA. For the below example, the current close price ($22.81) is taken as the first EMA value." }, { "code": null, "e": 2730, "s": 2601, "text": "The next step is to calculate the k value. Since the calculation is based on 5 days, N = 5 and k value is calculated as follows:" }, { "code": null, "e": 2750, "s": 2730, "text": " k = 2/(5+1) = 0.3 " }, { "code": null, "e": 2792, "s": 2750, "text": "EMA for 2nd day is calculated as follows:" }, { "code": null, "e": 2859, "s": 2792, "text": "Current closing price = 23.09\nPrevious period EMA = 22.81\nk = 0.3 " }, { "code": null, "e": 2943, "s": 2859, "text": "EMA \n= 22.81 + 0.3 * (23.09 - 22.81)\n= 22.81 + 0.3 * 0.28\n= 22.81 + 0.084\n= 22.894 " }, { "code": null, "e": 2985, "s": 2943, "text": "EMA for 3rd day is calculated as follows:" }, { "code": null, "e": 3052, "s": 2985, "text": "Current closing price = 22.91\nPrevious period EMA = 22.89\nk = 0.3 " }, { "code": null, "e": 3134, "s": 3052, "text": "EMA \n= 22.89 + 0.3 * (22.91 - 22.89)\n= 22.89 + 0.3 * .02\n= 22.89 + .006\n= 22.896 " }, { "code": null, "e": 3253, "s": 3134, "text": "SMA Calculation:Since we considered total days (N) as 5, the SMA is calculated as the average of 5 latest close price." }, { "code": null, "e": 3294, "s": 3253, "text": "SMA for 5 days is calculated as follows:" }, { "code": null, "e": 3369, "s": 3294, "text": "SMA \n= (22.81 + 23.09 + 22.91 + 23.23 + 22.83) / 5\n= 114.87 / 5 \n= 22.97 " }, { "code": null, "e": 3786, "s": 3369, "text": "2. Autoregressive Models:An autoregressive model can be used to predict future data based on past data. In this model, data is assumed to depend on its previous data. Since autoregressive models totally depend on past data to generate future models, there are chances of generating inaccurate data under certain conditions such as financial crises or sudden technological changes.The mathematical formula as follows:" }, { "code": null, "e": 3926, "s": 3786, "text": "AR Calculation:The below data provide the stock price of today(t), one day before (t-1), two days before (t-2) and three days before (t-3)." }, { "code": null, "e": 4239, "s": 3926, "text": "With the above stock price data, you need to perform the linear regression to get the parameters required for AR model. For this, you can use data analysis feature from excel. For regression, you can provide t data as Y input and (t-1), (t-2), (t-3) as X input. Microsoft excel will provide you the below result." }, { "code": null, "e": 4262, "s": 4239, "text": "Regression Statistics:" }, { "code": null, "e": 4385, "s": 4262, "text": "Multiple R: 0.786903932\nR Square: 0.619217798\nAdjusted R Square: 0.537621612\nStandard Error: 0.398415364\nObservations: 18 " }, { "code": null, "e": 4447, "s": 4385, "text": "Let’s look into how to use the output values from regression." }, { "code": null, "e": 4468, "s": 4447, "text": "Previous Stock Data:" }, { "code": null, "e": 4640, "s": 4468, "text": "Coefficient of t-1 = 0.840795074 and Close price = 22.8\nCoefficient of t-2 = 0.100511124 and Close price = 23.12\nCoefficient of t-3 = -0.308260596 and Close price = 23.25 " }, { "code": null, "e": 4659, "s": 4640, "text": "Value of Constant:" }, { "code": null, "e": 4704, "s": 4659, "text": "Coefficient of Intercept = 8.59250239 = 8.6 " }, { "code": null, "e": 4720, "s": 4704, "text": "Standard Error:" }, { "code": null, "e": 4776, "s": 4720, "text": "t-1 = 0.249566271\nt-2 = 0.331626753\nt-3 = -0.250400704 " }, { "code": null, "e": 4821, "s": 4776, "text": "Standard Error \n= 0.25 + 0.33 - 0.25\n= 0.33 " }, { "code": null, "e": 4954, "s": 4821, "text": "AR \n= 8.6 + [ (0.84*22.8) + (0.1*23.12) + (-0.31*23.25) ] + 0.33\n= 8.6 + [ 19.15 + 2.31 - 7.20] + 0.33\n= 8.6 + 14.26 + 0.33\n= 23.19 " }, { "code": null, "e": 5127, "s": 4954, "text": "Rather than going through the entire calculation, you can predict tomorrow stock price with today stock price and R square value (refer regression statistics output above)." }, { "code": null, "e": 5223, "s": 5127, "text": "Suppose that, the stock price of today is $22.84, then tomorrow’s stock price is calculated as:" }, { "code": null, "e": 5430, "s": 5223, "text": "AR(t+1) = Coefficient of Intercept + (R square * Today's Price) \n + Standard Error\n\nR Square = 0.619217798 \n\nStandard Error (from regression statistics) = 0.398415364 " }, { "code": null, "e": 5493, "s": 5430, "text": "AR \n= 8.6 + (0.619*22.84) + 0.39\n= 8.6 + 14.14 + 0.39\n= 23.13 " }, { "code": null, "e": 5804, "s": 5493, "text": "3. ARMA Models:ARMA model is another tool used to forecast a time series. These models are based on the combination of both autoregressive and moving average models. In the AR model, we use past data for regressing the variable and in the MA model, we use the sum of the mean of the time series for a forecast." }, { "code": null, "e": 5964, "s": 5804, "text": "Since the ARMA model is the combination of both AR part and MA part, this model is referred to as ARMA(p, q) model where p is the AR part and q is the MA part." }, { "code": null, "e": 6004, "s": 5964, "text": "The mathematical formula is as follows:" }, { "code": null, "e": 6132, "s": 6004, "text": "Where, = the autoregressive model’s parameter = the moving average model’s parameterc = a constant = error term’s [White Noise]" }, { "code": null, "e": 6167, "s": 6132, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 6172, "s": 6167, "text": "Misc" }, { "code": null, "e": 6177, "s": 6172, "text": "Misc" }, { "code": null, "e": 6182, "s": 6177, "text": "Misc" }, { "code": null, "e": 6280, "s": 6182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6313, "s": 6280, "text": "Shift Registers in Digital Logic" }, { "code": null, "e": 6364, "s": 6313, "text": "Flip-flop types, their Conversion and Applications" }, { "code": null, "e": 6405, "s": 6364, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 6431, "s": 6405, "text": "Counters in Digital Logic" }, { "code": null, "e": 6456, "s": 6431, "text": "Encoder in Digital Logic" }, { "code": null, "e": 6517, "s": 6456, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 6571, "s": 6517, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 6615, "s": 6571, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 6646, "s": 6615, "text": "Program for nth Catalan Number" } ]
Decision Trees — Pruning. My last blog focused on the concept of... | by Blake Lawrence | Towards Data Science
My last blog focused on the concept of decision trees which form the basis of the Random Forest machine learning algorithm. As it was only a short blog (4 minute read), I didn’t delve into the detail however did embed some (hopefully) useful links. In this post I would like to go a little further and cover: How random forest uses decision trees The problem of over-fitting and how you can potentially identify it Pruning decision trees to limit over-fitting issues. As you will see, machine learning in R can be incredibly simple, often only requiring a few lines of code to get a model running. Although useful, the default settings used by the algorithms are rarely ideal. The following code is an example to prepare a classification tree model. I have used the ‘rpart’ package however ‘caret’ is another alternative. Model = rpart(classifier ~ predictor, data = train_data, method = “class”, control = rpart.control(###)) The ‘classifier’ is the feature to be predicted by the model, and the ‘predictors’ are the independent features within the dataset which will be used to determine probabilities for the classifier outcome. The method = “class” statement will ensure a prediction is made for the classifier (for a factor type variable). For example, preparing scripts relating to a loan repayment data-set. The classifier was whether an applicant had ‘repaid’ or ‘defaulted’ on a debt with a number of features (columns) available to predict this outcome. The random forest algorithm uses a number of decision trees prepared using random segments of the training data. Each of the observations in the test data set is then run through each of the trees to independently make predictions as to the outcome of the classifier. The classification predicted by the largest number of trees represents the prediction of the model. If most of the trees predict a loan will be repaid, than this is the prediction of the model. Test_data$Prediction <- predict(Model, data = test_Data, type = “class”) Once a prediction vector was created, the overall accuracy of the models could be calculated and a confusion matrix produced showing which of the two outcomes (repaid and default) the model was best at predicting. Accuracy = mean(test_data$Predicted == test_data$actual_outcome) Confusion Matrix = table(test_data$Predicted,test_Data$actual_outcome) In one of the activities I completed in Data Camp, I went a little further than the exercise required to test the accuracy of both the standard decision tree as well as a version where I had pruned the tree. The reason for pruning is that the trees prepared by the base algorithm can be prone to overfitting as they become incredibly large and complex. Below I have shown the decision tree produced using the base algorithm with no tuning parameters. Don’t worry that the font is too small to read, I am simply highlighting just how complex the tree can be with no control parameters added. When I pruned the tree I tested different values for minsplit (number of observations to appear in a leaf before it is ‘pruned’) and maxdepth (maximum number of nodes in a branch). This terminology is all covered in my earlier blog if you would appreciate a quick refresh! I found that a tree of significantly reduced complexity actually provided a small increase in accuracy — I was aiming to keep accuracy stable! The original model produced similar levels of accuracy across both default and repaid home loans whereas the new model has improved significantly at predicting default loans with a smaller deterioration in accuracy on its repaid loan predictions. This would be worth exploring more however the drastic reduction in complexity has still yielded excellent results. This is the code I prepared for both the standard and pruned trees. Only a small amount of code with lots of room for further improvement! # Trees prepared with no pruning# prepare modellm <- rpart(outcome ~ ., data = loans_train, method = “class”, control = rpart.control(cp = 0))# prepare predictionloans_test$PredLM <- predict(lm,loans_test, type = “class”)# calculate overall accuracymean(loans_test$PredLM == loans_test$outcome)# prepare confusion matrixtable(loans_test$PredLM,loans_test$outcome)# plot treerpart.plot(lm, type = 3, box.palette = c(“red”, “green”), fallen.leaves = TRUE)# Trees prepared with pruning# prepare modellmp <- rpart(outcome ~ ., data = loans_train, method = “class”, control = rpart.control(cp = 0, minsplit = 250, maxdepth = 6))# prepare predictionloans_test$PredLMP <- predict(lmp,loans_test, type = “class”)# calculate overall accuracymean(loans_test$PredLMP == loans_test$outcome)# prepare confusion matrixtable(loans_test$PredLMP,loans_test$outcome)# plot treerpart.plot(lmp, type = 3,cex = .7, box.palette = c(“red”, “green”), fallen.leaves = TRUE)
[ { "code": null, "e": 421, "s": 172, "text": "My last blog focused on the concept of decision trees which form the basis of the Random Forest machine learning algorithm. As it was only a short blog (4 minute read), I didn’t delve into the detail however did embed some (hopefully) useful links." }, { "code": null, "e": 481, "s": 421, "text": "In this post I would like to go a little further and cover:" }, { "code": null, "e": 519, "s": 481, "text": "How random forest uses decision trees" }, { "code": null, "e": 587, "s": 519, "text": "The problem of over-fitting and how you can potentially identify it" }, { "code": null, "e": 640, "s": 587, "text": "Pruning decision trees to limit over-fitting issues." }, { "code": null, "e": 849, "s": 640, "text": "As you will see, machine learning in R can be incredibly simple, often only requiring a few lines of code to get a model running. Although useful, the default settings used by the algorithms are rarely ideal." }, { "code": null, "e": 994, "s": 849, "text": "The following code is an example to prepare a classification tree model. I have used the ‘rpart’ package however ‘caret’ is another alternative." }, { "code": null, "e": 1099, "s": 994, "text": "Model = rpart(classifier ~ predictor, data = train_data, method = “class”, control = rpart.control(###))" }, { "code": null, "e": 1304, "s": 1099, "text": "The ‘classifier’ is the feature to be predicted by the model, and the ‘predictors’ are the independent features within the dataset which will be used to determine probabilities for the classifier outcome." }, { "code": null, "e": 2098, "s": 1304, "text": "The method = “class” statement will ensure a prediction is made for the classifier (for a factor type variable). For example, preparing scripts relating to a loan repayment data-set. The classifier was whether an applicant had ‘repaid’ or ‘defaulted’ on a debt with a number of features (columns) available to predict this outcome. The random forest algorithm uses a number of decision trees prepared using random segments of the training data. Each of the observations in the test data set is then run through each of the trees to independently make predictions as to the outcome of the classifier. The classification predicted by the largest number of trees represents the prediction of the model. If most of the trees predict a loan will be repaid, than this is the prediction of the model." }, { "code": null, "e": 2171, "s": 2098, "text": "Test_data$Prediction <- predict(Model, data = test_Data, type = “class”)" }, { "code": null, "e": 2385, "s": 2171, "text": "Once a prediction vector was created, the overall accuracy of the models could be calculated and a confusion matrix produced showing which of the two outcomes (repaid and default) the model was best at predicting." }, { "code": null, "e": 2450, "s": 2385, "text": "Accuracy = mean(test_data$Predicted == test_data$actual_outcome)" }, { "code": null, "e": 2521, "s": 2450, "text": "Confusion Matrix = table(test_data$Predicted,test_Data$actual_outcome)" }, { "code": null, "e": 3112, "s": 2521, "text": "In one of the activities I completed in Data Camp, I went a little further than the exercise required to test the accuracy of both the standard decision tree as well as a version where I had pruned the tree. The reason for pruning is that the trees prepared by the base algorithm can be prone to overfitting as they become incredibly large and complex. Below I have shown the decision tree produced using the base algorithm with no tuning parameters. Don’t worry that the font is too small to read, I am simply highlighting just how complex the tree can be with no control parameters added." }, { "code": null, "e": 3385, "s": 3112, "text": "When I pruned the tree I tested different values for minsplit (number of observations to appear in a leaf before it is ‘pruned’) and maxdepth (maximum number of nodes in a branch). This terminology is all covered in my earlier blog if you would appreciate a quick refresh!" }, { "code": null, "e": 3891, "s": 3385, "text": "I found that a tree of significantly reduced complexity actually provided a small increase in accuracy — I was aiming to keep accuracy stable! The original model produced similar levels of accuracy across both default and repaid home loans whereas the new model has improved significantly at predicting default loans with a smaller deterioration in accuracy on its repaid loan predictions. This would be worth exploring more however the drastic reduction in complexity has still yielded excellent results." }, { "code": null, "e": 4030, "s": 3891, "text": "This is the code I prepared for both the standard and pruned trees. Only a small amount of code with lots of room for further improvement!" } ]
Clustering Coefficient in Graph Theory - GeeksforGeeks
08 Feb, 2018 In graph theory, a clustering coefficient is a measure of the degree to which nodes in a graph tend to cluster together. Evidence suggests that in most real-world networks, and in particular social networks, nodes tend to create tightly knit groups characterized by a relatively high density of ties; this likelihood tends to be greater than the average probability of a tie randomly established between two nodes (Holland and Leinhardt, 1971; Watts and Strogatz, 1998). Two versions of this measure exist: the global and the local. The global version was designed to give an overall indication of the clustering in the network, whereas the local gives an indication of the embeddedness of single nodes. Global clustering coefficient The global clustering coefficient is based on triplets of nodes. A triplet consists of three connected nodes. A triangle therefore includes three closed triplets, one centered on each of the nodes (n.b. this means the three triplets in a triangle come from overlapping selections of nodes). The global clustering coefficient is the number of closed triplets (or 3 x triangles) over the total number of triplets (both open and closed). The first attempt to measure it was made by Luce and Perry (1949). This measure gives an indication of the clustering in the whole network (global), and can be applied to both undirected and directed networks. Local clustering coefficient A graph formally consists of a set of vertices V and a set of edges E between them. An edge connects vertex with vertex . The neighborhood for a vertex is defined as its immediately connected neighbors as follows: . We define as the number of vertices, , in the neighbourhood, , of a vertex. The local clustering coefficient for a vertex is then given by the proportion of links between the vertices within its neighborhood divided by the number of links that could possibly exist between them. For a directed graph, is distinct from , and therefore for each neighborhood there are links that could exist among the vertices within the neighborhood ( is the number of neighbors of a vertex). Thus, the local clustering coefficient for directed graphs is given as [2] .An undirected graph has the property that and are considered identical. Therefore, if a vertex has neighbors, edges could exist among the vertices within the neighborhood. Thus, the local clustering coefficient for undirected graphs can be defined as .Let be the number of triangles on for undirected graph G. That is, is the number of sub-graphs of G with 3 edges and 3 vertices, one of which is v. Let be the number of triples on . That is, is the number of sub-graphs (not necessarily induced) with 2 edges and 3 vertices, one of which is v and such that v is incident to both edges. Then we can also define the clustering coefficient aslue .It is simple to show that the two preceding definitions are the same, since .These measures are 1 if every neighbor connected to is also connected to every other vertex within the neighborhood, and 0 if no vertex that is connected to connects to any other vertex that is connected to . Example local clustering coefficient on an undirected graph. The local clustering coefficient of the green node is computed as the proportion of connections among its neighbours. Here is the code to implement the above clustering coefficient in a graph. It is a part of the networkx library and can be directly accessed using it. def average_clustering(G, trials=1000): """Estimates the average clustering coefficient of G. The local clustering of each node in `G` is the fraction of triangles that actually exist over all possible triangles in its neighborhood. The average clustering coefficient of a graph `G` is the mean of local clusterings. This function finds an approximate average clustering coefficient for G by repeating `n` times (defined in `trials`) the following experiment: choose a node at random, choose two of its neighbors at random, and check if they are connected. The approximate coefficient is the fraction of triangles found over the number of trials [1]_. Parameters ---------- G : NetworkX graph trials : integer Number of trials to perform (default 1000). Returns ------- c : float Approximated average clustering coefficient. """ n = len(G) triangles = 0 nodes = G.nodes() for i in [int(random.random() * n) for i in range(trials)]: nbrs = list(G[nodes[i]]) if len(nbrs) < 2: continue u, v = random.sample(nbrs, 2) if u in G[v]: triangles += 1 return triangles / float(trials) Note: The above code is valid for undirected networks and not for the directed networks.The code below has been run on IDLE(Python IDE of windows). You would need to download the networkx library before you run this code. The part inside the curly braces represent the output. It is almost similar as Ipython(for Ububtu users). >>> import networkx as nx>>> G=nx.erdos_renyi_graph(10,0.4)>>> cc=nx.average_clustering(G)>>> cc#Output of Global CC0.08333333333333333 >>> c=nx.clustering(G)>>> c # Output of local CC{0: 0.0, 1: 0.3333333333333333, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0, 6: 0.0, 7: 0.3333333333333333, 8: 0.0, 9: 0.16666666666666666} The above two values give us the global clustering coefficient of a network as well as local clustering coefficient of a network. Next into this series, we will talk about another centrality measure for any given network. ReferencesYou can read more about the same at https://en.wikipedia.org/wiki/Clustering_coefficient http://networkx.readthedocs.io/en/networkx-1.10/index.html.This article is contributed by Jayant Bisht. 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.My Personal Notes arrow_drop_upSave . This article is contributed by Jayant Bisht. 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. Graph Mathematical Mathematical Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Detect cycle in an undirected graph Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24646, "s": 24618, "text": "\n08 Feb, 2018" }, { "code": null, "e": 25117, "s": 24646, "text": "In graph theory, a clustering coefficient is a measure of the degree to which nodes in a graph tend to cluster together. Evidence suggests that in most real-world networks, and in particular social networks, nodes tend to create tightly knit groups characterized by a relatively high density of ties; this likelihood tends to be greater than the average probability of a tie randomly established between two nodes (Holland and Leinhardt, 1971; Watts and Strogatz, 1998)." }, { "code": null, "e": 25350, "s": 25117, "text": "Two versions of this measure exist: the global and the local. The global version was designed to give an overall indication of the clustering in the network, whereas the local gives an indication of the embeddedness of single nodes." }, { "code": null, "e": 25380, "s": 25350, "text": "Global clustering coefficient" }, { "code": null, "e": 26025, "s": 25380, "text": "The global clustering coefficient is based on triplets of nodes. A triplet consists of three connected nodes. A triangle therefore includes three closed triplets, one centered on each of the nodes (n.b. this means the three triplets in a triangle come from overlapping selections of nodes). The global clustering coefficient is the number of closed triplets (or 3 x triangles) over the total number of triplets (both open and closed). The first attempt to measure it was made by Luce and Perry (1949). This measure gives an indication of the clustering in the whole network (global), and can be applied to both undirected and directed networks." }, { "code": null, "e": 26054, "s": 26025, "text": "Local clustering coefficient" }, { "code": null, "e": 26179, "s": 26054, "text": "A graph formally consists of a set of vertices V and a set of edges E between them. An edge connects vertex with vertex ." }, { "code": null, "e": 26273, "s": 26179, "text": "The neighborhood for a vertex is defined as its immediately connected neighbors as follows:" }, { "code": null, "e": 26275, "s": 26273, "text": "." }, { "code": null, "e": 26352, "s": 26275, "text": "We define as the number of vertices, , in the neighbourhood, , of a vertex." }, { "code": null, "e": 26831, "s": 26352, "text": "The local clustering coefficient for a vertex is then given by the proportion of links between the vertices within its neighborhood divided by the number of links that could possibly exist between them. For a directed graph, is distinct from , and therefore for each neighborhood there are links that could exist among the vertices within the neighborhood ( is the number of neighbors of a vertex). Thus, the local clustering coefficient for directed graphs is given as [2]" }, { "code": null, "e": 27088, "s": 26831, "text": ".An undirected graph has the property that and are considered identical. Therefore, if a vertex has neighbors, edges could exist among the vertices within the neighborhood. Thus, the local clustering coefficient for undirected graphs can be defined as" }, { "code": null, "e": 27564, "s": 27088, "text": ".Let be the number of triangles on for undirected graph G. That is, is the number of sub-graphs of G with 3 edges and 3 vertices, one of which is v. Let be the number of triples on . That is, is the number of sub-graphs (not necessarily induced) with 2 edges and 3 vertices, one of which is v and such that v is incident to both edges. Then we can also define the clustering coefficient aslue .It is simple to show that the two preceding definitions are the same, since" }, { "code": null, "e": 27777, "s": 27564, "text": " .These measures are 1 if every neighbor connected to is also connected to every other vertex within the neighborhood, and 0 if no vertex that is connected to connects to any other vertex that is connected to ." }, { "code": null, "e": 27956, "s": 27777, "text": "Example local clustering coefficient on an undirected graph. The local clustering coefficient of the green node is computed as the proportion of connections among its neighbours." }, { "code": null, "e": 28107, "s": 27956, "text": "Here is the code to implement the above clustering coefficient in a graph. It is a part of the networkx library and can be directly accessed using it." }, { "code": "def average_clustering(G, trials=1000): \"\"\"Estimates the average clustering coefficient of G. The local clustering of each node in `G` is the fraction of triangles that actually exist over all possible triangles in its neighborhood. The average clustering coefficient of a graph `G` is the mean of local clusterings. This function finds an approximate average clustering coefficient for G by repeating `n` times (defined in `trials`) the following experiment: choose a node at random, choose two of its neighbors at random, and check if they are connected. The approximate coefficient is the fraction of triangles found over the number of trials [1]_. Parameters ---------- G : NetworkX graph trials : integer Number of trials to perform (default 1000). Returns ------- c : float Approximated average clustering coefficient. \"\"\" n = len(G) triangles = 0 nodes = G.nodes() for i in [int(random.random() * n) for i in range(trials)]: nbrs = list(G[nodes[i]]) if len(nbrs) < 2: continue u, v = random.sample(nbrs, 2) if u in G[v]: triangles += 1 return triangles / float(trials)", "e": 29355, "s": 28107, "text": null }, { "code": null, "e": 29683, "s": 29355, "text": "Note: The above code is valid for undirected networks and not for the directed networks.The code below has been run on IDLE(Python IDE of windows). You would need to download the networkx library before you run this code. The part inside the curly braces represent the output. It is almost similar as Ipython(for Ububtu users)." }, { "code": ">>> import networkx as nx>>> G=nx.erdos_renyi_graph(10,0.4)>>> cc=nx.average_clustering(G)>>> cc#Output of Global CC0.08333333333333333 >>> c=nx.clustering(G)>>> c # Output of local CC{0: 0.0, 1: 0.3333333333333333, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0, 6: 0.0, 7: 0.3333333333333333, 8: 0.0, 9: 0.16666666666666666} ", "e": 29995, "s": 29683, "text": null }, { "code": null, "e": 30125, "s": 29995, "text": "The above two values give us the global clustering coefficient of a network as well as local clustering coefficient of a network." }, { "code": null, "e": 30217, "s": 30125, "text": "Next into this series, we will talk about another centrality measure for any given network." }, { "code": null, "e": 30263, "s": 30217, "text": "ReferencesYou can read more about the same at" }, { "code": null, "e": 30316, "s": 30263, "text": "https://en.wikipedia.org/wiki/Clustering_coefficient" }, { "code": null, "e": 30834, "s": 30316, "text": "http://networkx.readthedocs.io/en/networkx-1.10/index.html.This article is contributed by Jayant Bisht. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30836, "s": 30834, "text": "." }, { "code": null, "e": 31136, "s": 30836, "text": "This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31261, "s": 31136, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31267, "s": 31261, "text": "Graph" }, { "code": null, "e": 31280, "s": 31267, "text": "Mathematical" }, { "code": null, "e": 31293, "s": 31280, "text": "Mathematical" }, { "code": null, "e": 31299, "s": 31293, "text": "Graph" }, { "code": null, "e": 31397, "s": 31299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31406, "s": 31397, "text": "Comments" }, { "code": null, "e": 31419, "s": 31406, "text": "Old Comments" }, { "code": null, "e": 31439, "s": 31419, "text": "Topological Sorting" }, { "code": null, "e": 31472, "s": 31439, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 31540, "s": 31472, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 31615, "s": 31540, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 31651, "s": 31615, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 31681, "s": 31651, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31741, "s": 31681, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31756, "s": 31741, "text": "C++ Data Types" }, { "code": null, "e": 31799, "s": 31756, "text": "Set in C++ Standard Template Library (STL)" } ]
How to Access any Component Outside RecyclerView from RecyclerView in Android? - GeeksforGeeks
09 Dec, 2020 The title may be a little confusing but what we want to say is, suppose in an Android App, there’s a RecyclerView, and outside that there’s a TextView. In the RecyclerView there’s a list of clickable components, said Button. Now what I want is, for different button clicks, the text in the TextView will be different. So this is basically controlling a component outside RecyclerView, from a RecyclerView. As per the picture, there’s a RecyclerView with four Buttons (1 hidden at the left) and a TextView. For different Button clicks different texts are showing up in the TextView. In this article, the same concept will be implemented with a little real-world touch. So the final app will show a list and a sub-list of the Tutorials offered by GEEKS FOR GEEKS. Here’s a demo GIF of the final app: Prerequisites: How to install Android Studio Setting up a new project in Android Studio What is RecyclerView Step 1: Working with the activity_main.xml file Go to the res -> layout -> activity_main.xml file. Here is the code of that XML file: XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="10dp" android:orientation="vertical" android:padding="10dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"> <TextView style="@style/MaterialAlertDialog.MaterialComponents.Title.Icon" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="GEEKS FOR GEEKS TUTORIALS" android:textAlignment="center" android:textSize="25sp" android:textStyle="bold" /> </LinearLayout> <!-- The horizontal recyclerView where the Main-List items will be showed --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerViewOne" android:layout_width="match_parent" android:layout_height="150dp" android:layout_marginTop="20dp" android:clipToPadding="false" android:foregroundGravity="center" android:orientation="horizontal" /> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="20dp" android:gravity="center"> <!-- The TextView where the Main-List item title text will be showed --> <TextView android:id="@+id/algorithmTitleText" style="@style/ShapeAppearance.MaterialComponents.MediumComponent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/black" android:textSize="22sp" /> </LinearLayout> <!-- The vertical recyclerView where the Sub-List items will be showed --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerViewTwo" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="20dp" android:clipToPadding="false" android:foregroundGravity="center" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> Here, two RecyclerView is used, one horizontal (recyclerViewOne) and one vertical (recyclerViewTwo). The first one shows the main list and the second one shows the sub-list of the main list item. A TextView is also used to show the main list-item text. Step 2: Add single_card_layout.xml for the main list items Go to the res -> layout Right Click on the layout folder Go to New -> Layout Resource File Type the file name (single_card_layout.xml for me) Change the root element to RelativeLayout Click OK Here is the code of this XML file: XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"> <androidx.cardview.widget.CardView android:id="@+id/singleItemCardView" android:layout_width="145dp" android:layout_height="match_parent" android:layout_margin="10dp" android:elevation="10dp" app:cardCornerRadius="30dp" android:clickable="true" android:focusable="true" android:foreground="?android:attr/selectableItemBackground"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:layout_gravity="center"> <TextView android:id="@+id/singleItemTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingStart="10dp" android:paddingEnd="10dp" android:text="TEST TEXT" android:gravity="center" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="15sp" android:textAllCaps="true" android:letterSpacing="0.2" /> </RelativeLayout> </androidx.cardview.widget.CardView></RelativeLayout> This is basically the layout of the items shown in the recyclerViewOne or the main list or the horizontal RecyclerView. Step 3: Add single_card_layout_vertical.xml for the sub-list items Go to the res -> layout Right Click on the layout folder Go to New -> Layout Resource File Type the file name (single_card_layout_vertical.xml as per this example) Change the root element to RelativeLayout Click OK Here is the code of this XML file: XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"> <androidx.cardview.widget.CardView android:id="@+id/singleItemCardView" android:layout_width="match_parent" android:layout_height="60dp" android:layout_margin="10dp" android:clickable="true" android:elevation="10dp" android:focusable="true" android:foreground="?android:attr/selectableItemBackground" app:cardCornerRadius="5dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center_vertical" android:padding="5dp"> <TextView android:id="@+id/singleItemTextViewRVTwo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:letterSpacing="0.2" android:paddingStart="10dp" android:paddingEnd="10dp" android:text="TEST TEXT" android:textAlignment="inherit" android:textAllCaps="true" android:textColor="@android:color/black" android:textSize="15sp" /> </RelativeLayout> </androidx.cardview.widget.CardView></RelativeLayout> This is the layout of the items shown in the recyclerViewTwo or the sub list or the vertical RecyclerView. Step 4: Working on the horizontal RecyclerView or the main list Go to java ->com.wheic.recyclergetsout (Your’s may differ) Make a directory under com.wheic.recyclergetsout (I named it RV1). Making a directory from Android Studio is weird, there’s a lot of bugs in the process (at least for me). So you can follow these steps: Right-click on com.wheic.recyclergetsout (Your’s may differ) com.wheic.recyclergetsout -> New -> Sample Data Directory Go to Build -> Rebuild Project A sampledata folder will be seen under the app folder. Right-click on it. Go to Refactor -> Rename. Give the name of the folder. (Here we named it RV1). Click Refactor. Drag the folder on to com.wheic.recyclergetsout Click Refactor in the pop-up window. Go to Build -> Rebuild Project. OR, If don’t wanna do all these, just directly go to the Explorer and make a directory there. For this right-click on com.wheic.recyclergetsout -> Show in Explorer. Then create a folder there manually. Start working on the corresponding model class: Right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneModel.So basically I am using two variables, one String type, and one integer. The String variable will be used to store the title of the list item and the integer variable to differentiate each item. Then a constructor with both the variables and only the Getter functions are made for these two variables.Here’s the java code of the model class: Right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneModel. So basically I am using two variables, one String type, and one integer. The String variable will be used to store the title of the list item and the integer variable to differentiate each item. Then a constructor with both the variables and only the Getter functions are made for these two variables. Here’s the java code of the model class: Java public class RVOneModel { // this variable will store main-list item title private String name; // this will differentiate between the main-list items private int num; // parameterized constructor public RVOneModel(String name, int num) { this.name = name; this.num = num; } // getter functions for these two variables public String getName() { return name; } public int getNum() { return num; }} Start working on the Adapter class for the horizontal RecyclerView: So, right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneAdapter.So with the adapter, we also need a ViewHolder class.The use of these classes and every other method are already clearly described in this GFG link.Here’s the java code of this Adapter class with the ViewHolder class: So, right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneAdapter. So with the adapter, we also need a ViewHolder class. The use of these classes and every other method are already clearly described in this GFG link. Here’s the java code of this Adapter class with the ViewHolder class: Java import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.cardview.widget.CardView;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVOneAdapter extends RecyclerView.Adapter<RVOneAdapter.ViewHolder> { // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // Parameterized constructor of this // class to initialize tutorialList public RVOneAdapter(List<RVOneModel> tutorialList) { this.tutorialList = tutorialList; } // Attach the item layout with the proper xml file @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final RVOneModel modelItems = tutorialList.get(position); holder.setData(tutorialList.get(position).getName()); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public CardView singleItemCardView; public TextView singleItemTextView; //Link up the Main-List items layout // components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); singleItemCardView = itemView.findViewById(R.id.singleItemCardView); singleItemTextView = itemView.findViewById(R.id.singleItemTextView); } // setText in Main-List title text public void setData(String name){ this.singleItemTextView.setText(name); } }} Start working on the MainActivity.java to add the first RecyclerView: The tutorialList is stored with Main-List item title string variables one by one and then the adapter is set to the horizontal RecyclerView.Here is the code in MainActivity.java to add the first RecyclerView: The tutorialList is stored with Main-List item title string variables one by one and then the adapter is set to the horizontal RecyclerView. Here is the code in MainActivity.java to add the first RecyclerView: Java import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import android.widget.LinearLayout;import android.widget.TextView;import com.wheic.recyclergetsout.RV1.RVOneAdapter;import com.wheic.recyclergetsout.RV1.RVOneModel;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // reference for the Main-List RecyclerView private RecyclerView RVOne; // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // reference for the RVOneAdapter class private RVOneAdapter rvOneAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Linked up with its respective id // used in the activity_main.xml RVOne = findViewById(R.id.recyclerViewOne); RVTwo = findViewById(R.id.recyclerViewTwo); // Setting the Main-List RecyclerView horizontally RVOne.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false)); tutorialList = new ArrayList<>(); // Static data are stored one by one in the tutorialList arrayList tutorialList.add(new RVOneModel("Algorithms", 1)); tutorialList.add(new RVOneModel("Data Structures", 2)); tutorialList.add(new RVOneModel("Languages", 3)); tutorialList.add(new RVOneModel("Interview Corner", 4)); tutorialList.add(new RVOneModel("GATE", 5)); tutorialList.add(new RVOneModel("ISRO CS", 6)); tutorialList.add(new RVOneModel("UGC NET CS", 7)); tutorialList.add(new RVOneModel("CS Subjects", 8)); tutorialList.add(new RVOneModel("Web Technologies", 9)); rvOneAdapter = new RVOneAdapter(tutorialList); RVOne.setAdapter(rvOneAdapter); }} Step 5: Set up the clickListener for each item in the horizontal RecyclerView: The next 4 steps are done in RVOneAdapater.java First, an interface is created in RVOneAdapater.java for each item click with an onItemClick abstract method. Java // Interface to perform events on Main-List item clickpublic interface OnItemsClickListener{ void onItemClick(RVOneModel rvOneModel);} A reference variable of the interface is created. Java // Need this for the Main-list item onClick eventsprivate OnItemsClickListener listener; A method setWhenClickListener is created that will be called from the MainActivity. Java // Main-list item clickListener is initialized// This will be used in MainActivitypublic void setWhenClickListener(OnItemsClickListener listener){ this.listener = listener;} Now, inside onBindViewHolder, a setOnClickListener is created that will actually call the onItemClick method when a single item in the horizontal RecyclerView is clicked. Java holder.singleItemCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener != null){ listener.onItemClick(modelItems); } }}); In MainActivity.java, a reference variable is made for the TextView and it is attached with the XML file using the corresponding id. Java algorithmTitleText = findViewById(R.id.algorithmTitleText); Now, adapter setOnClickListener is called and the textView text change event will occur when a single list-item is clicked. Java rvOneAdapter.setWhenClickListener(new RVOneAdapter.OnItemsClickListener() { @Override public void onItemClick(RVOneModel rvOneModel) { algorithmTitleText.setText(rvOneModel.getName()); setRVTwoList(rvOneModel.getNum()); }}); Step 6: Work on the vertical RecyclerView or the sub-list Go to java -> com.wheic.recyclergetsout (Your’s may differ) Just like the previous one, a directory is made. I named it RV2. Start working on the model class for the sub-list: Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. for me it’s RVTwoModel.As per this app, in this model class, only one String variable is necessary. The String variable will store the title text of the sub-list item. Then just like the previous one a constructor and a getter function are created.Here’s the java code of the model class. Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. for me it’s RVTwoModel. As per this app, in this model class, only one String variable is necessary. The String variable will store the title text of the sub-list item. Then just like the previous one a constructor and a getter function are created. Here’s the java code of the model class. Java public class RVTwoModel { // this variable will store sub-list item title private String name; // parameterized constructor public RVTwoModel(String name) { this.name = name; } // getter function for the name variable public String getName() { return name; }} Start working on the Adapter class for the vertical RecyclerView: Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. I named it RVTwoAdapter.Just like any other RecyclerView, this adapter class is also not that different.Here’s the java code of this Adapter class and the ViewHolder class: Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. I named it RVTwoAdapter. Just like any other RecyclerView, this adapter class is also not that different. Here’s the java code of this Adapter class and the ViewHolder class: Java import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVTwoAdapter extends RecyclerView.Adapter<RVTwoAdapter.ViewHolder> { // Sub-list item titles will be stored here private List<RVTwoModel> tutorialSubList; // Parameterized constructor of this class // to initialize tutorialSubList public RVTwoAdapter(List<RVTwoModel> tutorialSubList) { this.tutorialSubList = tutorialSubList; } // Attach the item layout with the proper xml file @NonNull @Override public RVTwoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout_vertical, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull RVTwoAdapter.ViewHolder holder, int position) { holder.setData(tutorialSubList.get(position).getName()); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialSubList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public TextView rvTwoText; // Link up the Sub-List items layout // components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); rvTwoText = itemView.findViewById(R.id.singleItemTextViewRVTwo); } // setText in Sub-List title text public void setData(String name){ this.rvTwoText.setText(name); } }} Let’s finish the code in MainActivity.java: A second ArrayList tutorialSubList for the sub-list is needed. So a reference variable of a second ArrayList is created. A second ArrayList tutorialSubList for the sub-list is needed. So a reference variable of a second ArrayList is created. Java // Sub-list item titles will be stored hereprivate List<RVTwoModel> tutorialSubList; A function is created just for the vertical recyclerView, which takes an integer parameter.The static data is added in the ArrayList for each main-list item. A function is created just for the vertical recyclerView, which takes an integer parameter. The static data is added in the ArrayList for each main-list item. Here is the code for the function: Java private void setRVTwoList(int num){ // Setting the Sub-List RecyclerView vertically RVTwo.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); // Previous tutorialSubList will be deleted // and new memory will be allocated tutorialSubList = new ArrayList<>(); // Static data are stored one by one in the // tutorialSubList arrayList for each Main-List items if (num == 1) { tutorialSubList.add(new RVTwoModel("Searching Algorithms")); tutorialSubList.add(new RVTwoModel("Sorting Algorithms")); tutorialSubList.add(new RVTwoModel("Graph Algorithms")); tutorialSubList.add(new RVTwoModel("Pattern Algorithms")); tutorialSubList.add(new RVTwoModel("Geometric Algorithms")); tutorialSubList.add(new RVTwoModel("Mathematical")); tutorialSubList.add(new RVTwoModel("Randomized Algorithms")); tutorialSubList.add(new RVTwoModel("Greedy Algorithms")); tutorialSubList.add(new RVTwoModel("Dynamic Programming")); tutorialSubList.add(new RVTwoModel("Divide and Conquer")); tutorialSubList.add(new RVTwoModel("Backtracking")); tutorialSubList.add(new RVTwoModel("Branch and Bound")); tutorialSubList.add(new RVTwoModel("All Algorithms")); } else if (num == 2){ tutorialSubList.add(new RVTwoModel("Arrays")); tutorialSubList.add(new RVTwoModel("Linked List")); tutorialSubList.add(new RVTwoModel("Stack")); tutorialSubList.add(new RVTwoModel("Queue")); tutorialSubList.add(new RVTwoModel("Binary Tree")); tutorialSubList.add(new RVTwoModel("Binary Search Tree")); tutorialSubList.add(new RVTwoModel("Heap")); tutorialSubList.add(new RVTwoModel("Hashing")); tutorialSubList.add(new RVTwoModel("Graph")); tutorialSubList.add(new RVTwoModel("Advanced Data Structure")); tutorialSubList.add(new RVTwoModel("Matrix")); tutorialSubList.add(new RVTwoModel("Strings")); tutorialSubList.add(new RVTwoModel("All Data Structures")); } else if (num == 3){ tutorialSubList.add(new RVTwoModel("C")); tutorialSubList.add(new RVTwoModel("C++")); tutorialSubList.add(new RVTwoModel("Java")); tutorialSubList.add(new RVTwoModel("Python")); tutorialSubList.add(new RVTwoModel("C#")); tutorialSubList.add(new RVTwoModel("Javascript")); tutorialSubList.add(new RVTwoModel("JQuery")); tutorialSubList.add(new RVTwoModel("SQL")); tutorialSubList.add(new RVTwoModel("PHP")); tutorialSubList.add(new RVTwoModel("Scala")); tutorialSubList.add(new RVTwoModel("Perl")); tutorialSubList.add(new RVTwoModel("GO Language")); tutorialSubList.add(new RVTwoModel("HTML")); tutorialSubList.add(new RVTwoModel("CSS")); tutorialSubList.add(new RVTwoModel("Kotlin")); } else if (num == 4){ tutorialSubList.add(new RVTwoModel("Company Preparation")); tutorialSubList.add(new RVTwoModel("Top Topics")); tutorialSubList.add(new RVTwoModel("Practice Company Questions")); tutorialSubList.add(new RVTwoModel("Interview Experiences")); tutorialSubList.add(new RVTwoModel("Experienced Interviews")); tutorialSubList.add(new RVTwoModel("Internship Interviews")); tutorialSubList.add(new RVTwoModel("Competitive Programming")); tutorialSubList.add(new RVTwoModel("Design Patterns")); tutorialSubList.add(new RVTwoModel("Multiple Choice Quizzes")); } else if (num == 5){ tutorialSubList.add(new RVTwoModel("GATE CS Notes 2021")); tutorialSubList.add(new RVTwoModel("Last Minute Notes")); tutorialSubList.add(new RVTwoModel("GATE CS Solved Papers")); tutorialSubList.add(new RVTwoModel("GATE CS Original Papers and Official Keys")); tutorialSubList.add(new RVTwoModel("GATE 2021 Dates")); tutorialSubList.add(new RVTwoModel("GATE CS 2021 Syllabus")); tutorialSubList.add(new RVTwoModel("Important Topics for GATE CS")); tutorialSubList.add(new RVTwoModel("Sudo GATE 2021")); } else if (num == 6){ tutorialSubList.add(new RVTwoModel("ISRO CS Solved Papers")); tutorialSubList.add(new RVTwoModel("ISRO CS Original Papers and Official Keys")); tutorialSubList.add(new RVTwoModel("ISRO CS Syllabus for Scientist/Engineer Exam")); } else if (num == 7){ tutorialSubList.add(new RVTwoModel("UGC NET CS Notes Paper II")); tutorialSubList.add(new RVTwoModel("UGC NET CS Notes Paper III")); tutorialSubList.add(new RVTwoModel("UGC NET CS Solved Papers")); } else if (num == 8){ tutorialSubList.add(new RVTwoModel("Mathematics")); tutorialSubList.add(new RVTwoModel("Operating System")); tutorialSubList.add(new RVTwoModel("DBMS")); tutorialSubList.add(new RVTwoModel("Computer Networks")); tutorialSubList.add(new RVTwoModel("Computer Organization and Architecture")); tutorialSubList.add(new RVTwoModel("Theory of Computation")); tutorialSubList.add(new RVTwoModel("Compiler Design")); tutorialSubList.add(new RVTwoModel("Digital Logic")); tutorialSubList.add(new RVTwoModel("Software Engineering")); } else if (num == 9){ tutorialSubList.add(new RVTwoModel("HTML")); tutorialSubList.add(new RVTwoModel("CSS")); tutorialSubList.add(new RVTwoModel("Javascript")); tutorialSubList.add(new RVTwoModel("jQuery")); tutorialSubList.add(new RVTwoModel("PHP")); } rvTwoAdapter = new RVTwoAdapter(tutorialSubList); RVTwo.setAdapter(rvTwoAdapter);} Inside onCreate(), the setRVTwo() function is called in the main-list item clickListener. Also, it is called outside because we need to see the sub-list just when the activity gets created. Java // The app will show Algorithms Sub-List// every time the activity startsalgorithmTitleText.setText("Algorithms");setRVTwoList(1); MainActivity.java Java import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import android.widget.LinearLayout;import android.widget.TextView;import com.wheic.recyclergetsout.RV1.RVOneAdapter;import com.wheic.recyclergetsout.RV1.RVOneModel;import com.wheic.recyclergetsout.RV2.RVTwoAdapter;import com.wheic.recyclergetsout.RV2.RVTwoModel;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // reference for the Main-List RecyclerView private RecyclerView RVOne; // reference for the Sub-List RecyclerView private RecyclerView RVTwo; // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // Sub-list item titles will be stored here private List<RVTwoModel> tutorialSubList; // reference for the RVOneAdapter class private RVOneAdapter rvOneAdapter; // reference for the RVTwoAdapter class private RVTwoAdapter rvTwoAdapter; // TextView to show the title of the clicked Main-List item private TextView algorithmTitleText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Linked up with its respective id used in the activity_main.xml RVOne = findViewById(R.id.recyclerViewOne); RVTwo = findViewById(R.id.recyclerViewTwo); algorithmTitleText = findViewById(R.id.algorithmTitleText); // Setting the Main-List RecyclerView horizontally RVOne.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false)); tutorialList = new ArrayList<>(); // Static data are stored one by one in the tutorialList arrayList tutorialList.add(new RVOneModel("Algorithms", 1)); tutorialList.add(new RVOneModel("Data Structures", 2)); tutorialList.add(new RVOneModel("Languages", 3)); tutorialList.add(new RVOneModel("Interview Corner", 4)); tutorialList.add(new RVOneModel("GATE", 5)); tutorialList.add(new RVOneModel("ISRO CS", 6)); tutorialList.add(new RVOneModel("UGC NET CS", 7)); tutorialList.add(new RVOneModel("CS Subjects", 8)); tutorialList.add(new RVOneModel("Web Technologies", 9)); // The app will show Algorithms Sub-List every time the activity starts algorithmTitleText.setText("Algorithms"); setRVTwoList(1); rvOneAdapter = new RVOneAdapter(tutorialList); RVOne.setAdapter(rvOneAdapter); // Setting up the events that will occur on each Main-List item click rvOneAdapter.setWhenClickListener(new RVOneAdapter.OnItemsClickListener() { @Override public void onItemClick(RVOneModel rvOneModel) { algorithmTitleText.setText(rvOneModel.getName()); setRVTwoList(rvOneModel.getNum()); } }); } private void setRVTwoList(int num){ // Setting the Sub-List RecyclerView vertically RVTwo.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); // Previous tutorialSubList will be deleted and new memory will be allocated tutorialSubList = new ArrayList<>(); // Static data are stored one by one in the tutorialSubList arrayList for each Main-List items if (num == 1) { tutorialSubList.add(new RVTwoModel("Searching Algorithms")); tutorialSubList.add(new RVTwoModel("Sorting Algorithms")); tutorialSubList.add(new RVTwoModel("Graph Algorithms")); tutorialSubList.add(new RVTwoModel("Pattern Algorithms")); tutorialSubList.add(new RVTwoModel("Geometric Algorithms")); tutorialSubList.add(new RVTwoModel("Mathematical")); tutorialSubList.add(new RVTwoModel("Randomized Algorithms")); tutorialSubList.add(new RVTwoModel("Greedy Algorithms")); tutorialSubList.add(new RVTwoModel("Dynamic Programming")); tutorialSubList.add(new RVTwoModel("Divide and Conquer")); tutorialSubList.add(new RVTwoModel("Backtracking")); tutorialSubList.add(new RVTwoModel("Branch and Bound")); tutorialSubList.add(new RVTwoModel("All Algorithms")); } else if (num == 2){ tutorialSubList.add(new RVTwoModel("Arrays")); tutorialSubList.add(new RVTwoModel("Linked List")); tutorialSubList.add(new RVTwoModel("Stack")); tutorialSubList.add(new RVTwoModel("Queue")); tutorialSubList.add(new RVTwoModel("Binary Tree")); tutorialSubList.add(new RVTwoModel("Binary Search Tree")); tutorialSubList.add(new RVTwoModel("Heap")); tutorialSubList.add(new RVTwoModel("Hashing")); tutorialSubList.add(new RVTwoModel("Graph")); tutorialSubList.add(new RVTwoModel("Advanced Data Structure")); tutorialSubList.add(new RVTwoModel("Matrix")); tutorialSubList.add(new RVTwoModel("Strings")); tutorialSubList.add(new RVTwoModel("All Data Structures")); } else if (num == 3){ tutorialSubList.add(new RVTwoModel("C")); tutorialSubList.add(new RVTwoModel("C++")); tutorialSubList.add(new RVTwoModel("Java")); tutorialSubList.add(new RVTwoModel("Python")); tutorialSubList.add(new RVTwoModel("C#")); tutorialSubList.add(new RVTwoModel("Javascript")); tutorialSubList.add(new RVTwoModel("JQuery")); tutorialSubList.add(new RVTwoModel("SQL")); tutorialSubList.add(new RVTwoModel("PHP")); tutorialSubList.add(new RVTwoModel("Scala")); tutorialSubList.add(new RVTwoModel("Perl")); tutorialSubList.add(new RVTwoModel("GO Language")); tutorialSubList.add(new RVTwoModel("HTML")); tutorialSubList.add(new RVTwoModel("CSS")); tutorialSubList.add(new RVTwoModel("Kotlin")); } else if (num == 4){ tutorialSubList.add(new RVTwoModel("Company Preparation")); tutorialSubList.add(new RVTwoModel("Top Topics")); tutorialSubList.add(new RVTwoModel("Practice Company Questions")); tutorialSubList.add(new RVTwoModel("Interview Experiences")); tutorialSubList.add(new RVTwoModel("Experienced Interviews")); tutorialSubList.add(new RVTwoModel("Internship Interviews")); tutorialSubList.add(new RVTwoModel("Competitive Programming")); tutorialSubList.add(new RVTwoModel("Design Patterns")); tutorialSubList.add(new RVTwoModel("Multiple Choice Quizzes")); } else if (num == 5){ tutorialSubList.add(new RVTwoModel("GATE CS Notes 2021")); tutorialSubList.add(new RVTwoModel("Last Minute Notes")); tutorialSubList.add(new RVTwoModel("GATE CS Solved Papers")); tutorialSubList.add(new RVTwoModel("GATE CS Original Papers and Official Keys")); tutorialSubList.add(new RVTwoModel("GATE 2021 Dates")); tutorialSubList.add(new RVTwoModel("GATE CS 2021 Syllabus")); tutorialSubList.add(new RVTwoModel("Important Topics for GATE CS")); tutorialSubList.add(new RVTwoModel("Sudo GATE 2021")); } else if (num == 6){ tutorialSubList.add(new RVTwoModel("ISRO CS Solved Papers")); tutorialSubList.add(new RVTwoModel("ISRO CS Original Papers and Official Keys")); tutorialSubList.add(new RVTwoModel("ISRO CS Syllabus for Scientist/Engineer Exam")); } else if (num == 7){ tutorialSubList.add(new RVTwoModel("UGC NET CS Notes Paper II")); tutorialSubList.add(new RVTwoModel("UGC NET CS Notes Paper III")); tutorialSubList.add(new RVTwoModel("UGC NET CS Solved Papers")); } else if (num == 8){ tutorialSubList.add(new RVTwoModel("Mathematics")); tutorialSubList.add(new RVTwoModel("Operating System")); tutorialSubList.add(new RVTwoModel("DBMS")); tutorialSubList.add(new RVTwoModel("Computer Networks")); tutorialSubList.add(new RVTwoModel("Computer Organization and Architecture")); tutorialSubList.add(new RVTwoModel("Theory of Computation")); tutorialSubList.add(new RVTwoModel("Compiler Design")); tutorialSubList.add(new RVTwoModel("Digital Logic")); tutorialSubList.add(new RVTwoModel("Software Engineering")); } else if (num == 9){ tutorialSubList.add(new RVTwoModel("HTML")); tutorialSubList.add(new RVTwoModel("CSS")); tutorialSubList.add(new RVTwoModel("Javascript")); tutorialSubList.add(new RVTwoModel("jQuery")); tutorialSubList.add(new RVTwoModel("PHP")); } rvTwoAdapter = new RVTwoAdapter(tutorialSubList); RVTwo.setAdapter(rvTwoAdapter); }} RVOneAdapter.java Java import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.cardview.widget.CardView;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVOneAdapter extends RecyclerView.Adapter<RVOneAdapter.ViewHolder> { // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // Need this clickListener for the Main-list item onClick events private OnItemsClickListener listener; // Parameterized constructor of this class to initialize tutorialList public RVOneAdapter(List<RVOneModel> tutorialList) { this.tutorialList = tutorialList; } // Main-list item clickListener is initialized // This will be used in MainActivity public void setWhenClickListener(OnItemsClickListener listener){ this.listener = listener; } // Attach the item layout with the proper xml file @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final RVOneModel modelItems = tutorialList.get(position); holder.setData(tutorialList.get(position).getName()); holder.singleItemCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener != null){ listener.onItemClick(modelItems); } } }); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public CardView singleItemCardView; public TextView singleItemTextView; // Link up the Main-List items layout components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); singleItemCardView = itemView.findViewById(R.id.singleItemCardView); singleItemTextView = itemView.findViewById(R.id.singleItemTextView); } // setText in Main-List title text public void setData(String name){ this.singleItemTextView.setText(name); } } // Interface to perform events on Main-List item click public interface OnItemsClickListener{ void onItemClick(RVOneModel rvOneModel); }} RVOneModel.java Java public class RVOneModel { // this variable will store main-list item title private String name; // this will help differentiate between the main-list items private int num; // parameterized constructor public RVOneModel(String name, int num) { this.name = name; this.num = num; } // getter functions for these two variables public String getName() { return name; } public int getNum() { return num; }} RVTwoAdapter.java Java import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVTwoAdapter extends RecyclerView.Adapter<RVTwoAdapter.ViewHolder> { // Sub-list item titles will be stored here private List<RVTwoModel> tutorialSubList; // Parameterized constructor of this // class to initialize tutorialSubList public RVTwoAdapter(List<RVTwoModel> tutorialSubList) { this.tutorialSubList = tutorialSubList; } // Attach the item layout with the proper xml file @NonNull @Override public RVTwoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout_vertical, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull RVTwoAdapter.ViewHolder holder, int position) { holder.setData(tutorialSubList.get(position).getName()); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialSubList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public TextView rvTwoText; // Link up the Sub-List items layout components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); rvTwoText = itemView.findViewById(R.id.singleItemTextViewRVTwo); } // setText in Sub-List title text public void setData(String name){ this.rvTwoText.setText(name); } }} RVTwoModel.java Java public class RVTwoModel { // this variable will store sub-list item title private String name; // parameterized constructor public RVTwoModel(String name) { this.name = name; } // getter function for the name variable public String getName() { return name; }} You can check this project from this GitHub link. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 25062, "s": 25034, "text": "\n09 Dec, 2020" }, { "code": null, "e": 25468, "s": 25062, "text": "The title may be a little confusing but what we want to say is, suppose in an Android App, there’s a RecyclerView, and outside that there’s a TextView. In the RecyclerView there’s a list of clickable components, said Button. Now what I want is, for different button clicks, the text in the TextView will be different. So this is basically controlling a component outside RecyclerView, from a RecyclerView." }, { "code": null, "e": 25860, "s": 25468, "text": "As per the picture, there’s a RecyclerView with four Buttons (1 hidden at the left) and a TextView. For different Button clicks different texts are showing up in the TextView. In this article, the same concept will be implemented with a little real-world touch. So the final app will show a list and a sub-list of the Tutorials offered by GEEKS FOR GEEKS. Here’s a demo GIF of the final app:" }, { "code": null, "e": 25875, "s": 25860, "text": "Prerequisites:" }, { "code": null, "e": 25905, "s": 25875, "text": "How to install Android Studio" }, { "code": null, "e": 25948, "s": 25905, "text": "Setting up a new project in Android Studio" }, { "code": null, "e": 25969, "s": 25948, "text": "What is RecyclerView" }, { "code": null, "e": 26017, "s": 25969, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 26068, "s": 26017, "text": "Go to the res -> layout -> activity_main.xml file." }, { "code": null, "e": 26103, "s": 26068, "text": "Here is the code of that XML file:" }, { "code": null, "e": 26107, "s": 26103, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"10dp\" android:orientation=\"vertical\" android:padding=\"10dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\"> <TextView style=\"@style/MaterialAlertDialog.MaterialComponents.Title.Icon\" android:layout_width=\"wrap_content\" android:layout_height=\"match_parent\" android:text=\"GEEKS FOR GEEKS TUTORIALS\" android:textAlignment=\"center\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> </LinearLayout> <!-- The horizontal recyclerView where the Main-List items will be showed --> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recyclerViewOne\" android:layout_width=\"match_parent\" android:layout_height=\"150dp\" android:layout_marginTop=\"20dp\" android:clipToPadding=\"false\" android:foregroundGravity=\"center\" android:orientation=\"horizontal\" /> <LinearLayout android:id=\"@+id/linearLayout\" android:layout_width=\"match_parent\" android:layout_height=\"50dp\" android:layout_marginTop=\"20dp\" android:gravity=\"center\"> <!-- The TextView where the Main-List item title text will be showed --> <TextView android:id=\"@+id/algorithmTitleText\" style=\"@style/ShapeAppearance.MaterialComponents.MediumComponent\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"@android:color/black\" android:textSize=\"22sp\" /> </LinearLayout> <!-- The vertical recyclerView where the Sub-List items will be showed --> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recyclerViewTwo\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"20dp\" android:clipToPadding=\"false\" android:foregroundGravity=\"center\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 29083, "s": 26107, "text": null }, { "code": null, "e": 29279, "s": 29083, "text": "Here, two RecyclerView is used, one horizontal (recyclerViewOne) and one vertical (recyclerViewTwo). The first one shows the main list and the second one shows the sub-list of the main list item." }, { "code": null, "e": 29336, "s": 29279, "text": "A TextView is also used to show the main list-item text." }, { "code": null, "e": 29395, "s": 29336, "text": "Step 2: Add single_card_layout.xml for the main list items" }, { "code": null, "e": 29419, "s": 29395, "text": "Go to the res -> layout" }, { "code": null, "e": 29452, "s": 29419, "text": "Right Click on the layout folder" }, { "code": null, "e": 29486, "s": 29452, "text": "Go to New -> Layout Resource File" }, { "code": null, "e": 29537, "s": 29486, "text": "Type the file name (single_card_layout.xml for me)" }, { "code": null, "e": 29579, "s": 29537, "text": "Change the root element to RelativeLayout" }, { "code": null, "e": 29588, "s": 29579, "text": "Click OK" }, { "code": null, "e": 29623, "s": 29588, "text": "Here is the code of this XML file:" }, { "code": null, "e": 29627, "s": 29623, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:gravity=\"center\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\"> <androidx.cardview.widget.CardView android:id=\"@+id/singleItemCardView\" android:layout_width=\"145dp\" android:layout_height=\"match_parent\" android:layout_margin=\"10dp\" android:elevation=\"10dp\" app:cardCornerRadius=\"30dp\" android:clickable=\"true\" android:focusable=\"true\" android:foreground=\"?android:attr/selectableItemBackground\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:layout_gravity=\"center\"> <TextView android:id=\"@+id/singleItemTextView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:paddingStart=\"10dp\" android:paddingEnd=\"10dp\" android:text=\"TEST TEXT\" android:gravity=\"center\" android:textAlignment=\"center\" android:textColor=\"@android:color/black\" android:textSize=\"15sp\" android:textAllCaps=\"true\" android:letterSpacing=\"0.2\" /> </RelativeLayout> </androidx.cardview.widget.CardView></RelativeLayout>", "e": 31160, "s": 29627, "text": null }, { "code": null, "e": 31280, "s": 31160, "text": "This is basically the layout of the items shown in the recyclerViewOne or the main list or the horizontal RecyclerView." }, { "code": null, "e": 31347, "s": 31280, "text": "Step 3: Add single_card_layout_vertical.xml for the sub-list items" }, { "code": null, "e": 31371, "s": 31347, "text": "Go to the res -> layout" }, { "code": null, "e": 31404, "s": 31371, "text": "Right Click on the layout folder" }, { "code": null, "e": 31438, "s": 31404, "text": "Go to New -> Layout Resource File" }, { "code": null, "e": 31511, "s": 31438, "text": "Type the file name (single_card_layout_vertical.xml as per this example)" }, { "code": null, "e": 31553, "s": 31511, "text": "Change the root element to RelativeLayout" }, { "code": null, "e": 31562, "s": 31553, "text": "Click OK" }, { "code": null, "e": 31597, "s": 31562, "text": "Here is the code of this XML file:" }, { "code": null, "e": 31601, "s": 31597, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\"> <androidx.cardview.widget.CardView android:id=\"@+id/singleItemCardView\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_margin=\"10dp\" android:clickable=\"true\" android:elevation=\"10dp\" android:focusable=\"true\" android:foreground=\"?android:attr/selectableItemBackground\" app:cardCornerRadius=\"5dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_gravity=\"center\" android:gravity=\"center_vertical\" android:padding=\"5dp\"> <TextView android:id=\"@+id/singleItemTextViewRVTwo\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:gravity=\"center_vertical\" android:letterSpacing=\"0.2\" android:paddingStart=\"10dp\" android:paddingEnd=\"10dp\" android:text=\"TEST TEXT\" android:textAlignment=\"inherit\" android:textAllCaps=\"true\" android:textColor=\"@android:color/black\" android:textSize=\"15sp\" /> </RelativeLayout> </androidx.cardview.widget.CardView></RelativeLayout>", "e": 33191, "s": 31601, "text": null }, { "code": null, "e": 33298, "s": 33191, "text": "This is the layout of the items shown in the recyclerViewTwo or the sub list or the vertical RecyclerView." }, { "code": null, "e": 33362, "s": 33298, "text": "Step 4: Working on the horizontal RecyclerView or the main list" }, { "code": null, "e": 33421, "s": 33362, "text": "Go to java ->com.wheic.recyclergetsout (Your’s may differ)" }, { "code": null, "e": 33624, "s": 33421, "text": "Make a directory under com.wheic.recyclergetsout (I named it RV1). Making a directory from Android Studio is weird, there’s a lot of bugs in the process (at least for me). So you can follow these steps:" }, { "code": null, "e": 33685, "s": 33624, "text": "Right-click on com.wheic.recyclergetsout (Your’s may differ)" }, { "code": null, "e": 33743, "s": 33685, "text": "com.wheic.recyclergetsout -> New -> Sample Data Directory" }, { "code": null, "e": 33774, "s": 33743, "text": "Go to Build -> Rebuild Project" }, { "code": null, "e": 33829, "s": 33774, "text": "A sampledata folder will be seen under the app folder." }, { "code": null, "e": 33874, "s": 33829, "text": "Right-click on it. Go to Refactor -> Rename." }, { "code": null, "e": 33927, "s": 33874, "text": "Give the name of the folder. (Here we named it RV1)." }, { "code": null, "e": 33943, "s": 33927, "text": "Click Refactor." }, { "code": null, "e": 33991, "s": 33943, "text": "Drag the folder on to com.wheic.recyclergetsout" }, { "code": null, "e": 34028, "s": 33991, "text": "Click Refactor in the pop-up window." }, { "code": null, "e": 34060, "s": 34028, "text": "Go to Build -> Rebuild Project." }, { "code": null, "e": 34262, "s": 34060, "text": "OR, If don’t wanna do all these, just directly go to the Explorer and make a directory there. For this right-click on com.wheic.recyclergetsout -> Show in Explorer. Then create a folder there manually." }, { "code": null, "e": 34310, "s": 34262, "text": "Start working on the corresponding model class:" }, { "code": null, "e": 34769, "s": 34310, "text": "Right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneModel.So basically I am using two variables, one String type, and one integer. The String variable will be used to store the title of the list item and the integer variable to differentiate each item. Then a constructor with both the variables and only the Getter functions are made for these two variables.Here’s the java code of the model class:" }, { "code": null, "e": 34887, "s": 34769, "text": "Right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneModel." }, { "code": null, "e": 35189, "s": 34887, "text": "So basically I am using two variables, one String type, and one integer. The String variable will be used to store the title of the list item and the integer variable to differentiate each item. Then a constructor with both the variables and only the Getter functions are made for these two variables." }, { "code": null, "e": 35230, "s": 35189, "text": "Here’s the java code of the model class:" }, { "code": null, "e": 35235, "s": 35230, "text": "Java" }, { "code": "public class RVOneModel { // this variable will store main-list item title private String name; // this will differentiate between the main-list items private int num; // parameterized constructor public RVOneModel(String name, int num) { this.name = name; this.num = num; } // getter functions for these two variables public String getName() { return name; } public int getNum() { return num; }}", "e": 35716, "s": 35235, "text": null }, { "code": null, "e": 35784, "s": 35716, "text": "Start working on the Adapter class for the horizontal RecyclerView:" }, { "code": null, "e": 36125, "s": 35784, "text": "So, right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneAdapter.So with the adapter, we also need a ViewHolder class.The use of these classes and every other method are already clearly described in this GFG link.Here’s the java code of this Adapter class with the ViewHolder class:" }, { "code": null, "e": 36249, "s": 36125, "text": "So, right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneAdapter." }, { "code": null, "e": 36303, "s": 36249, "text": "So with the adapter, we also need a ViewHolder class." }, { "code": null, "e": 36399, "s": 36303, "text": "The use of these classes and every other method are already clearly described in this GFG link." }, { "code": null, "e": 36469, "s": 36399, "text": "Here’s the java code of this Adapter class with the ViewHolder class:" }, { "code": null, "e": 36474, "s": 36469, "text": "Java" }, { "code": "import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.cardview.widget.CardView;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVOneAdapter extends RecyclerView.Adapter<RVOneAdapter.ViewHolder> { // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // Parameterized constructor of this // class to initialize tutorialList public RVOneAdapter(List<RVOneModel> tutorialList) { this.tutorialList = tutorialList; } // Attach the item layout with the proper xml file @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final RVOneModel modelItems = tutorialList.get(position); holder.setData(tutorialList.get(position).getName()); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public CardView singleItemCardView; public TextView singleItemTextView; //Link up the Main-List items layout // components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); singleItemCardView = itemView.findViewById(R.id.singleItemCardView); singleItemTextView = itemView.findViewById(R.id.singleItemTextView); } // setText in Main-List title text public void setData(String name){ this.singleItemTextView.setText(name); } }}", "e": 38622, "s": 36474, "text": null }, { "code": null, "e": 38692, "s": 38622, "text": "Start working on the MainActivity.java to add the first RecyclerView:" }, { "code": null, "e": 38901, "s": 38692, "text": "The tutorialList is stored with Main-List item title string variables one by one and then the adapter is set to the horizontal RecyclerView.Here is the code in MainActivity.java to add the first RecyclerView:" }, { "code": null, "e": 39042, "s": 38901, "text": "The tutorialList is stored with Main-List item title string variables one by one and then the adapter is set to the horizontal RecyclerView." }, { "code": null, "e": 39111, "s": 39042, "text": "Here is the code in MainActivity.java to add the first RecyclerView:" }, { "code": null, "e": 39116, "s": 39111, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import android.widget.LinearLayout;import android.widget.TextView;import com.wheic.recyclergetsout.RV1.RVOneAdapter;import com.wheic.recyclergetsout.RV1.RVOneModel;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // reference for the Main-List RecyclerView private RecyclerView RVOne; // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // reference for the RVOneAdapter class private RVOneAdapter rvOneAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Linked up with its respective id // used in the activity_main.xml RVOne = findViewById(R.id.recyclerViewOne); RVTwo = findViewById(R.id.recyclerViewTwo); // Setting the Main-List RecyclerView horizontally RVOne.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false)); tutorialList = new ArrayList<>(); // Static data are stored one by one in the tutorialList arrayList tutorialList.add(new RVOneModel(\"Algorithms\", 1)); tutorialList.add(new RVOneModel(\"Data Structures\", 2)); tutorialList.add(new RVOneModel(\"Languages\", 3)); tutorialList.add(new RVOneModel(\"Interview Corner\", 4)); tutorialList.add(new RVOneModel(\"GATE\", 5)); tutorialList.add(new RVOneModel(\"ISRO CS\", 6)); tutorialList.add(new RVOneModel(\"UGC NET CS\", 7)); tutorialList.add(new RVOneModel(\"CS Subjects\", 8)); tutorialList.add(new RVOneModel(\"Web Technologies\", 9)); rvOneAdapter = new RVOneAdapter(tutorialList); RVOne.setAdapter(rvOneAdapter); }}", "e": 41106, "s": 39116, "text": null }, { "code": null, "e": 41187, "s": 41108, "text": "Step 5: Set up the clickListener for each item in the horizontal RecyclerView:" }, { "code": null, "e": 41235, "s": 41187, "text": "The next 4 steps are done in RVOneAdapater.java" }, { "code": null, "e": 41345, "s": 41235, "text": "First, an interface is created in RVOneAdapater.java for each item click with an onItemClick abstract method." }, { "code": null, "e": 41350, "s": 41345, "text": "Java" }, { "code": "// Interface to perform events on Main-List item clickpublic interface OnItemsClickListener{ void onItemClick(RVOneModel rvOneModel);}", "e": 41488, "s": 41350, "text": null }, { "code": null, "e": 41538, "s": 41488, "text": "A reference variable of the interface is created." }, { "code": null, "e": 41543, "s": 41538, "text": "Java" }, { "code": "// Need this for the Main-list item onClick eventsprivate OnItemsClickListener listener;", "e": 41632, "s": 41543, "text": null }, { "code": null, "e": 41716, "s": 41632, "text": "A method setWhenClickListener is created that will be called from the MainActivity." }, { "code": null, "e": 41721, "s": 41716, "text": "Java" }, { "code": "// Main-list item clickListener is initialized// This will be used in MainActivitypublic void setWhenClickListener(OnItemsClickListener listener){ this.listener = listener;}", "e": 41898, "s": 41721, "text": null }, { "code": null, "e": 42069, "s": 41898, "text": "Now, inside onBindViewHolder, a setOnClickListener is created that will actually call the onItemClick method when a single item in the horizontal RecyclerView is clicked." }, { "code": null, "e": 42074, "s": 42069, "text": "Java" }, { "code": "holder.singleItemCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener != null){ listener.onItemClick(modelItems); } }});", "e": 42285, "s": 42074, "text": null }, { "code": null, "e": 42418, "s": 42285, "text": "In MainActivity.java, a reference variable is made for the TextView and it is attached with the XML file using the corresponding id." }, { "code": null, "e": 42423, "s": 42418, "text": "Java" }, { "code": "algorithmTitleText = findViewById(R.id.algorithmTitleText);", "e": 42483, "s": 42423, "text": null }, { "code": null, "e": 42607, "s": 42483, "text": "Now, adapter setOnClickListener is called and the textView text change event will occur when a single list-item is clicked." }, { "code": null, "e": 42612, "s": 42607, "text": "Java" }, { "code": "rvOneAdapter.setWhenClickListener(new RVOneAdapter.OnItemsClickListener() { @Override public void onItemClick(RVOneModel rvOneModel) { algorithmTitleText.setText(rvOneModel.getName()); setRVTwoList(rvOneModel.getNum()); }});", "e": 42860, "s": 42612, "text": null }, { "code": null, "e": 42918, "s": 42860, "text": "Step 6: Work on the vertical RecyclerView or the sub-list" }, { "code": null, "e": 42978, "s": 42918, "text": "Go to java -> com.wheic.recyclergetsout (Your’s may differ)" }, { "code": null, "e": 43043, "s": 42978, "text": "Just like the previous one, a directory is made. I named it RV2." }, { "code": null, "e": 43094, "s": 43043, "text": "Start working on the model class for the sub-list:" }, { "code": null, "e": 43478, "s": 43094, "text": "Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. for me it’s RVTwoModel.As per this app, in this model class, only one String variable is necessary. The String variable will store the title text of the sub-list item. Then just like the previous one a constructor and a getter function are created.Here’s the java code of the model class." }, { "code": null, "e": 43597, "s": 43478, "text": "Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. for me it’s RVTwoModel." }, { "code": null, "e": 43823, "s": 43597, "text": "As per this app, in this model class, only one String variable is necessary. The String variable will store the title text of the sub-list item. Then just like the previous one a constructor and a getter function are created." }, { "code": null, "e": 43864, "s": 43823, "text": "Here’s the java code of the model class." }, { "code": null, "e": 43869, "s": 43864, "text": "Java" }, { "code": "public class RVTwoModel { // this variable will store sub-list item title private String name; // parameterized constructor public RVTwoModel(String name) { this.name = name; } // getter function for the name variable public String getName() { return name; }}", "e": 44174, "s": 43869, "text": null }, { "code": null, "e": 44240, "s": 44174, "text": "Start working on the Adapter class for the vertical RecyclerView:" }, { "code": null, "e": 44508, "s": 44240, "text": "Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. I named it RVTwoAdapter.Just like any other RecyclerView, this adapter class is also not that different.Here’s the java code of this Adapter class and the ViewHolder class:" }, { "code": null, "e": 44628, "s": 44508, "text": "Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. I named it RVTwoAdapter." }, { "code": null, "e": 44709, "s": 44628, "text": "Just like any other RecyclerView, this adapter class is also not that different." }, { "code": null, "e": 44778, "s": 44709, "text": "Here’s the java code of this Adapter class and the ViewHolder class:" }, { "code": null, "e": 44783, "s": 44778, "text": "Java" }, { "code": "import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVTwoAdapter extends RecyclerView.Adapter<RVTwoAdapter.ViewHolder> { // Sub-list item titles will be stored here private List<RVTwoModel> tutorialSubList; // Parameterized constructor of this class // to initialize tutorialSubList public RVTwoAdapter(List<RVTwoModel> tutorialSubList) { this.tutorialSubList = tutorialSubList; } // Attach the item layout with the proper xml file @NonNull @Override public RVTwoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout_vertical, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull RVTwoAdapter.ViewHolder holder, int position) { holder.setData(tutorialSubList.get(position).getName()); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialSubList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public TextView rvTwoText; // Link up the Sub-List items layout // components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); rvTwoText = itemView.findViewById(R.id.singleItemTextViewRVTwo); } // setText in Sub-List title text public void setData(String name){ this.rvTwoText.setText(name); } }}", "e": 46730, "s": 44783, "text": null }, { "code": null, "e": 46774, "s": 46730, "text": "Let’s finish the code in MainActivity.java:" }, { "code": null, "e": 46895, "s": 46774, "text": "A second ArrayList tutorialSubList for the sub-list is needed. So a reference variable of a second ArrayList is created." }, { "code": null, "e": 47016, "s": 46895, "text": "A second ArrayList tutorialSubList for the sub-list is needed. So a reference variable of a second ArrayList is created." }, { "code": null, "e": 47021, "s": 47016, "text": "Java" }, { "code": "// Sub-list item titles will be stored hereprivate List<RVTwoModel> tutorialSubList;", "e": 47106, "s": 47021, "text": null }, { "code": null, "e": 47264, "s": 47106, "text": "A function is created just for the vertical recyclerView, which takes an integer parameter.The static data is added in the ArrayList for each main-list item." }, { "code": null, "e": 47356, "s": 47264, "text": "A function is created just for the vertical recyclerView, which takes an integer parameter." }, { "code": null, "e": 47423, "s": 47356, "text": "The static data is added in the ArrayList for each main-list item." }, { "code": null, "e": 47458, "s": 47423, "text": "Here is the code for the function:" }, { "code": null, "e": 47463, "s": 47458, "text": "Java" }, { "code": "private void setRVTwoList(int num){ // Setting the Sub-List RecyclerView vertically RVTwo.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); // Previous tutorialSubList will be deleted // and new memory will be allocated tutorialSubList = new ArrayList<>(); // Static data are stored one by one in the // tutorialSubList arrayList for each Main-List items if (num == 1) { tutorialSubList.add(new RVTwoModel(\"Searching Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Sorting Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Graph Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Pattern Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Geometric Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Mathematical\")); tutorialSubList.add(new RVTwoModel(\"Randomized Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Greedy Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Dynamic Programming\")); tutorialSubList.add(new RVTwoModel(\"Divide and Conquer\")); tutorialSubList.add(new RVTwoModel(\"Backtracking\")); tutorialSubList.add(new RVTwoModel(\"Branch and Bound\")); tutorialSubList.add(new RVTwoModel(\"All Algorithms\")); } else if (num == 2){ tutorialSubList.add(new RVTwoModel(\"Arrays\")); tutorialSubList.add(new RVTwoModel(\"Linked List\")); tutorialSubList.add(new RVTwoModel(\"Stack\")); tutorialSubList.add(new RVTwoModel(\"Queue\")); tutorialSubList.add(new RVTwoModel(\"Binary Tree\")); tutorialSubList.add(new RVTwoModel(\"Binary Search Tree\")); tutorialSubList.add(new RVTwoModel(\"Heap\")); tutorialSubList.add(new RVTwoModel(\"Hashing\")); tutorialSubList.add(new RVTwoModel(\"Graph\")); tutorialSubList.add(new RVTwoModel(\"Advanced Data Structure\")); tutorialSubList.add(new RVTwoModel(\"Matrix\")); tutorialSubList.add(new RVTwoModel(\"Strings\")); tutorialSubList.add(new RVTwoModel(\"All Data Structures\")); } else if (num == 3){ tutorialSubList.add(new RVTwoModel(\"C\")); tutorialSubList.add(new RVTwoModel(\"C++\")); tutorialSubList.add(new RVTwoModel(\"Java\")); tutorialSubList.add(new RVTwoModel(\"Python\")); tutorialSubList.add(new RVTwoModel(\"C#\")); tutorialSubList.add(new RVTwoModel(\"Javascript\")); tutorialSubList.add(new RVTwoModel(\"JQuery\")); tutorialSubList.add(new RVTwoModel(\"SQL\")); tutorialSubList.add(new RVTwoModel(\"PHP\")); tutorialSubList.add(new RVTwoModel(\"Scala\")); tutorialSubList.add(new RVTwoModel(\"Perl\")); tutorialSubList.add(new RVTwoModel(\"GO Language\")); tutorialSubList.add(new RVTwoModel(\"HTML\")); tutorialSubList.add(new RVTwoModel(\"CSS\")); tutorialSubList.add(new RVTwoModel(\"Kotlin\")); } else if (num == 4){ tutorialSubList.add(new RVTwoModel(\"Company Preparation\")); tutorialSubList.add(new RVTwoModel(\"Top Topics\")); tutorialSubList.add(new RVTwoModel(\"Practice Company Questions\")); tutorialSubList.add(new RVTwoModel(\"Interview Experiences\")); tutorialSubList.add(new RVTwoModel(\"Experienced Interviews\")); tutorialSubList.add(new RVTwoModel(\"Internship Interviews\")); tutorialSubList.add(new RVTwoModel(\"Competitive Programming\")); tutorialSubList.add(new RVTwoModel(\"Design Patterns\")); tutorialSubList.add(new RVTwoModel(\"Multiple Choice Quizzes\")); } else if (num == 5){ tutorialSubList.add(new RVTwoModel(\"GATE CS Notes 2021\")); tutorialSubList.add(new RVTwoModel(\"Last Minute Notes\")); tutorialSubList.add(new RVTwoModel(\"GATE CS Solved Papers\")); tutorialSubList.add(new RVTwoModel(\"GATE CS Original Papers and Official Keys\")); tutorialSubList.add(new RVTwoModel(\"GATE 2021 Dates\")); tutorialSubList.add(new RVTwoModel(\"GATE CS 2021 Syllabus\")); tutorialSubList.add(new RVTwoModel(\"Important Topics for GATE CS\")); tutorialSubList.add(new RVTwoModel(\"Sudo GATE 2021\")); } else if (num == 6){ tutorialSubList.add(new RVTwoModel(\"ISRO CS Solved Papers\")); tutorialSubList.add(new RVTwoModel(\"ISRO CS Original Papers and Official Keys\")); tutorialSubList.add(new RVTwoModel(\"ISRO CS Syllabus for Scientist/Engineer Exam\")); } else if (num == 7){ tutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper II\")); tutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper III\")); tutorialSubList.add(new RVTwoModel(\"UGC NET CS Solved Papers\")); } else if (num == 8){ tutorialSubList.add(new RVTwoModel(\"Mathematics\")); tutorialSubList.add(new RVTwoModel(\"Operating System\")); tutorialSubList.add(new RVTwoModel(\"DBMS\")); tutorialSubList.add(new RVTwoModel(\"Computer Networks\")); tutorialSubList.add(new RVTwoModel(\"Computer Organization and Architecture\")); tutorialSubList.add(new RVTwoModel(\"Theory of Computation\")); tutorialSubList.add(new RVTwoModel(\"Compiler Design\")); tutorialSubList.add(new RVTwoModel(\"Digital Logic\")); tutorialSubList.add(new RVTwoModel(\"Software Engineering\")); } else if (num == 9){ tutorialSubList.add(new RVTwoModel(\"HTML\")); tutorialSubList.add(new RVTwoModel(\"CSS\")); tutorialSubList.add(new RVTwoModel(\"Javascript\")); tutorialSubList.add(new RVTwoModel(\"jQuery\")); tutorialSubList.add(new RVTwoModel(\"PHP\")); } rvTwoAdapter = new RVTwoAdapter(tutorialSubList); RVTwo.setAdapter(rvTwoAdapter);}", "e": 53134, "s": 47463, "text": null }, { "code": null, "e": 53324, "s": 53134, "text": "Inside onCreate(), the setRVTwo() function is called in the main-list item clickListener. Also, it is called outside because we need to see the sub-list just when the activity gets created." }, { "code": null, "e": 53329, "s": 53324, "text": "Java" }, { "code": "// The app will show Algorithms Sub-List// every time the activity startsalgorithmTitleText.setText(\"Algorithms\");setRVTwoList(1);", "e": 53460, "s": 53329, "text": null }, { "code": null, "e": 53480, "s": 53462, "text": "MainActivity.java" }, { "code": null, "e": 53485, "s": 53480, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import android.widget.LinearLayout;import android.widget.TextView;import com.wheic.recyclergetsout.RV1.RVOneAdapter;import com.wheic.recyclergetsout.RV1.RVOneModel;import com.wheic.recyclergetsout.RV2.RVTwoAdapter;import com.wheic.recyclergetsout.RV2.RVTwoModel;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // reference for the Main-List RecyclerView private RecyclerView RVOne; // reference for the Sub-List RecyclerView private RecyclerView RVTwo; // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // Sub-list item titles will be stored here private List<RVTwoModel> tutorialSubList; // reference for the RVOneAdapter class private RVOneAdapter rvOneAdapter; // reference for the RVTwoAdapter class private RVTwoAdapter rvTwoAdapter; // TextView to show the title of the clicked Main-List item private TextView algorithmTitleText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Linked up with its respective id used in the activity_main.xml RVOne = findViewById(R.id.recyclerViewOne); RVTwo = findViewById(R.id.recyclerViewTwo); algorithmTitleText = findViewById(R.id.algorithmTitleText); // Setting the Main-List RecyclerView horizontally RVOne.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false)); tutorialList = new ArrayList<>(); // Static data are stored one by one in the tutorialList arrayList tutorialList.add(new RVOneModel(\"Algorithms\", 1)); tutorialList.add(new RVOneModel(\"Data Structures\", 2)); tutorialList.add(new RVOneModel(\"Languages\", 3)); tutorialList.add(new RVOneModel(\"Interview Corner\", 4)); tutorialList.add(new RVOneModel(\"GATE\", 5)); tutorialList.add(new RVOneModel(\"ISRO CS\", 6)); tutorialList.add(new RVOneModel(\"UGC NET CS\", 7)); tutorialList.add(new RVOneModel(\"CS Subjects\", 8)); tutorialList.add(new RVOneModel(\"Web Technologies\", 9)); // The app will show Algorithms Sub-List every time the activity starts algorithmTitleText.setText(\"Algorithms\"); setRVTwoList(1); rvOneAdapter = new RVOneAdapter(tutorialList); RVOne.setAdapter(rvOneAdapter); // Setting up the events that will occur on each Main-List item click rvOneAdapter.setWhenClickListener(new RVOneAdapter.OnItemsClickListener() { @Override public void onItemClick(RVOneModel rvOneModel) { algorithmTitleText.setText(rvOneModel.getName()); setRVTwoList(rvOneModel.getNum()); } }); } private void setRVTwoList(int num){ // Setting the Sub-List RecyclerView vertically RVTwo.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); // Previous tutorialSubList will be deleted and new memory will be allocated tutorialSubList = new ArrayList<>(); // Static data are stored one by one in the tutorialSubList arrayList for each Main-List items if (num == 1) { tutorialSubList.add(new RVTwoModel(\"Searching Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Sorting Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Graph Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Pattern Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Geometric Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Mathematical\")); tutorialSubList.add(new RVTwoModel(\"Randomized Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Greedy Algorithms\")); tutorialSubList.add(new RVTwoModel(\"Dynamic Programming\")); tutorialSubList.add(new RVTwoModel(\"Divide and Conquer\")); tutorialSubList.add(new RVTwoModel(\"Backtracking\")); tutorialSubList.add(new RVTwoModel(\"Branch and Bound\")); tutorialSubList.add(new RVTwoModel(\"All Algorithms\")); } else if (num == 2){ tutorialSubList.add(new RVTwoModel(\"Arrays\")); tutorialSubList.add(new RVTwoModel(\"Linked List\")); tutorialSubList.add(new RVTwoModel(\"Stack\")); tutorialSubList.add(new RVTwoModel(\"Queue\")); tutorialSubList.add(new RVTwoModel(\"Binary Tree\")); tutorialSubList.add(new RVTwoModel(\"Binary Search Tree\")); tutorialSubList.add(new RVTwoModel(\"Heap\")); tutorialSubList.add(new RVTwoModel(\"Hashing\")); tutorialSubList.add(new RVTwoModel(\"Graph\")); tutorialSubList.add(new RVTwoModel(\"Advanced Data Structure\")); tutorialSubList.add(new RVTwoModel(\"Matrix\")); tutorialSubList.add(new RVTwoModel(\"Strings\")); tutorialSubList.add(new RVTwoModel(\"All Data Structures\")); } else if (num == 3){ tutorialSubList.add(new RVTwoModel(\"C\")); tutorialSubList.add(new RVTwoModel(\"C++\")); tutorialSubList.add(new RVTwoModel(\"Java\")); tutorialSubList.add(new RVTwoModel(\"Python\")); tutorialSubList.add(new RVTwoModel(\"C#\")); tutorialSubList.add(new RVTwoModel(\"Javascript\")); tutorialSubList.add(new RVTwoModel(\"JQuery\")); tutorialSubList.add(new RVTwoModel(\"SQL\")); tutorialSubList.add(new RVTwoModel(\"PHP\")); tutorialSubList.add(new RVTwoModel(\"Scala\")); tutorialSubList.add(new RVTwoModel(\"Perl\")); tutorialSubList.add(new RVTwoModel(\"GO Language\")); tutorialSubList.add(new RVTwoModel(\"HTML\")); tutorialSubList.add(new RVTwoModel(\"CSS\")); tutorialSubList.add(new RVTwoModel(\"Kotlin\")); } else if (num == 4){ tutorialSubList.add(new RVTwoModel(\"Company Preparation\")); tutorialSubList.add(new RVTwoModel(\"Top Topics\")); tutorialSubList.add(new RVTwoModel(\"Practice Company Questions\")); tutorialSubList.add(new RVTwoModel(\"Interview Experiences\")); tutorialSubList.add(new RVTwoModel(\"Experienced Interviews\")); tutorialSubList.add(new RVTwoModel(\"Internship Interviews\")); tutorialSubList.add(new RVTwoModel(\"Competitive Programming\")); tutorialSubList.add(new RVTwoModel(\"Design Patterns\")); tutorialSubList.add(new RVTwoModel(\"Multiple Choice Quizzes\")); } else if (num == 5){ tutorialSubList.add(new RVTwoModel(\"GATE CS Notes 2021\")); tutorialSubList.add(new RVTwoModel(\"Last Minute Notes\")); tutorialSubList.add(new RVTwoModel(\"GATE CS Solved Papers\")); tutorialSubList.add(new RVTwoModel(\"GATE CS Original Papers and Official Keys\")); tutorialSubList.add(new RVTwoModel(\"GATE 2021 Dates\")); tutorialSubList.add(new RVTwoModel(\"GATE CS 2021 Syllabus\")); tutorialSubList.add(new RVTwoModel(\"Important Topics for GATE CS\")); tutorialSubList.add(new RVTwoModel(\"Sudo GATE 2021\")); } else if (num == 6){ tutorialSubList.add(new RVTwoModel(\"ISRO CS Solved Papers\")); tutorialSubList.add(new RVTwoModel(\"ISRO CS Original Papers and Official Keys\")); tutorialSubList.add(new RVTwoModel(\"ISRO CS Syllabus for Scientist/Engineer Exam\")); } else if (num == 7){ tutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper II\")); tutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper III\")); tutorialSubList.add(new RVTwoModel(\"UGC NET CS Solved Papers\")); } else if (num == 8){ tutorialSubList.add(new RVTwoModel(\"Mathematics\")); tutorialSubList.add(new RVTwoModel(\"Operating System\")); tutorialSubList.add(new RVTwoModel(\"DBMS\")); tutorialSubList.add(new RVTwoModel(\"Computer Networks\")); tutorialSubList.add(new RVTwoModel(\"Computer Organization and Architecture\")); tutorialSubList.add(new RVTwoModel(\"Theory of Computation\")); tutorialSubList.add(new RVTwoModel(\"Compiler Design\")); tutorialSubList.add(new RVTwoModel(\"Digital Logic\")); tutorialSubList.add(new RVTwoModel(\"Software Engineering\")); } else if (num == 9){ tutorialSubList.add(new RVTwoModel(\"HTML\")); tutorialSubList.add(new RVTwoModel(\"CSS\")); tutorialSubList.add(new RVTwoModel(\"Javascript\")); tutorialSubList.add(new RVTwoModel(\"jQuery\")); tutorialSubList.add(new RVTwoModel(\"PHP\")); } rvTwoAdapter = new RVTwoAdapter(tutorialSubList); RVTwo.setAdapter(rvTwoAdapter); }}", "e": 62573, "s": 53485, "text": null }, { "code": null, "e": 62593, "s": 62575, "text": "RVOneAdapter.java" }, { "code": null, "e": 62598, "s": 62593, "text": "Java" }, { "code": "import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.cardview.widget.CardView;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVOneAdapter extends RecyclerView.Adapter<RVOneAdapter.ViewHolder> { // Main-list item titles will be stored here private List<RVOneModel> tutorialList; // Need this clickListener for the Main-list item onClick events private OnItemsClickListener listener; // Parameterized constructor of this class to initialize tutorialList public RVOneAdapter(List<RVOneModel> tutorialList) { this.tutorialList = tutorialList; } // Main-list item clickListener is initialized // This will be used in MainActivity public void setWhenClickListener(OnItemsClickListener listener){ this.listener = listener; } // Attach the item layout with the proper xml file @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final RVOneModel modelItems = tutorialList.get(position); holder.setData(tutorialList.get(position).getName()); holder.singleItemCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener != null){ listener.onItemClick(modelItems); } } }); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public CardView singleItemCardView; public TextView singleItemTextView; // Link up the Main-List items layout components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); singleItemCardView = itemView.findViewById(R.id.singleItemCardView); singleItemTextView = itemView.findViewById(R.id.singleItemTextView); } // setText in Main-List title text public void setData(String name){ this.singleItemTextView.setText(name); } } // Interface to perform events on Main-List item click public interface OnItemsClickListener{ void onItemClick(RVOneModel rvOneModel); }}", "e": 65456, "s": 62598, "text": null }, { "code": null, "e": 65474, "s": 65458, "text": "RVOneModel.java" }, { "code": null, "e": 65479, "s": 65474, "text": "Java" }, { "code": "public class RVOneModel { // this variable will store main-list item title private String name; // this will help differentiate between the main-list items private int num; // parameterized constructor public RVOneModel(String name, int num) { this.name = name; this.num = num; } // getter functions for these two variables public String getName() { return name; } public int getNum() { return num; }}", "e": 65957, "s": 65479, "text": null }, { "code": null, "e": 65977, "s": 65959, "text": "RVTwoAdapter.java" }, { "code": null, "e": 65982, "s": 65977, "text": "Java" }, { "code": "import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.wheic.recyclergetsout.R;import java.util.List; public class RVTwoAdapter extends RecyclerView.Adapter<RVTwoAdapter.ViewHolder> { // Sub-list item titles will be stored here private List<RVTwoModel> tutorialSubList; // Parameterized constructor of this // class to initialize tutorialSubList public RVTwoAdapter(List<RVTwoModel> tutorialSubList) { this.tutorialSubList = tutorialSubList; } // Attach the item layout with the proper xml file @NonNull @Override public RVTwoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout_vertical, parent, false); return new ViewHolder(view); } // It deals with the setting of different data and methods @Override public void onBindViewHolder(@NonNull RVTwoAdapter.ViewHolder holder, int position) { holder.setData(tutorialSubList.get(position).getName()); } // It returns the length of the RecyclerView @Override public int getItemCount() { return tutorialSubList.size(); } // The ViewHolder is a java class that stores // the reference to the item layout views public class ViewHolder extends RecyclerView.ViewHolder{ public TextView rvTwoText; // Link up the Sub-List items layout components with their respective id public ViewHolder(@NonNull View itemView) { super(itemView); rvTwoText = itemView.findViewById(R.id.singleItemTextViewRVTwo); } // setText in Sub-List title text public void setData(String name){ this.rvTwoText.setText(name); } }}", "e": 67916, "s": 65982, "text": null }, { "code": null, "e": 67934, "s": 67918, "text": "RVTwoModel.java" }, { "code": null, "e": 67939, "s": 67934, "text": "Java" }, { "code": "public class RVTwoModel { // this variable will store sub-list item title private String name; // parameterized constructor public RVTwoModel(String name) { this.name = name; } // getter function for the name variable public String getName() { return name; }}", "e": 68244, "s": 67939, "text": null }, { "code": null, "e": 68294, "s": 68244, "text": "You can check this project from this GitHub link." }, { "code": null, "e": 68302, "s": 68294, "text": "android" }, { "code": null, "e": 68326, "s": 68302, "text": "Technical Scripter 2020" }, { "code": null, "e": 68334, "s": 68326, "text": "Android" }, { "code": null, "e": 68339, "s": 68334, "text": "Java" }, { "code": null, "e": 68358, "s": 68339, "text": "Technical Scripter" }, { "code": null, "e": 68363, "s": 68358, "text": "Java" }, { "code": null, "e": 68371, "s": 68363, "text": "Android" }, { "code": null, "e": 68469, "s": 68371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 68478, "s": 68469, "text": "Comments" }, { "code": null, "e": 68491, "s": 68478, "text": "Old Comments" }, { "code": null, "e": 68533, "s": 68491, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 68572, "s": 68533, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 68622, "s": 68572, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 68673, "s": 68622, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 68711, "s": 68673, "text": "Android Listview in Java with Example" }, { "code": null, "e": 68726, "s": 68711, "text": "Arrays in Java" }, { "code": null, "e": 68770, "s": 68726, "text": "Split() String method in Java with examples" }, { "code": null, "e": 68792, "s": 68770, "text": "For-each loop in Java" }, { "code": null, "e": 68817, "s": 68792, "text": "Reverse a string in Java" } ]
Java Collection | Set 1 (ArrayList) Part-2 | Practice | GeeksforGeeks
Implement different operations on a ArrayList A . Input: The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries . A query can be of five types 1. a x (Adds an element x to the ArrayList A at the end ) 2. b (Sorts the ArrayList A in ascending order ) 3. c (Reverses the ArrayList A) 4. d (prints the size of the ArrayList) 5. e (prints space separated values of the ArrayList) 5. f (Sorts the ArrayList A in descending order) Output: The output for each test case will be space separated integers denoting the results of each query . Constraints: 1<=T<=100 1<=Q<=100 Example: Input 2 6 a 4 a 6 a 7 b c e 4 a 55 a 11 d e Output 7 6 4 2 55 11 Explanation : For the first test case There are six queries. Queries are performed in this order 1. a 4 { ArrayList has 4 } 2. a 7 {ArrayList has 7 } 3. a 6 {ArrayList has 6} 4. b {sorts the ArrayList in ascending order, ArrayList now is 5 6 7} 5. c {reverse the ArrayList} 6. e {prints the element of the ArrayList 7 6 4} For the sec test case There are four queries. Queries are performed in this order 1. a 55 (ArrayList A has 55} 2. a 11 (ArrayList A has 55 ,11} 3. d (prints the size of the ArrayList A ie. 2 ) 4. e (prints the elements of the ArrayList A ie 55 11) Note:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 mda976714 months ago class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<Integer> A, int x) {// Your code here A.add(x); } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<Integer> A) {// Your code here Collections.sort(A); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<Integer> A) {// Your code hereCollections.reverse(A); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<Integer> A) {// Your code here return A.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<Integer> A) {// Your code here Collections.sort(A,Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<Integer> A) { // Your code here for(Integer x:A) { System.out.print(x+" "); } }} +1 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.32 class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) { A.add(x); } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) { Collections.sort(A); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) { Collections.reverse(A); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) { return A.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) { Collections.sort(A, Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for(Integer x: A) { System.out.print(x + " "); } }} +1 Amir Ansari1 year ago Amir Ansari Correct AnswerExecution Time:0.31 class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) {// Your code here A.add(x); } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) {// Your code here Collections.sort(A); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) {// Your code hereCollections.reverse(A); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {// Your code here return A.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) {// Your code here Collections.sort(A,Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { // Your code here for(int i = 0 ;i < A.size();i++){ System.out.print(A.get(i) +" "); } }} 0 Shreya Patil2 years ago Shreya Patil class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) {// Your code here A.add(x); } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) {// Your code here Collections.sort(A); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) { Collections.reverse(A); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {// Your code here return A.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) {// Your code here Collections.sort(A,Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { // Your code here for(int i=0;i<a.size();i++) system.out.print(a.get(i)+"="" ");="" }="" }="" <code=""> 0 Pratikshya Mishra2 years ago Pratikshya Mishra // { Driver Code Startsimport java.util.Scanner;import java.util.*; class ArrayList_Collection{public static void main(String args[]){Scanner sc = new Scanner(System.in);int T = sc.nextInt();while(T>0){ArrayList<integer> A = new ArrayList<integer>();int q = sc.nextInt(); while(q>0){char c = sc.next().charAt(0);GfG g = new GfG();if(c == 'a'){int x = sc.nextInt();g.add_to_ArrayList(A,x);} if(c == 'b')g.sort_ArrayList_Asc(A); if(c == 'c')g.reverse_ArrayList(A); if(c == 'd')System.out.print(g.size_Of_ArrayList(A)+" "); if(c == 'e')g.print_ArrayList(A); if(c == 'f')g.sort_ArrayList_Desc(A); q--;}T--;System.out.println();}}}// } Driver Code Ends /*You are required to complete below methods*/ class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) { A.add(x);// Your code here } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) { Collections.sort(A);// Your code here } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) { Collections.reverse(A);// Your code here } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) { return A.size();// Your code here } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) { Collections.sort(A,Collections.reverseOrder());// Your code here } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for(int i=0;i<a.size();i++) {="" system.out.println(a.get(i)+"="" ");="" }="" your="" code="" here="" }="" }=""> 0 Vikram Shekhawat2 years ago Vikram Shekhawat /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) {A.add(x); } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) {Collections.sort(A); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) {Collections.reverse(A); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {return A.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) {Collections.sort(A, Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for (int i = 0; i < A.size();i++) { System.out.print(A.get(i)+" "); } }} 0 kaushar fatima3 years ago kaushar fatima https://ide.geeksforgeeks.o... only first element is being displayed 0 rishi pandey3 years ago rishi pandey https://ide.geeksforgeeks.o... tell me what is wrong 0 LAMIAZOHRA MIHOUBI4 years ago LAMIAZOHRA MIHOUBI hi guys my code (here: https://practice.geeksforge... is failing at a certain input but I just don't understand why, can anybody help please?here's the input:138a 50 a 277 c c a 404 f c b a 61 c a 740 e e a 95 f d e c e f d f c d a 653 c b c c b d f e f e d d band here's the expected output:61 404 277 50 740 61 404 277 50 740 6 740 404 277 95 61 50 50 61 95 277 404 740 6 6 7 740 653 404 277 95 61 50 740 653 404 277 95 61 50 7 7and here's my output:61 277 404 50 740 61 277 404 50 740 6 740 404 277 95 61 50 50 740 277 95 61 404 6 6 7 740 653 404 277 95 61 50 740 653 404 277 95 61 50 7 7 0 Chaitanya Stndt5 years ago Chaitanya Stndt working perfect in eclipse ide:but i having this problemRun Time ErrorException in thread "main" java.util.NoSuchElementExceptionat java.util.Scanner.throwFor(Scanner.java:862)at java.util.Scanner.next(Scanner.java:1485)at java.util.Scanner.nextInt(Scanner.java:2117)at java.util.Scanner.nextInt(Scanner.java:2076)at GfG.<init>(GfG.java:90)at ArrayList_Collection.main(GfG.java:18) and my code is/*You are required to complete below methods*/ public class GfG {ArrayList<integer> ar = new ArrayList<>();Scanner s = new Scanner(System.in);void add_to_ArrayList(ArrayList<integer> A, int x) {ar.add(x); } void sort_ArrayList_Asc(ArrayList<integer> A) {Collections.sort(ar); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) {Collections.reverse(ar); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {return ar.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) { Collections.sort(ar, Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for (Integer pro : ar) {pro.toString();} } int t =s.nextInt();{//System.out.println("enter queries");for(int i=0; i<t;i++){ int="" q="s.nextInt();" for="" (int="" j="0;" j="" <="" q;="" j++)="" {="" system.out.println("enter="" string");="" string="" choice="s.next();" if(choice.equals("a")){="" system.out.println("enter="" integer");="" int="" n="s.nextInt();" add_to_arraylist(ar,="" n);="" }="" else="" if="" (choice.equals("b"))="" {="" sort_arraylist_asc(ar);="" }="" else="" if="" (choice.equals("c"))="" {="" reverse_arraylist(ar);="" }="" else="" if="" (choice.equals("d"))="" {="" size_of_arraylist(ar);="" }="" else="" if="" (choice.equals("e"))="" {="" print_arraylist(ar);="" }="" else="" if="" (choice.equals("f"))="" {="" sort_arraylist_desc(ar);="" }="" }="" }="" }="" }=""> We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 278, "s": 226, "text": "Implement different operations on a ArrayList A .\n " }, { "code": null, "e": 987, "s": 278, "text": "Input:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .\nA query can be of five types \n1. a x (Adds an element x to the ArrayList A at the end )\n2. b (Sorts the ArrayList A in ascending order )\n3. c (Reverses the ArrayList A)\n4. d (prints the size of the ArrayList)\n5. e (prints space separated values of the ArrayList)\n5. f (Sorts the ArrayList A in descending order)\n\n\nOutput:\nThe output for each test case will be space separated integers denoting the results of each query . \n\nConstraints:\n1<=T<=100\n1<=Q<=100\n\nExample:" }, { "code": null, "e": 1953, "s": 987, "text": "Input\n2\n6\na 4 a 6 a 7 b c e\n4\na 55 a 11 d e\n \nOutput\n7 6 4\n2 55 11\n\nExplanation :\nFor the first test case\nThere are six queries. Queries are performed in this order\n1. a 4 { ArrayList has 4 }\n2. a 7 {ArrayList has 7 }\n3. a 6 {ArrayList has 6}\n4. b {sorts the ArrayList in ascending order, ArrayList now is 5 6 7}\n5. c {reverse the ArrayList}\n6. e {prints the element of the ArrayList 7 6 4}\n\nFor the sec test case \nThere are four queries. Queries are performed in this order\n1. a 55 (ArrayList A has 55}\n2. a 11 (ArrayList A has 55 ,11}\n3. d (prints the size of the ArrayList A ie. 2 )\n4. e (prints the elements of the ArrayList A ie 55 11)\n\n\nNote:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1957, "s": 1955, "text": "0" }, { "code": null, "e": 1978, "s": 1957, "text": "mda976714 months ago" }, { "code": null, "e": 2930, "s": 1978, "text": "class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<Integer> A, int x) {// Your code here A.add(x); } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<Integer> A) {// Your code here Collections.sort(A); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<Integer> A) {// Your code hereCollections.reverse(A); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<Integer> A) {// Your code here return A.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<Integer> A) {// Your code here Collections.sort(A,Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<Integer> A) { // Your code here for(Integer x:A) { System.out.print(x+\" \"); } }} " }, { "code": null, "e": 2933, "s": 2930, "text": "+1" }, { "code": null, "e": 2959, "s": 2933, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 2975, "s": 2959, "text": "Debojyoti Sinha" }, { "code": null, "e": 3024, "s": 2975, "text": "Correct Answer.Correct AnswerExecution Time:0.32" }, { "code": null, "e": 3921, "s": 3024, "text": "class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) { A.add(x); } /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) { Collections.sort(A); } /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) { Collections.reverse(A); } /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) { return A.size(); } /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) { Collections.sort(A, Collections.reverseOrder()); } /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for(Integer x: A) { System.out.print(x + \" \"); } }}" }, { "code": null, "e": 3924, "s": 3921, "text": "+1" }, { "code": null, "e": 3946, "s": 3924, "text": "Amir Ansari1 year ago" }, { "code": null, "e": 3958, "s": 3946, "text": "Amir Ansari" }, { "code": null, "e": 3992, "s": 3958, "text": "Correct AnswerExecution Time:0.31" }, { "code": null, "e": 4160, "s": 3992, "text": "class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) {// Your code here A.add(x); }" }, { "code": null, "e": 4306, "s": 4160, "text": " /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) {// Your code here Collections.sort(A); }" }, { "code": null, "e": 4437, "s": 4306, "text": " /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) {// Your code hereCollections.reverse(A); }" }, { "code": null, "e": 4575, "s": 4437, "text": " /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {// Your code here return A.size(); }" }, { "code": null, "e": 4750, "s": 4575, "text": " /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) {// Your code here Collections.sort(A,Collections.reverseOrder()); }" }, { "code": null, "e": 4985, "s": 4750, "text": " /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { // Your code here for(int i = 0 ;i < A.size();i++){ System.out.print(A.get(i) +\" \"); } }}" }, { "code": null, "e": 4987, "s": 4985, "text": "0" }, { "code": null, "e": 5011, "s": 4987, "text": "Shreya Patil2 years ago" }, { "code": null, "e": 5024, "s": 5011, "text": "Shreya Patil" }, { "code": null, "e": 5193, "s": 5024, "text": "class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) {// Your code here A.add(x); }" }, { "code": null, "e": 5341, "s": 5193, "text": " /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) {// Your code here Collections.sort(A); }" }, { "code": null, "e": 5463, "s": 5341, "text": " /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) { Collections.reverse(A); }" }, { "code": null, "e": 5602, "s": 5463, "text": " /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {// Your code here return A.size(); }" }, { "code": null, "e": 5780, "s": 5602, "text": " /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) {// Your code here Collections.sort(A,Collections.reverseOrder()); }" }, { "code": null, "e": 6008, "s": 5780, "text": " /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { // Your code here for(int i=0;i<a.size();i++) system.out.print(a.get(i)+\"=\"\" \");=\"\" }=\"\" }=\"\" <code=\"\">" }, { "code": null, "e": 6010, "s": 6008, "text": "0" }, { "code": null, "e": 6039, "s": 6010, "text": "Pratikshya Mishra2 years ago" }, { "code": null, "e": 6057, "s": 6039, "text": "Pratikshya Mishra" }, { "code": null, "e": 6125, "s": 6057, "text": "// { Driver Code Startsimport java.util.Scanner;import java.util.*;" }, { "code": null, "e": 6329, "s": 6125, "text": "class ArrayList_Collection{public static void main(String args[]){Scanner sc = new Scanner(System.in);int T = sc.nextInt();while(T>0){ArrayList<integer> A = new ArrayList<integer>();int q = sc.nextInt();" }, { "code": null, "e": 6447, "s": 6329, "text": "while(q>0){char c = sc.next().charAt(0);GfG g = new GfG();if(c == 'a'){int x = sc.nextInt();g.add_to_ArrayList(A,x);}" }, { "code": null, "e": 6484, "s": 6447, "text": "if(c == 'b')g.sort_ArrayList_Asc(A);" }, { "code": null, "e": 6520, "s": 6484, "text": "if(c == 'c')g.reverse_ArrayList(A);" }, { "code": null, "e": 6578, "s": 6520, "text": "if(c == 'd')System.out.print(g.size_Of_ArrayList(A)+\" \");" }, { "code": null, "e": 6612, "s": 6578, "text": "if(c == 'e')g.print_ArrayList(A);" }, { "code": null, "e": 6650, "s": 6612, "text": "if(c == 'f')g.sort_ArrayList_Desc(A);" }, { "code": null, "e": 6705, "s": 6650, "text": "q--;}T--;System.out.println();}}}// } Driver Code Ends" }, { "code": null, "e": 6752, "s": 6705, "text": "/*You are required to complete below methods*/" }, { "code": null, "e": 6925, "s": 6752, "text": "class GfG{ /*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) { A.add(x);// Your code here }" }, { "code": null, "e": 7077, "s": 6925, "text": " /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) { Collections.sort(A);// Your code here }" }, { "code": null, "e": 7216, "s": 7077, "text": " /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) { Collections.reverse(A);// Your code here }" }, { "code": null, "e": 7359, "s": 7216, "text": " /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) { return A.size();// Your code here }" }, { "code": null, "e": 7541, "s": 7359, "text": " /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) { Collections.sort(A,Collections.reverseOrder());// Your code here }" }, { "code": null, "e": 7772, "s": 7541, "text": " /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for(int i=0;i<a.size();i++) {=\"\" system.out.println(a.get(i)+\"=\"\" \");=\"\" }=\"\" your=\"\" code=\"\" here=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 7774, "s": 7772, "text": "0" }, { "code": null, "e": 7802, "s": 7774, "text": "Vikram Shekhawat2 years ago" }, { "code": null, "e": 7819, "s": 7802, "text": "Vikram Shekhawat" }, { "code": null, "e": 7953, "s": 7819, "text": "/*inserts an element x at the back of the ArrayList A */ void add_to_ArrayList(ArrayList<integer> A, int x) {A.add(x); }" }, { "code": null, "e": 8080, "s": 7953, "text": " /*sort the ArrayList A in ascending order*/ void sort_ArrayList_Asc(ArrayList<integer> A) {Collections.sort(A); }" }, { "code": null, "e": 8194, "s": 8080, "text": " /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) {Collections.reverse(A); }" }, { "code": null, "e": 8312, "s": 8194, "text": " /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {return A.size(); }" }, { "code": null, "e": 8470, "s": 8312, "text": " /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) {Collections.sort(A, Collections.reverseOrder()); }" }, { "code": null, "e": 8693, "s": 8470, "text": " /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for (int i = 0; i < A.size();i++) { System.out.print(A.get(i)+\" \"); } }}" }, { "code": null, "e": 8695, "s": 8693, "text": "0" }, { "code": null, "e": 8721, "s": 8695, "text": "kaushar fatima3 years ago" }, { "code": null, "e": 8736, "s": 8721, "text": "kaushar fatima" }, { "code": null, "e": 8805, "s": 8736, "text": "https://ide.geeksforgeeks.o... only first element is being displayed" }, { "code": null, "e": 8807, "s": 8805, "text": "0" }, { "code": null, "e": 8831, "s": 8807, "text": "rishi pandey3 years ago" }, { "code": null, "e": 8844, "s": 8831, "text": "rishi pandey" }, { "code": null, "e": 8897, "s": 8844, "text": "https://ide.geeksforgeeks.o... tell me what is wrong" }, { "code": null, "e": 8899, "s": 8897, "text": "0" }, { "code": null, "e": 8929, "s": 8899, "text": "LAMIAZOHRA MIHOUBI4 years ago" }, { "code": null, "e": 8948, "s": 8929, "text": "LAMIAZOHRA MIHOUBI" }, { "code": null, "e": 9540, "s": 8948, "text": "hi guys my code (here: https://practice.geeksforge... is failing at a certain input but I just don't understand why, can anybody help please?here's the input:138a 50 a 277 c c a 404 f c b a 61 c a 740 e e a 95 f d e c e f d f c d a 653 c b c c b d f e f e d d band here's the expected output:61 404 277 50 740 61 404 277 50 740 6 740 404 277 95 61 50 50 61 95 277 404 740 6 6 7 740 653 404 277 95 61 50 740 653 404 277 95 61 50 7 7and here's my output:61 277 404 50 740 61 277 404 50 740 6 740 404 277 95 61 50 50 740 277 95 61 404 6 6 7 740 653 404 277 95 61 50 740 653 404 277 95 61 50 7 7" }, { "code": null, "e": 9542, "s": 9540, "text": "0" }, { "code": null, "e": 9569, "s": 9542, "text": "Chaitanya Stndt5 years ago" }, { "code": null, "e": 9585, "s": 9569, "text": "Chaitanya Stndt" }, { "code": null, "e": 9967, "s": 9585, "text": "working perfect in eclipse ide:but i having this problemRun Time ErrorException in thread \"main\" java.util.NoSuchElementExceptionat java.util.Scanner.throwFor(Scanner.java:862)at java.util.Scanner.next(Scanner.java:1485)at java.util.Scanner.nextInt(Scanner.java:2117)at java.util.Scanner.nextInt(Scanner.java:2076)at GfG.<init>(GfG.java:90)at ArrayList_Collection.main(GfG.java:18)" }, { "code": null, "e": 10028, "s": 9967, "text": "and my code is/*You are required to complete below methods*/" }, { "code": null, "e": 10194, "s": 10028, "text": "public class GfG {ArrayList<integer> ar = new ArrayList<>();Scanner s = new Scanner(System.in);void add_to_ArrayList(ArrayList<integer> A, int x) {ar.add(x); }" }, { "code": null, "e": 10271, "s": 10194, "text": "void sort_ArrayList_Asc(ArrayList<integer> A) {Collections.sort(ar); }" }, { "code": null, "e": 10386, "s": 10271, "text": " /*reverses the ArrayList A*/ void reverse_ArrayList(ArrayList<integer> A) {Collections.reverse(ar); }" }, { "code": null, "e": 10505, "s": 10386, "text": " /*returns the size of the ArrayList A */ int size_Of_ArrayList(ArrayList<integer> A) {return ar.size(); }" }, { "code": null, "e": 10668, "s": 10505, "text": " /*sorts the ArrayList A in descending order*/ void sort_ArrayList_Desc(ArrayList<integer> A) { Collections.sort(ar, Collections.reverseOrder()); }" }, { "code": null, "e": 10827, "s": 10668, "text": " /*prints space separated elements of ArrayList A*/ void print_ArrayList(ArrayList<integer> A) { for (Integer pro : ar) {pro.toString();} }" }, { "code": null, "e": 11576, "s": 10827, "text": "int t =s.nextInt();{//System.out.println(\"enter queries\");for(int i=0; i<t;i++){ int=\"\" q=\"s.nextInt();\" for=\"\" (int=\"\" j=\"0;\" j=\"\" <=\"\" q;=\"\" j++)=\"\" {=\"\" system.out.println(\"enter=\"\" string\");=\"\" string=\"\" choice=\"s.next();\" if(choice.equals(\"a\")){=\"\" system.out.println(\"enter=\"\" integer\");=\"\" int=\"\" n=\"s.nextInt();\" add_to_arraylist(ar,=\"\" n);=\"\" }=\"\" else=\"\" if=\"\" (choice.equals(\"b\"))=\"\" {=\"\" sort_arraylist_asc(ar);=\"\" }=\"\" else=\"\" if=\"\" (choice.equals(\"c\"))=\"\" {=\"\" reverse_arraylist(ar);=\"\" }=\"\" else=\"\" if=\"\" (choice.equals(\"d\"))=\"\" {=\"\" size_of_arraylist(ar);=\"\" }=\"\" else=\"\" if=\"\" (choice.equals(\"e\"))=\"\" {=\"\" print_arraylist(ar);=\"\" }=\"\" else=\"\" if=\"\" (choice.equals(\"f\"))=\"\" {=\"\" sort_arraylist_desc(ar);=\"\" }=\"\" }=\"\" }=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 11722, "s": 11576, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 11758, "s": 11722, "text": " Login to access your submissions. " }, { "code": null, "e": 11768, "s": 11758, "text": "\nProblem\n" }, { "code": null, "e": 11778, "s": 11768, "text": "\nContest\n" }, { "code": null, "e": 11841, "s": 11778, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11989, "s": 11841, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 12197, "s": 11989, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 12303, "s": 12197, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Deploy Flask API to Google Cloud | Towards Data Science
Building that first API is for many of us, a significant step towards creating impactful tools that may one day be used by many developers. But often those APIs don’t make it out of our local machines. Fortunately, it’s incredibly easy to deploy APIs. Assuming you have no idea what you’re doing right now — you will probably be deploying your first API in around ten minutes. I’m not joking, it’s super easy. Let’s get started. There are a couple of prerequisites. These might push you over the ten-minute mark slightly, but it won’t take long I promise! We’re going to be deploying our API using Google’s cloud service, or Google Cloud Platform (GCP). You will need to enter billing details, but if this is your first time on GCP you will be given a few hundred 💲 worth of free credits. If you want to avoid any billing, make sure that you delete your project after you’ve finished with it. Sign up for GCP and select/create a project — keep a note of the project name.Enable billingEnable the Cloud Build API.Install and initialize the Cloud SDK. Sign up for GCP and select/create a project — keep a note of the project name. Enable billing Enable the Cloud Build API. Install and initialize the Cloud SDK. After initialization, you may need to select the project that you previously created. We will be using the GCP App Engine service to deploy our Flask API. To use this we will need to add App Engine to our chosen project, and then install the App Engine extension for Python. From inside your chosen prompt window, we create a new App Engine app using the project name (using your project name) and choose a region. gcloud app create --project=aurelio-330516 Then we install the App Engine extension for Python with: gcloud components install app-engine-python We now have all of the prerequisites required for deploying our API to GCP’s App Engine. Let’s move on to the Flask API itself. Before blindly throwing our API python script at GCP’s App Engine and hoping for the best — we should confirm that it works. We can do this by simulating the App Engine environment, but first — we need an API. I will be using this API script. It doesn’t do anything particularly interesting, but it is simple and therefore useful for our example. You can see how I built it here. Alongside the API script main.py — you will also need to include a ./data directory that contains the two files users.csv and locations.csv. Altogether this means we have a single directory that looks like this: Back to simulation. To simulate the App Engine environment we will be using gunicorn to run a local Web Server Gateway Interface (WSGI) server. Before this, you may need to pip install gunicorn — then, in the same environment, we run the API: Then we can head on over to http://0.0.0.0:8080/users. If the API is running as expected we should see a small JSON response that looks like this: Gunicorn is using our Python environment — so the libraries we’re importing at the top of our main.py script are already installed. And we also know that we’re using (in my case) Python 3.8. This is a problem when we deploy the API to GCP. App Engine will have no idea that we need to use these packages nor that we’re using Python 3.8. So we must add two more files to our directory: requirements.txt will contain a list of the Python packages for App Engine to install. app.yaml will set the runtime to use Python 3.8. These files will look like this: And that’s all we need. Now we deploy by running gcloud app deploy inside the directory containing all of our files. This will take a moment to deploy, after which we should see the URL of our deployed API! Heading over to that URL followed by the /users endpoint will return us the same JSON object we saw earlier: This means our API is up and running and we can go ahead and make requests as we would with any other API! That’s all for this quick walkthrough for deploying Flask APIs using GCP’s App Engine. I hope you enjoyed it! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too. Thanks for reading! 🤖 70% Discount on the NLP With Transformers Course *All images are by the author except where stated otherwise
[ { "code": null, "e": 373, "s": 171, "text": "Building that first API is for many of us, a significant step towards creating impactful tools that may one day be used by many developers. But often those APIs don’t make it out of our local machines." }, { "code": null, "e": 548, "s": 373, "text": "Fortunately, it’s incredibly easy to deploy APIs. Assuming you have no idea what you’re doing right now — you will probably be deploying your first API in around ten minutes." }, { "code": null, "e": 600, "s": 548, "text": "I’m not joking, it’s super easy. Let’s get started." }, { "code": null, "e": 825, "s": 600, "text": "There are a couple of prerequisites. These might push you over the ten-minute mark slightly, but it won’t take long I promise! We’re going to be deploying our API using Google’s cloud service, or Google Cloud Platform (GCP)." }, { "code": null, "e": 1064, "s": 825, "text": "You will need to enter billing details, but if this is your first time on GCP you will be given a few hundred 💲 worth of free credits. If you want to avoid any billing, make sure that you delete your project after you’ve finished with it." }, { "code": null, "e": 1221, "s": 1064, "text": "Sign up for GCP and select/create a project — keep a note of the project name.Enable billingEnable the Cloud Build API.Install and initialize the Cloud SDK." }, { "code": null, "e": 1300, "s": 1221, "text": "Sign up for GCP and select/create a project — keep a note of the project name." }, { "code": null, "e": 1315, "s": 1300, "text": "Enable billing" }, { "code": null, "e": 1343, "s": 1315, "text": "Enable the Cloud Build API." }, { "code": null, "e": 1381, "s": 1343, "text": "Install and initialize the Cloud SDK." }, { "code": null, "e": 1467, "s": 1381, "text": "After initialization, you may need to select the project that you previously created." }, { "code": null, "e": 1656, "s": 1467, "text": "We will be using the GCP App Engine service to deploy our Flask API. To use this we will need to add App Engine to our chosen project, and then install the App Engine extension for Python." }, { "code": null, "e": 1796, "s": 1656, "text": "From inside your chosen prompt window, we create a new App Engine app using the project name (using your project name) and choose a region." }, { "code": null, "e": 1839, "s": 1796, "text": "gcloud app create --project=aurelio-330516" }, { "code": null, "e": 1897, "s": 1839, "text": "Then we install the App Engine extension for Python with:" }, { "code": null, "e": 1941, "s": 1897, "text": "gcloud components install app-engine-python" }, { "code": null, "e": 2069, "s": 1941, "text": "We now have all of the prerequisites required for deploying our API to GCP’s App Engine. Let’s move on to the Flask API itself." }, { "code": null, "e": 2279, "s": 2069, "text": "Before blindly throwing our API python script at GCP’s App Engine and hoping for the best — we should confirm that it works. We can do this by simulating the App Engine environment, but first — we need an API." }, { "code": null, "e": 2449, "s": 2279, "text": "I will be using this API script. It doesn’t do anything particularly interesting, but it is simple and therefore useful for our example. You can see how I built it here." }, { "code": null, "e": 2661, "s": 2449, "text": "Alongside the API script main.py — you will also need to include a ./data directory that contains the two files users.csv and locations.csv. Altogether this means we have a single directory that looks like this:" }, { "code": null, "e": 2904, "s": 2661, "text": "Back to simulation. To simulate the App Engine environment we will be using gunicorn to run a local Web Server Gateway Interface (WSGI) server. Before this, you may need to pip install gunicorn — then, in the same environment, we run the API:" }, { "code": null, "e": 3051, "s": 2904, "text": "Then we can head on over to http://0.0.0.0:8080/users. If the API is running as expected we should see a small JSON response that looks like this:" }, { "code": null, "e": 3242, "s": 3051, "text": "Gunicorn is using our Python environment — so the libraries we’re importing at the top of our main.py script are already installed. And we also know that we’re using (in my case) Python 3.8." }, { "code": null, "e": 3436, "s": 3242, "text": "This is a problem when we deploy the API to GCP. App Engine will have no idea that we need to use these packages nor that we’re using Python 3.8. So we must add two more files to our directory:" }, { "code": null, "e": 3523, "s": 3436, "text": "requirements.txt will contain a list of the Python packages for App Engine to install." }, { "code": null, "e": 3572, "s": 3523, "text": "app.yaml will set the runtime to use Python 3.8." }, { "code": null, "e": 3605, "s": 3572, "text": "These files will look like this:" }, { "code": null, "e": 3812, "s": 3605, "text": "And that’s all we need. Now we deploy by running gcloud app deploy inside the directory containing all of our files. This will take a moment to deploy, after which we should see the URL of our deployed API!" }, { "code": null, "e": 3921, "s": 3812, "text": "Heading over to that URL followed by the /users endpoint will return us the same JSON object we saw earlier:" }, { "code": null, "e": 4028, "s": 3921, "text": "This means our API is up and running and we can go ahead and make requests as we would with any other API!" }, { "code": null, "e": 4115, "s": 4028, "text": "That’s all for this quick walkthrough for deploying Flask APIs using GCP’s App Engine." }, { "code": null, "e": 4276, "s": 4115, "text": "I hope you enjoyed it! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too." }, { "code": null, "e": 4296, "s": 4276, "text": "Thanks for reading!" }, { "code": null, "e": 4347, "s": 4296, "text": "🤖 70% Discount on the NLP With Transformers Course" } ]
Tryit Editor v3.7
Tryit: HTML table - striped rows
[]
Check two ArrayList for equality in Java
Two ArrayList can be compared to check if they are equal or not using the method java.util.ArrayList.equals(). This method has a single parameter i.e. an ArrayList that is compared with the current object. It returns true if the two ArrayList are equal and false otherwise. A program that demonstrates this is given as follows − Live Demo import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List aList1 = new ArrayList(); aList1.add("Sun"); aList1.add("Moon"); aList1.add("Stars"); List aList2 = new ArrayList(); aList2.add("Sun"); aList2.add("Moon"); aList2.add("Stars"); System.out.println("The two ArrayList are equal? " + aList1.equals(aList2)); } } The two ArrayList are equal? true Now let us understand the above program. The ArrayList aList1 and aList2 are created and ArrayList.add() is used to add the elements to the two ArrayList. Then ArrayList.equals() method is used to check if the ArrayList are equal or not and the result is displayed. A code snippet which demonstrates this is as follows − List aList1 = new ArrayList(); aList1.add("Sun"); aList1.add("Moon"); aList1.add("Stars"); List aList2 = new ArrayList(); aList2.add("Sun"); aList2.add("Moon"); aList2.add("Stars"); System.out.println("The two ArrayList are equal? " + aList1.equals(aList2));
[ { "code": null, "e": 1336, "s": 1062, "text": "Two ArrayList can be compared to check if they are equal or not using the method java.util.ArrayList.equals(). This method has a single parameter i.e. an ArrayList that is compared with the current object. It returns true if the two ArrayList are equal and false otherwise." }, { "code": null, "e": 1391, "s": 1336, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1402, "s": 1391, "text": " Live Demo" }, { "code": null, "e": 1837, "s": 1402, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] args) {\n List aList1 = new ArrayList();\n aList1.add(\"Sun\");\n aList1.add(\"Moon\");\n aList1.add(\"Stars\");\n List aList2 = new ArrayList();\n aList2.add(\"Sun\");\n aList2.add(\"Moon\");\n aList2.add(\"Stars\");\n System.out.println(\"The two ArrayList are equal? \" + aList1.equals(aList2));\n }\n}" }, { "code": null, "e": 1871, "s": 1837, "text": "The two ArrayList are equal? true" }, { "code": null, "e": 1912, "s": 1871, "text": "Now let us understand the above program." }, { "code": null, "e": 2192, "s": 1912, "text": "The ArrayList aList1 and aList2 are created and ArrayList.add() is used to add the elements to the two ArrayList. Then ArrayList.equals() method is used to check if the ArrayList are equal or not and the result is displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2451, "s": 2192, "text": "List aList1 = new ArrayList();\naList1.add(\"Sun\");\naList1.add(\"Moon\");\naList1.add(\"Stars\");\nList aList2 = new ArrayList();\naList2.add(\"Sun\");\naList2.add(\"Moon\");\naList2.add(\"Stars\");\nSystem.out.println(\"The two ArrayList are equal? \" + aList1.equals(aList2));" } ]
Spring boot Exception Handling | @ExceptionHandler | @ControllerAdvice
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we will show you how to handle exceptions in Spring Boot REST API application. This guide helps you to understand how to define generic/global exception handlers in spring boot application. Here I am going to implement a complete Spring boot restful service with all the CRUD operations and handling proper exception handling. Spring Boot Strater 2.0.4 RELEASE Spring Boot Starter WEB Spring Boot Starter JDBC MySql Connector Java 1.8 <?xml version="1.0" encoding="UTF-8"?> <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.onlinetutorialspoint</groupId> <artifactId>Spring-Boot-ExceptionHandling</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Spring-Boot-ExceptionHandling</name> <description>Spring Boot Exception Handling Example</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> package com.onlinetutorialspoint.model; public class Item { private int id; private String name; private String category; public Item() { } public Item(int id, String name, String category) { this.id = id; this.name = name; this.category = category; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } } Preparing Spring Boot Error Response classes. This is the main response class representing response status, error message, and timestamp. package com.onlinetutorialspoint.exception; public class ItemErrorResponse { private int status; public ItemErrorResponse() { } private String message; private long timeStamp; public ItemErrorResponse(int status, String message, long timeStamp) { this.status = status; this.message = message; this.timeStamp = timeStamp; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } } Create ItemNotFoundException class, responsible for handling scenarios like when an item is not available in our database. package com.onlinetutorialspoint.exception; public class ItemNotFoundException extends RuntimeException{ public ItemNotFoundException(String message) { super(message); } public ItemNotFoundException(String message, Throwable cause) { super(message, cause); } public ItemNotFoundException(Throwable cause) { super(cause); } } Create a global ItemExceptionHandler, which handles ItemNotFoundException and all types of exceptions like 403, 500 and so on. package com.onlinetutorialspoint.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ItemExceptionHandler { @ExceptionHandler public ResponseEntity<ItemErrorResponse> handleException(ItemNotFoundException ine){ ItemErrorResponse errorResponse = new ItemErrorResponse(); errorResponse.setStatus(HttpStatus.NOT_FOUND.value()); errorResponse.setMessage(ine.getMessage()); errorResponse.setTimeStamp(System.currentTimeMillis()); return new ResponseEntity<ItemErrorResponse>(errorResponse,HttpStatus.NOT_FOUND); } @ExceptionHandler public ResponseEntity<ItemErrorResponse> handleException(Exception ex){ ItemErrorResponse errorResponse = new ItemErrorResponse(); errorResponse.setStatus(HttpStatus.BAD_REQUEST.value()); errorResponse.setMessage(ex.getMessage()); errorResponse.setTimeStamp(System.currentTimeMillis()); return new ResponseEntity<ItemErrorResponse>(errorResponse,HttpStatus.BAD_REQUEST); } } @ControllerAdvice is used to apply the exception handling technique across the application. This annotation can be used on top of the class; then the class will act as a controller-advice. @ControllerAdvice is something similar to an interceptor or a filter. It Pre-processes the request to the controller and Post-process the response to handle exceptions. Define exception handler methods using @ExceptionHandler annotation given by the Spring Framework. It is going to return ResponseEntity. ResponseEntity is a simple wrapper of HTTP response object; it provides fine-grained control to specify HTTP status codes, HTTP headers and response body. We are creating ItemRepository having all CRUD operations. package com.onlinetutorialspoint.repo; import com.onlinetutorialspoint.exception.ItemNotFoundException; import com.onlinetutorialspoint.model.Item; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class ItemRepository { @Autowired JdbcTemplate template; /*Getting all Items from table*/ public List<Item> getAllItems(){ List<Item> items = template.query("select id, name,category from item",(result,rowNum)->new Item(result.getInt("id"), result.getString("name"),result.getString("category"))); return items; } /*Getting a specific item by item id from table*/ public Item getItem(int itemId){ Item item = null; String query = "SELECT * FROM ITEM WHERE ID=?"; try{ item = template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class)); }catch(Exception e){ throw new ItemNotFoundException("Item Not Found : "+itemId); } return item; } /*Adding an item into database table*/ public int addItem(Item item){ String query = "INSERT INTO ITEM VALUES(?,?,?)"; return template.update(query,new Object[] { Integer.valueOf(item.getId()),item.getName(),item.getCategory() }); } /*delete an item from database*/ public int deleteItem(int id){ String query = "DELETE FROM ITEM WHERE ID =?"; int size = template.update(query,id); if(size == 0){ throw new ItemNotFoundException("No Item Found to delete: "+id); } return size; } /*update an item from database*/ public void updateItem(Item item){ String query = "UPDATE ITEM SET name=?, category=? WHERE id =?"; template.update(query, new Object[] { item.getName(),item.getCategory(), Integer.valueOf(item.getId()) }); } } Creating Spring Boot RestController class package com.onlinetutorialspoint.controller; import com.onlinetutorialspoint.exception.ItemNotFoundException; import com.onlinetutorialspoint.model.Item; import com.onlinetutorialspoint.repo.ItemRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.util.List; @RestController public class ItemController { @Autowired ItemRepository itemRepo; @RequestMapping("/getAllItems") @ResponseBody public ResponseEntity<List<Item>> getAllItems(){ List<Item> items = itemRepo.getAllItems(); return new ResponseEntity<List<Item>>(items, HttpStatus.OK); } @GetMapping("/item/{itemId}") @ResponseBody public ResponseEntity<Item> getItem(@PathVariable int itemId){ if(itemId <= 0){ throw new ItemNotFoundException("Invalid ItemId"); } Item item = itemRepo.getItem(itemId); return new ResponseEntity<Item>(item, HttpStatus.OK); } @PostMapping(value = "/addItem",consumes = {"application/json"},produces = {"application/json"}) @ResponseBody public ResponseEntity<Item> addItem(@RequestBody Item item,UriComponentsBuilder builder){ itemRepo.addItem(item); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/addItem/{id}").buildAndExpand(item.getId()).toUri()); return new ResponseEntity<Item>(headers, HttpStatus.CREATED); } @PutMapping("/updateItem") @ResponseBody public ResponseEntity<Item> updateItem(@RequestBody Item item){ if(item != null){ itemRepo.updateItem(item); } return new ResponseEntity<Item>(item, HttpStatus.OK); } @DeleteMapping("/delete/{id}") @ResponseBody public ResponseEntity<Void> deleteItem(@PathVariable int id){ itemRepo.deleteItem(id); return new ResponseEntity<Void>(HttpStatus.ACCEPTED); } } Main class package com.onlinetutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } mvn spring-boot:run [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building Spring-Boot-ExceptionHandling 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) > test-compile @ Spring-Boot-ExceptionHandling >>> [INFO] [INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ Spring-Boot-ExceptionHandling --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ Spring-Boot-ExceptionHandling --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:3.0.2:testResources (default-testResources) @ Spring-Boot-ExceptionHandling --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory E:\work\Spring-Boot-ExceptionHandling\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ Spring-Boot-ExceptionHandling --- [INFO] No sources to compile [INFO] [INFO] <<< spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) < test-compile @ Spring-Boot-ExceptionHandling <<< [INFO] [INFO] [INFO] --- spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) @ Spring-Boot-ExceptionHandling --- . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.4.RELEASE) 2018-08-27 11:40:24.880 INFO 4584 --- [ main] com.onlinetutorialspoint.Application : Starting Application on DESKTOP-RN4SMHT with PID 4584 (E:\work\Spring-Boot-Excepti onHandling\target\classes started by Lenovo in E:\work\Spring-Boot-ExceptionHandling) 2018-08-27 11:40:24.896 INFO 4584 --- [ main] com.onlinetutorialspoint.Application : No active profile set, falling back to default profiles: default 2018-08-27 11:40:25.146 INFO 4584 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWeb ServerApplicationContext@2de77997: startup date [Mon Aug 27 11:40:25 IST 2018]; root of context hierarchy 2018-08-27 11:40:31.161 INFO 4584 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2018-08-27 11:40:31.317 INFO 4584 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2018-08-27 11:40:31.317 INFO 4584 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.32 2018-08-27 11:40:31.348 INFO 4584 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in pro duction environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_161\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java \javapath;C:\oraclexe\app\oracle\product.2.0\server\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ MySQL\MySQL Server 5.5\bin;C:\php;C:\Apache24;C:\Apache24\bin;C:\Program Files\Java\jdk1.8.0_161\bin;D:\Softwares\apache-maven-3.5.2\bin;C:\Program Files\Git\cmd;C:\Program Files\Git \mingw64\bin;C:\Program Files\Git\usr\bin;D:\Softwares\apache-ant-1.10.2\bin;C:\ProgramData\chocolatey\bin;;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\nodejs\;C:\Users\Lenovo\AppD ata\Local\Programs\Python\Python36\Scripts\;C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\;C:\Users\Lenovo\AppData\Local\Microsoft\WindowsApps;C:\Users\Lenovo\AppData\Local\ atom\bin;C:\Users\Lenovo\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\Docker Toolbox;C:\Users\Lenovo\AppData\Roaming\npm;.] 2018-08-27 11:40:31.567 INFO 4584 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-08-27 11:40:31.583 INFO 4584 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 6468 ms 2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] 2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2018-08-27 11:40:32.911 INFO 4584 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework. web.servlet.resource.ResourceHttpRequestHandler] 2018-08-27 11:40:33.833 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.Annota tionConfigServletWebServerApplicationContext@2de77997: startup date [Mon Aug 27 11:40:25 IST 2018]; root of context hierarchy 2018-08-27 11:40:34.041 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/item/{itemId}],methods=[GET]}" onto public org.springframework.http.Res ponseEntity<com.onlinetutorialspoint.model.Item> com.onlinetutorialspoint.controller.ItemController.getItem(int) 2018-08-27 11:40:34.056 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/delete/{id}],methods=[DELETE]}" onto public org.springframework.http.Re sponseEntity<java.lang.Void> com.onlinetutorialspoint.controller.ItemController.deleteItem(int) 2018-08-27 11:40:34.056 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getAllItems]}" onto public org.springframework.http.ResponseEntity<java .util.List<com.onlinetutorialspoint.model.Item>> com.onlinetutorialspoint.controller.ItemController.getAllItems() 2018-08-27 11:40:34.056 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/updateItem],methods=[PUT]}" onto public org.springframework.http.Respon seEntity<com.onlinetutorialspoint.model.Item> com.onlinetutorialspoint.controller.ItemController.updateItem(com.onlinetutorialspoint.model.Item) ......... ......... Getting all Items : Getting a specific Item: Getting unavailable Item: Deleting unavailable Item: Invalid Item code format (General Exception handler) Happy Learning 🙂 Spring-Boot-ExceptionHandling File size: 97 KB Downloads: 845 Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot Redis Data Example CRUD Operations How to use Spring Boot Random Port Spring Boot How to change the Tomcat to Jetty Server Spring Boot H2 Database + JDBC Template Example Spring Boot In Memory Basic Authentication Security Spring Boot MockMvc JUnit Test Example Spring Boot JNDI Configuration – External Tomcat Spring Boot EhCache Example How to Create own Spring Boot Error Page Spring Boot Kafka Consume JSON Messages Example Advantages of Exception Handling @Component,@Service,@Repository,@Controller in spring Simple Spring Boot Example Spring Boot JPA Integration Example Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot Redis Data Example CRUD Operations How to use Spring Boot Random Port Spring Boot How to change the Tomcat to Jetty Server Spring Boot H2 Database + JDBC Template Example Spring Boot In Memory Basic Authentication Security Spring Boot MockMvc JUnit Test Example Spring Boot JNDI Configuration – External Tomcat Spring Boot EhCache Example How to Create own Spring Boot Error Page Spring Boot Kafka Consume JSON Messages Example Advantages of Exception Handling @Component,@Service,@Repository,@Controller in spring Simple Spring Boot Example Spring Boot JPA Integration Example Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 495, "s": 398, "text": "In this tutorial, we will show you how to handle exceptions in Spring Boot REST API application." }, { "code": null, "e": 743, "s": 495, "text": "This guide helps you to understand how to define generic/global exception handlers in spring boot application. Here I am going to implement a complete Spring boot restful service with all the CRUD operations and handling proper exception handling." }, { "code": null, "e": 777, "s": 743, "text": "Spring Boot Strater 2.0.4 RELEASE" }, { "code": null, "e": 801, "s": 777, "text": "Spring Boot Starter WEB" }, { "code": null, "e": 826, "s": 801, "text": "Spring Boot Starter JDBC" }, { "code": null, "e": 842, "s": 826, "text": "MySql Connector" }, { "code": null, "e": 851, "s": 842, "text": "Java 1.8" }, { "code": null, "e": 2527, "s": 851, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>Spring-Boot-ExceptionHandling</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>Spring-Boot-ExceptionHandling</name>\n <description>Spring Boot Exception Handling Example</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.4.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-jdbc</artifactId>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <scope>runtime</scope>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n" }, { "code": null, "e": 3233, "s": 2527, "text": "package com.onlinetutorialspoint.model;\n\npublic class Item {\n private int id;\n private String name;\n private String category;\n\n public Item() {\n }\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n}\n" }, { "code": null, "e": 3371, "s": 3233, "text": "Preparing Spring Boot Error Response classes. This is the main response class representing response status, error message, and timestamp." }, { "code": null, "e": 4195, "s": 3371, "text": "package com.onlinetutorialspoint.exception;\n\npublic class ItemErrorResponse {\n\n private int status;\n\n public ItemErrorResponse() {\n }\n\n private String message;\n private long timeStamp;\n\n public ItemErrorResponse(int status, String message, long timeStamp) {\n this.status = status;\n this.message = message;\n this.timeStamp = timeStamp;\n }\n\n public int getStatus() {\n return status;\n }\n\n public void setStatus(int status) {\n this.status = status;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public long getTimeStamp() {\n return timeStamp;\n }\n\n public void setTimeStamp(long timeStamp) {\n this.timeStamp = timeStamp;\n }\n}\n" }, { "code": null, "e": 4318, "s": 4195, "text": "Create ItemNotFoundException class, responsible for handling scenarios like when an item is not available in our database." }, { "code": null, "e": 4696, "s": 4318, "text": "package com.onlinetutorialspoint.exception;\n\npublic class ItemNotFoundException extends RuntimeException{\n\n public ItemNotFoundException(String message) {\n super(message);\n }\n\n public ItemNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public ItemNotFoundException(Throwable cause) {\n super(cause);\n }\n}\n" }, { "code": null, "e": 4823, "s": 4696, "text": "Create a global ItemExceptionHandler, which handles ItemNotFoundException and all types of exceptions like 403, 500 and so on." }, { "code": null, "e": 6046, "s": 4823, "text": "package com.onlinetutorialspoint.exception;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.ControllerAdvice;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\n\n@ControllerAdvice\npublic class ItemExceptionHandler {\n\n @ExceptionHandler\n public ResponseEntity<ItemErrorResponse> handleException(ItemNotFoundException ine){\n ItemErrorResponse errorResponse = new ItemErrorResponse();\n errorResponse.setStatus(HttpStatus.NOT_FOUND.value());\n errorResponse.setMessage(ine.getMessage());\n errorResponse.setTimeStamp(System.currentTimeMillis());\n return new ResponseEntity<ItemErrorResponse>(errorResponse,HttpStatus.NOT_FOUND);\n }\n\n @ExceptionHandler\n public ResponseEntity<ItemErrorResponse> handleException(Exception ex){\n ItemErrorResponse errorResponse = new ItemErrorResponse();\n errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());\n errorResponse.setMessage(ex.getMessage());\n errorResponse.setTimeStamp(System.currentTimeMillis());\n return new ResponseEntity<ItemErrorResponse>(errorResponse,HttpStatus.BAD_REQUEST);\n }\n}\n" }, { "code": null, "e": 6235, "s": 6046, "text": "@ControllerAdvice is used to apply the exception handling technique across the application. This annotation can be used on top of the class; then the class will act as a controller-advice." }, { "code": null, "e": 6404, "s": 6235, "text": "@ControllerAdvice is something similar to an interceptor or a filter. It Pre-processes the request to the controller and Post-process the response to handle exceptions." }, { "code": null, "e": 6541, "s": 6404, "text": "Define exception handler methods using @ExceptionHandler annotation given by the Spring Framework. It is going to return ResponseEntity." }, { "code": null, "e": 6696, "s": 6541, "text": "ResponseEntity is a simple wrapper of HTTP response object; it provides fine-grained control to specify HTTP status codes, HTTP headers and response body." }, { "code": null, "e": 6755, "s": 6696, "text": "We are creating ItemRepository having all CRUD operations." }, { "code": null, "e": 8902, "s": 6755, "text": "package com.onlinetutorialspoint.repo;\n\nimport com.onlinetutorialspoint.exception.ItemNotFoundException;\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.jdbc.core.BeanPropertyRowMapper;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.List;\n\n@Repository\npublic class ItemRepository {\n\n @Autowired\n JdbcTemplate template;\n\n /*Getting all Items from table*/\n public List<Item> getAllItems(){\n List<Item> items = template.query(\"select id, name,category from item\",(result,rowNum)->new Item(result.getInt(\"id\"),\n result.getString(\"name\"),result.getString(\"category\")));\n return items;\n }\n /*Getting a specific item by item id from table*/\n public Item getItem(int itemId){\n Item item = null;\n String query = \"SELECT * FROM ITEM WHERE ID=?\";\n try{\n item = template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class));\n }catch(Exception e){\n throw new ItemNotFoundException(\"Item Not Found : \"+itemId);\n }\n return item;\n }\n /*Adding an item into database table*/\n public int addItem(Item item){\n String query = \"INSERT INTO ITEM VALUES(?,?,?)\";\n return template.update(query,new Object[] {\n Integer.valueOf(item.getId()),item.getName(),item.getCategory()\n });\n }\n /*delete an item from database*/\n public int deleteItem(int id){\n String query = \"DELETE FROM ITEM WHERE ID =?\";\n int size = template.update(query,id);\n if(size == 0){\n throw new ItemNotFoundException(\"No Item Found to delete: \"+id);\n }\n return size;\n }\n\n /*update an item from database*/\n public void updateItem(Item item){\n String query = \"UPDATE ITEM SET name=?, category=? WHERE id =?\";\n template.update(query,\n new Object[] {\n item.getName(),item.getCategory(), Integer.valueOf(item.getId())\n });\n }\n}\n" }, { "code": null, "e": 8944, "s": 8902, "text": "Creating Spring Boot RestController class" }, { "code": null, "e": 11095, "s": 8944, "text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.exception.ItemNotFoundException;\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.util.UriComponentsBuilder;\n\nimport java.util.List;\n\n@RestController\npublic class ItemController {\n @Autowired\n ItemRepository itemRepo;\n\n @RequestMapping(\"/getAllItems\")\n @ResponseBody\n public ResponseEntity<List<Item>> getAllItems(){\n List<Item> items = itemRepo.getAllItems();\n return new ResponseEntity<List<Item>>(items, HttpStatus.OK);\n }\n\n @GetMapping(\"/item/{itemId}\")\n @ResponseBody\n public ResponseEntity<Item> getItem(@PathVariable int itemId){\n if(itemId <= 0){\n throw new ItemNotFoundException(\"Invalid ItemId\");\n }\n Item item = itemRepo.getItem(itemId);\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @PostMapping(value = \"/addItem\",consumes = {\"application/json\"},produces = {\"application/json\"})\n @ResponseBody\n public ResponseEntity<Item> addItem(@RequestBody Item item,UriComponentsBuilder builder){\n itemRepo.addItem(item);\n HttpHeaders headers = new HttpHeaders();\n headers.setLocation(builder.path(\"/addItem/{id}\").buildAndExpand(item.getId()).toUri());\n return new ResponseEntity<Item>(headers, HttpStatus.CREATED);\n }\n\n @PutMapping(\"/updateItem\")\n @ResponseBody\n public ResponseEntity<Item> updateItem(@RequestBody Item item){\n if(item != null){\n itemRepo.updateItem(item);\n }\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @DeleteMapping(\"/delete/{id}\")\n @ResponseBody\n public ResponseEntity<Void> deleteItem(@PathVariable int id){\n itemRepo.deleteItem(id);\n return new ResponseEntity<Void>(HttpStatus.ACCEPTED);\n }\n}\n" }, { "code": null, "e": 11106, "s": 11095, "text": "Main class" }, { "code": null, "e": 11415, "s": 11106, "text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n}\n" }, { "code": null, "e": 18393, "s": 11415, "text": "mvn spring-boot:run\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------------------------------------------------------------\n[INFO] Building Spring-Boot-ExceptionHandling 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO]\n[INFO] >>> spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) > test-compile @ Spring-Boot-ExceptionHandling >>>\n[INFO]\n[INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ Spring-Boot-ExceptionHandling ---\n[INFO] Using 'UTF-8' encoding to copy filtered resources.\n[INFO] Copying 1 resource\n[INFO] Copying 0 resource\n[INFO]\n[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ Spring-Boot-ExceptionHandling ---\n[INFO] Nothing to compile - all classes are up to date\n[INFO]\n[INFO] --- maven-resources-plugin:3.0.2:testResources (default-testResources) @ Spring-Boot-ExceptionHandling ---\n[INFO] Using 'UTF-8' encoding to copy filtered resources.\n[INFO] skip non existing resourceDirectory E:\\work\\Spring-Boot-ExceptionHandling\\src\\test\\resources\n[INFO]\n[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ Spring-Boot-ExceptionHandling ---\n[INFO] No sources to compile\n[INFO]\n[INFO] <<< spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) < test-compile @ Spring-Boot-ExceptionHandling <<<\n[INFO]\n[INFO]\n[INFO] --- spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) @ Spring-Boot-ExceptionHandling ---\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.0.4.RELEASE)\n\n2018-08-27 11:40:24.880 INFO 4584 --- [ main] com.onlinetutorialspoint.Application : Starting Application on DESKTOP-RN4SMHT with PID 4584 (E:\\work\\Spring-Boot-Excepti\nonHandling\\target\\classes started by Lenovo in E:\\work\\Spring-Boot-ExceptionHandling)\n2018-08-27 11:40:24.896 INFO 4584 --- [ main] com.onlinetutorialspoint.Application : No active profile set, falling back to default profiles: default\n2018-08-27 11:40:25.146 INFO 4584 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWeb\nServerApplicationContext@2de77997: startup date [Mon Aug 27 11:40:25 IST 2018]; root of context hierarchy\n2018-08-27 11:40:31.161 INFO 4584 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)\n2018-08-27 11:40:31.317 INFO 4584 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n2018-08-27 11:40:31.317 INFO 4584 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.32\n2018-08-27 11:40:31.348 INFO 4584 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in pro\nduction environments was not found on the java.library.path: [C:\\Program Files\\Java\\jdk1.8.0_161\\bin;C:\\WINDOWS\\Sun\\Java\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\ProgramData\\Oracle\\Java\n\\javapath;C:\\oraclexe\\app\\oracle\\product.2.0\\server\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\\nMySQL\\MySQL Server 5.5\\bin;C:\\php;C:\\Apache24;C:\\Apache24\\bin;C:\\Program Files\\Java\\jdk1.8.0_161\\bin;D:\\Softwares\\apache-maven-3.5.2\\bin;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Git\n\\mingw64\\bin;C:\\Program Files\\Git\\usr\\bin;D:\\Softwares\\apache-ant-1.10.2\\bin;C:\\ProgramData\\chocolatey\\bin;;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files\\nodejs\\;C:\\Users\\Lenovo\\AppD\nata\\Local\\Programs\\Python\\Python36\\Scripts\\;C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python36\\;C:\\Users\\Lenovo\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\Lenovo\\AppData\\Local\\\natom\\bin;C:\\Users\\Lenovo\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Program Files\\Microsoft VS Code\\bin;C:\\Program Files\\Docker Toolbox;C:\\Users\\Lenovo\\AppData\\Roaming\\npm;.]\n2018-08-27 11:40:31.567 INFO 4584 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext\n2018-08-27 11:40:31.583 INFO 4584 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 6468 ms\n2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]\n2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]\n2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]\n2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]\n2018-08-27 11:40:31.786 INFO 4584 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]\n2018-08-27 11:40:32.911 INFO 4584 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.\nweb.servlet.resource.ResourceHttpRequestHandler]\n2018-08-27 11:40:33.833 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.Annota\ntionConfigServletWebServerApplicationContext@2de77997: startup date [Mon Aug 27 11:40:25 IST 2018]; root of context hierarchy\n2018-08-27 11:40:34.041 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/item/{itemId}],methods=[GET]}\" onto public org.springframework.http.Res\nponseEntity<com.onlinetutorialspoint.model.Item> com.onlinetutorialspoint.controller.ItemController.getItem(int)\n2018-08-27 11:40:34.056 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/delete/{id}],methods=[DELETE]}\" onto public org.springframework.http.Re\nsponseEntity<java.lang.Void> com.onlinetutorialspoint.controller.ItemController.deleteItem(int)\n2018-08-27 11:40:34.056 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/getAllItems]}\" onto public org.springframework.http.ResponseEntity<java\n.util.List<com.onlinetutorialspoint.model.Item>> com.onlinetutorialspoint.controller.ItemController.getAllItems()\n2018-08-27 11:40:34.056 INFO 4584 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped \"{[/updateItem],methods=[PUT]}\" onto public org.springframework.http.Respon\nseEntity<com.onlinetutorialspoint.model.Item> com.onlinetutorialspoint.controller.ItemController.updateItem(com.onlinetutorialspoint.model.Item)\n.........\n........." }, { "code": null, "e": 18413, "s": 18393, "text": "Getting all Items :" }, { "code": null, "e": 18438, "s": 18413, "text": "Getting a specific Item:" }, { "code": null, "e": 18464, "s": 18438, "text": "Getting unavailable Item:" }, { "code": null, "e": 18491, "s": 18464, "text": "Deleting unavailable Item:" }, { "code": null, "e": 18544, "s": 18491, "text": "Invalid Item code format (General Exception handler)" }, { "code": null, "e": 18561, "s": 18544, "text": "Happy Learning 🙂" }, { "code": null, "e": 18627, "s": 18561, "text": "\n\nSpring-Boot-ExceptionHandling\n\nFile size: 97 KB\nDownloads: 845\n" }, { "code": null, "e": 19266, "s": 18627, "text": "\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring Boot Redis Data Example CRUD Operations\nHow to use Spring Boot Random Port\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot In Memory Basic Authentication Security\nSpring Boot MockMvc JUnit Test Example\nSpring Boot JNDI Configuration – External Tomcat\nSpring Boot EhCache Example\nHow to Create own Spring Boot Error Page\nSpring Boot Kafka Consume JSON Messages Example\nAdvantages of Exception Handling\n@Component,@Service,@Repository,@Controller in spring\nSimple Spring Boot Example\nSpring Boot JPA Integration Example\n" }, { "code": null, "e": 19313, "s": 19266, "text": "Spring Boot JdbcTemplate CRUD Operations Mysql" }, { "code": null, "e": 19360, "s": 19313, "text": "Spring Boot Redis Data Example CRUD Operations" }, { "code": null, "e": 19395, "s": 19360, "text": "How to use Spring Boot Random Port" }, { "code": null, "e": 19448, "s": 19395, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 19496, "s": 19448, "text": "Spring Boot H2 Database + JDBC Template Example" }, { "code": null, "e": 19548, "s": 19496, "text": "Spring Boot In Memory Basic Authentication Security" }, { "code": null, "e": 19587, "s": 19548, "text": "Spring Boot MockMvc JUnit Test Example" }, { "code": null, "e": 19636, "s": 19587, "text": "Spring Boot JNDI Configuration – External Tomcat" }, { "code": null, "e": 19664, "s": 19636, "text": "Spring Boot EhCache Example" }, { "code": null, "e": 19705, "s": 19664, "text": "How to Create own Spring Boot Error Page" }, { "code": null, "e": 19753, "s": 19705, "text": "Spring Boot Kafka Consume JSON Messages Example" }, { "code": null, "e": 19786, "s": 19753, "text": "Advantages of Exception Handling" }, { "code": null, "e": 19840, "s": 19786, "text": "@Component,@Service,@Repository,@Controller in spring" }, { "code": null, "e": 19867, "s": 19840, "text": "Simple Spring Boot Example" }, { "code": null, "e": 19903, "s": 19867, "text": "Spring Boot JPA Integration Example" }, { "code": null, "e": 19909, "s": 19907, "text": "Δ" }, { "code": null, "e": 19936, "s": 19909, "text": " Spring Boot – Hello World" }, { "code": null, "e": 19963, "s": 19936, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 19997, "s": 19963, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 20038, "s": 19997, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 20083, "s": 20038, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 20121, "s": 20083, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 20155, "s": 20121, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 20186, "s": 20155, "text": " Spring Boot – Properties File" }, { "code": null, "e": 20220, "s": 20186, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 20253, "s": 20220, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 20286, "s": 20253, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 20326, "s": 20286, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 20351, "s": 20326, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 20382, "s": 20351, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 20406, "s": 20382, "text": " Spring Boot – Actuator" }, { "code": null, "e": 20452, "s": 20406, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 20475, "s": 20452, "text": " Spring Boot – Swagger" }, { "code": null, "e": 20502, "s": 20475, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 20548, "s": 20502, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 20588, "s": 20548, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 20617, "s": 20588, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 20651, "s": 20617, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 20681, "s": 20651, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 20717, "s": 20681, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 20750, "s": 20717, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 20783, "s": 20750, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 20827, "s": 20783, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 20861, "s": 20827, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 20893, "s": 20861, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 20921, "s": 20893, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 20952, "s": 20921, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 20993, "s": 20952, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 21027, "s": 20993, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 21052, "s": 21027, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 21086, "s": 21052, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 21122, "s": 21086, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 21168, "s": 21122, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 21219, "s": 21168, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 21261, "s": 21219, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 21292, "s": 21261, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 21315, "s": 21292, "text": " Spring Boot – EhCache" }, { "code": null, "e": 21345, "s": 21315, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 21375, "s": 21345, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 21424, "s": 21375, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 21458, "s": 21424, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 21491, "s": 21458, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 21520, "s": 21491, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 21552, "s": 21520, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 21589, "s": 21552, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 21618, "s": 21589, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 21647, "s": 21618, "text": " Spring Boot – MockMvc JUnit" } ]
How to check a String for palindrome using arrays in java?
To verify whether the given string is a palindrome (using arrays) Convert the given string into a character array using the toCharArray() method. Make a copy of this array. Reverse the array. Compare the original array and the reversed array. in case of match given string is a palindrome. import java.util.Arrays; import java.util.Scanner; public class Palindrome { public static void main(String args[]) { System.out.println("Enter a string "); Scanner sc = new Scanner(System.in); String s = sc.nextLine(); char[] myArray = s.toCharArray(); int size = myArray.length; char [] original = Arrays.copyOf(myArray,myArray.length); for (int i = 0; i < size / 2; i++) { char temp = myArray[i]; myArray[i] = myArray[size-i-1]; myArray[size-i-1] = temp; } System.out.println("Original Array"+Arrays.toString(original)); System.out.println("Reverse Array"+Arrays.toString(myArray)); if(Arrays.equals(myArray, original)) { System.out.println("Entered string is a palindrome"); } else { System.out.println("Entered string is not a palindrome"); } } } Enter a string mam Original Array[m, a, m] Reverse Array[m, a, m] Entered string is a palindrome
[ { "code": null, "e": 1128, "s": 1062, "text": "To verify whether the given string is a palindrome (using arrays)" }, { "code": null, "e": 1208, "s": 1128, "text": "Convert the given string into a character array using the toCharArray() method." }, { "code": null, "e": 1235, "s": 1208, "text": "Make a copy of this array." }, { "code": null, "e": 1254, "s": 1235, "text": "Reverse the array." }, { "code": null, "e": 1305, "s": 1254, "text": "Compare the original array and the reversed array." }, { "code": null, "e": 1352, "s": 1305, "text": "in case of match given string is a palindrome." }, { "code": null, "e": 2236, "s": 1352, "text": "import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Palindrome {\n public static void main(String args[]) {\n System.out.println(\"Enter a string \");\n Scanner sc = new Scanner(System.in);\n String s = sc.nextLine();\n char[] myArray = s.toCharArray();\n int size = myArray.length;\n char [] original = Arrays.copyOf(myArray,myArray.length);\n\n for (int i = 0; i < size / 2; i++) {\n char temp = myArray[i];\n myArray[i] = myArray[size-i-1];\n myArray[size-i-1] = temp;\n }\n System.out.println(\"Original Array\"+Arrays.toString(original));\n System.out.println(\"Reverse Array\"+Arrays.toString(myArray));\n\n if(Arrays.equals(myArray, original)) {\n System.out.println(\"Entered string is a palindrome\");\n } else {\n System.out.println(\"Entered string is not a palindrome\");\n }\n }\n}" }, { "code": null, "e": 2334, "s": 2236, "text": "Enter a string\nmam\nOriginal Array[m, a, m]\nReverse Array[m, a, m]\nEntered string is a palindrome\n" } ]
How does pipelining improve performance in computer architecture?
Performance in an unpipelined processor is characterized by the cycle time and the execution time of the instructions. In the case of pipelined execution, instruction processing is interleaved in the pipeline rather than performed sequentially as in non-pipelined processors. Therefore the concept of the execution time of instruction has no meaning, and the in-depth performance specification of a pipelined processor requires three different measures: the cycle time of the processor and the latency and repetition rate values of the instructions. The cycle time defines the time accessible for each stage to accomplish the important operations. The cycle time of the processor is specified by the worst-case processing time of the highest stage. Latency defines the amount of time that the result of a specific instruction takes to become accessible in the pipeline for subsequent dependent instruction. Latency is given as multiples of the cycle time. If the latency of a particular instruction is one cycle, its result is available for a subsequent RAW-dependent instruction in the next cycle. In this case, a RAW-dependent instruction can be processed without any delay. If the latency is more than one cycle, say n-cycles an immediately following RAW-dependent instruction has to be interrupted in the pipeline for n-1 cycles. There are two different kinds of RAW dependency such as define-use dependency and load-use dependency and there are two corresponding kinds of latencies known as define-use latency and load-use latency. The define-use latency of instruction is the time delay occurring after decoding and issue until the result of an operating instruction becomes available in the pipeline for subsequent RAW-dependent instructions. If the value of the define-use latency is one cycle, and immediately following RAW-dependent instruction can be processed without any delay in the pipeline. The define-use delay of instruction is the time a subsequent RAW-dependent instruction has to be interrupted in the pipeline. The define-use delay is one cycle less than the define-use latency. The term load-use latencyload-use latency is interpreted in connection with load instructions, such as in the sequence load r1, x; ad r5, r1, r2; In this example, the result of the load instruction is needed as a source operand in the subsequent ad. The notion of load-use latency and load-use delay is interpreted in the same way as define-use latency and define-use delay. The latency of an instruction being executed in parallel is determined by the execute phase of the pipeline. It can illustrate this with the FP pipeline of the PowerPC 603 which is shown in the figure. The Power PC 603 processes FP additions/subtraction or multiplication in three phases. Two cycles are needed for the instruction fetch, decode and issue phase. The subsequent execution phase takes three cycles. At the end of this phase, the result of the operation is forwarded (bypassed) to any requesting unit in the processor. Finally, in the completion phase, the result is written back into the architectural register file.
[ { "code": null, "e": 1612, "s": 1062, "text": "Performance in an unpipelined processor is characterized by the cycle time and the execution time of the instructions. In the case of pipelined execution, instruction processing is interleaved in the pipeline rather than performed sequentially as in non-pipelined processors. Therefore the concept of the execution time of instruction has no meaning, and the in-depth performance specification of a pipelined processor requires three different measures: the cycle time of the processor and the latency and repetition rate values of the instructions." }, { "code": null, "e": 1811, "s": 1612, "text": "The cycle time defines the time accessible for each stage to accomplish the important operations. The cycle time of the processor is specified by the worst-case processing time of the highest stage." }, { "code": null, "e": 2018, "s": 1811, "text": "Latency defines the amount of time that the result of a specific instruction takes to become accessible in the pipeline for subsequent dependent instruction. Latency is given as multiples of the cycle time." }, { "code": null, "e": 2396, "s": 2018, "text": "If the latency of a particular instruction is one cycle, its result is available for a subsequent RAW-dependent instruction in the next cycle. In this case, a RAW-dependent instruction can be processed without any delay. If the latency is more than one cycle, say n-cycles an immediately following RAW-dependent instruction has to be interrupted in the pipeline for n-1 cycles." }, { "code": null, "e": 2599, "s": 2396, "text": "There are two different kinds of RAW dependency such as define-use dependency and load-use dependency and there are two corresponding kinds of latencies known as define-use latency and load-use latency." }, { "code": null, "e": 2969, "s": 2599, "text": "The define-use latency of instruction is the time delay occurring after decoding and issue until the result of an operating instruction becomes available in the pipeline for subsequent RAW-dependent instructions. If the value of the define-use latency is one cycle, and immediately following RAW-dependent instruction can be processed without any delay in the pipeline." }, { "code": null, "e": 3163, "s": 2969, "text": "The define-use delay of instruction is the time a subsequent RAW-dependent instruction has to be interrupted in the pipeline. The define-use delay is one cycle less than the define-use latency." }, { "code": null, "e": 3282, "s": 3163, "text": "The term load-use latencyload-use latency is interpreted in connection with load instructions, such as in the sequence" }, { "code": null, "e": 3314, "s": 3282, "text": "load r1, x;\nad r5, r1, r2;" }, { "code": null, "e": 3543, "s": 3314, "text": "In this example, the result of the load instruction is needed as a source operand in the subsequent ad. The notion of load-use latency and load-use delay is interpreted in the same way as define-use latency and define-use delay." }, { "code": null, "e": 3745, "s": 3543, "text": "The latency of an instruction being executed in parallel is determined by the execute phase of the pipeline. It can illustrate this with the FP pipeline of the PowerPC 603 which is shown in the figure." }, { "code": null, "e": 4174, "s": 3745, "text": "The Power PC 603 processes FP additions/subtraction or multiplication in three phases. Two cycles are needed for the instruction fetch, decode and issue phase. The subsequent execution phase takes three cycles. At the end of this phase, the result of the operation is forwarded (bypassed) to any requesting unit in the processor. Finally, in the completion phase, the result is written back into the architectural register file." } ]
MySQL filtering by multiple columns?
To perform filtering by multiple columns, use where clause along with OR. Let us first create a table − mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(10), Score int ); Query OK, 0 rows affected (0.28 sec) Insert some records in the table using insert command − mysql> insert into DemoTable(Name,Score) values('John',80); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable(Name,Score) values('John',90); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable(Name,Score) values('Carol',89); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable(Name,Score) values('John',86); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable(Name,Score) values('Carol',98); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable(Name,Score) values('David',99); Query OK, 1 row affected (0.06 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +----+-------+-------+ | Id | Name | Score | +----+-------+-------+ | 1 | John | 80 | | 2 | John | 90 | | 3 | Carol | 89 | | 4 | John | 86 | | 5 | Carol | 98 | | 6 | David | 99 | +----+-------+-------+ 6 rows in set (0.00 sec) Following is the query to perform filtering by multiple columns − mysql> select *from DemoTable where (Name,Score)=('John', 90) or (Name,Score)=('Carol', 98); This will produce the following output − +----+-------+-------+ | Id | Name | Score | +----+-------+-------+ | 2 | John | 90 | | 5 | Carol | 98 | +----+-------+-------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1291, "s": 1187, "text": "To perform filtering by multiple columns, use where clause along with OR. Let us first create a table −" }, { "code": null, "e": 1450, "s": 1291, "text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(10),\n Score int\n );\nQuery OK, 0 rows affected (0.28 sec)" }, { "code": null, "e": 1506, "s": 1450, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2090, "s": 1506, "text": "mysql> insert into DemoTable(Name,Score) values('John',80);\nQuery OK, 1 row affected (0.04 sec)\n\nmysql> insert into DemoTable(Name,Score) values('John',90);\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(Name,Score) values('Carol',89);\nQuery OK, 1 row affected (0.04 sec)\n\nmysql> insert into DemoTable(Name,Score) values('John',86);\nQuery OK, 1 row affected (0.04 sec)\n\nmysql> insert into DemoTable(Name,Score) values('Carol',98);\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(Name,Score) values('David',99);\nQuery OK, 1 row affected (0.06 sec)" }, { "code": null, "e": 2150, "s": 2090, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2181, "s": 2150, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2222, "s": 2181, "text": "This will produce the following output −" }, { "code": null, "e": 2477, "s": 2222, "text": "+----+-------+-------+\n| Id | Name | Score |\n+----+-------+-------+\n| 1 | John | 80 |\n| 2 | John | 90 |\n| 3 | Carol | 89 |\n| 4 | John | 86 |\n| 5 | Carol | 98 |\n| 6 | David | 99 |\n+----+-------+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2543, "s": 2477, "text": "Following is the query to perform filtering by multiple columns −" }, { "code": null, "e": 2636, "s": 2543, "text": "mysql> select *from DemoTable where (Name,Score)=('John', 90) or (Name,Score)=('Carol', 98);" }, { "code": null, "e": 2677, "s": 2636, "text": "This will produce the following output −" }, { "code": null, "e": 2840, "s": 2677, "text": "+----+-------+-------+\n| Id | Name | Score |\n+----+-------+-------+\n| 2 | John | 90 |\n| 5 | Carol | 98 |\n+----+-------+-------+\n2 rows in set (0.00 sec)" } ]
Web Scraping Coronavirus Data into MS Excel
23 May, 2022 Prerequisites: Web Scraping using BeautifulSoap Coronavirus cases are increasing rapidly worldwide. This article will guide you on how to web scrape Coronavirus data and into Ms-excel. If you’ve ever copy and pasted information from a website, you’ve performed the same function as any web scraper, only on a microscopic, manual scale. Web scraping, also known as online data mining, is the method of extracting or scraping data from a website. This knowledge is gathered and then translated to a medium that is more accessible to the user. It’s either a spreadsheet or an API. Approach: Request for a response from the webpage.Parse and extract with the help of the BeautifulSoup() class method and lxml module.Download and export the data with pandas into Excel. Request for a response from the webpage. Parse and extract with the help of the BeautifulSoup() class method and lxml module. Download and export the data with pandas into Excel. The Data Source: We need a webpage to fetch the coronavirus data. So we will be using the Worldometer website here. Worldometer’s webpage will look something like this: data source There are a few libraries you will need, so first, you need to install them. Go to your command line and install them. pip install requests pip install lxml pip install bs4 Now let’s see what we can do with these libraries. Below are the steps for Web Scraping Coronavirus Data into Excel: Step 1) Use the requests library to grab the page. Python3 # Import required moduleimport requests # Make requests from webpageresult = requests.get('https://www.worldometers.info/coronavirus/country/india/') The request library that we downloaded goes and gets a response, to get a request from the webpage, we use requests.get(website URL) method. If the request is successful, it will be stored as a giant python string. We will be able to fetch the complete webpage source code when we run result.text. But the code will not be structured. Note: This may fail if you have a firewall blocking Python/Jupyter. Sometimes you need to run this twice if it fails the first time. Step 2) Use BeautifulSoap() method to extract data from websites. bs4 library already has lots of built-in tools and methods to grab information from a string of this nature (basically an HTML file). It is a Python library for pulling data out of HTML and XML files. Using BeautifulSoup() method of bs4 module we can create a soup object that contains all the ingredients of the webpage. Python3 # Import required modulesimport bs4 # Creating soap objectsoup = bs4.BeautifulSoup(result.text,'lxml') Importing bs4 is to create a BeautifulSoup object. And we’re going to pass on two things here, result.text string and lxml as a string as a constructor argument. lxml goes through this HTML document and then figures out different CSS classes, ids, HTML elements, and tags, etc. Extracting the data, to find the element, you need to right-click and hit inspect on the number of cases. Refer to the attached snapshot below. inspecting the website We need to find the right class i.e. class_= ‘maincounter-number’ serves our purpose. Refer to the attached snapshot below. Finding the right class The BeautifulSoup object has been created in our Python script and the HTML data of the website has been scraped off of the page. Next, we need to get the data that we are interested in, out of the HTML code. Python3 # Searching div tags having maincounter-number classcases = soup.find_all('div' ,class_= 'maincounter-number') Input Screenshot (Inspect element): There is still a lot of HTML code that we do not want. Our desired data entries is wrapped in the HTML div element and inside class_= ‘maincounter-number’. We can use this knowledge to further clean up the scraped data. Step 3) Storing the data We need to save the scraped data in some form that can be used effectively. For this project, all the data will be saved in a Python list. Python3 # List to store number of casesdata = [] # Find the span and get data from itfor i in cases: span = i.find('span') data.append(span.string) # Display number of casesprint(data) Input Screenshot (inspect element): Output: We will use span to fetch data from div. We need the number of cases only, not the tags. So we will use span.string to get those numbers, and then they are stored in data[]. Now that we have the number of cases, we are ready to export our data into an Excel file. Step 4) Processing the data Our last step is to export the data to Ms-excel, for which we are going to use the pandas module. To load the pandas module and start working with it, import the package. Python3 import pandas as pd # Creating dataframedf = pd.DataFrame({"CoronaData": data}) # Naming the columnsdf.index = ['TotalCases', ' Deaths', 'Recovered'] DataFrame is a 2D labeled data structure, potentially heterogeneous tabular data structure with labeled axes (rows and columns). df = pd.DataFrame({“CoronaData”: data}) is used to create a DataFrame and give it a name and map it to the data list that we created earlier. Next, we will give column names with df.index. Output: Step 5) Exporting data into Excel We are ready to export the data into Excel. We will use df.to_csv() method for this task. Python3 # Exporting data into Exceldf.to_csv('Corona_Data.csv') Output: Below is the complete program from the above steps: Python3 # Import required modulesimport requestsimport bs4import pandas as pd # Make requests from webpageurl = 'https://www.worldometers.info/coronavirus/country/india/'result = requests.get(url) # Creating soap objectsoup = bs4.BeautifulSoup(result.text,'lxml') # Searching div tags having maincounter-number classcases = soup.find_all('div' ,class_= 'maincounter-number') # List to store number of casesdata = [] # Find the span and get data from itfor i in cases: span = i.find('span') data.append(span.string) # Display number of casesprint(data) # Creating dataframedf = pd.DataFrame({"CoronaData": data}) # Naming the columnsdf.index = ['TotalCases', ' Deaths', 'Recovered'] # Exporting data into Exceldf.to_csv('Corona_Data.csv') Final Result: gabaa406 surinderdawra388 sweetyty rkbhola5 Python web-scraping-exercises Python-projects Web-scraping Python 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n23 May, 2022" }, { "code": null, "e": 101, "s": 53, "text": "Prerequisites: Web Scraping using BeautifulSoap" }, { "code": null, "e": 238, "s": 101, "text": "Coronavirus cases are increasing rapidly worldwide. This article will guide you on how to web scrape Coronavirus data and into Ms-excel." }, { "code": null, "e": 631, "s": 238, "text": "If you’ve ever copy and pasted information from a website, you’ve performed the same function as any web scraper, only on a microscopic, manual scale. Web scraping, also known as online data mining, is the method of extracting or scraping data from a website. This knowledge is gathered and then translated to a medium that is more accessible to the user. It’s either a spreadsheet or an API." }, { "code": null, "e": 642, "s": 631, "text": "Approach: " }, { "code": null, "e": 819, "s": 642, "text": "Request for a response from the webpage.Parse and extract with the help of the BeautifulSoup() class method and lxml module.Download and export the data with pandas into Excel." }, { "code": null, "e": 860, "s": 819, "text": "Request for a response from the webpage." }, { "code": null, "e": 945, "s": 860, "text": "Parse and extract with the help of the BeautifulSoup() class method and lxml module." }, { "code": null, "e": 998, "s": 945, "text": "Download and export the data with pandas into Excel." }, { "code": null, "e": 1015, "s": 998, "text": "The Data Source:" }, { "code": null, "e": 1167, "s": 1015, "text": "We need a webpage to fetch the coronavirus data. So we will be using the Worldometer website here. Worldometer’s webpage will look something like this:" }, { "code": null, "e": 1180, "s": 1167, "text": "data source " }, { "code": null, "e": 1257, "s": 1180, "text": "There are a few libraries you will need, so first, you need to install them." }, { "code": null, "e": 1299, "s": 1257, "text": "Go to your command line and install them." }, { "code": null, "e": 1353, "s": 1299, "text": "pip install requests\npip install lxml\npip install bs4" }, { "code": null, "e": 1404, "s": 1353, "text": "Now let’s see what we can do with these libraries." }, { "code": null, "e": 1470, "s": 1404, "text": "Below are the steps for Web Scraping Coronavirus Data into Excel:" }, { "code": null, "e": 1521, "s": 1470, "text": "Step 1) Use the requests library to grab the page." }, { "code": null, "e": 1529, "s": 1521, "text": "Python3" }, { "code": "# Import required moduleimport requests # Make requests from webpageresult = requests.get('https://www.worldometers.info/coronavirus/country/india/')", "e": 1679, "s": 1529, "text": null }, { "code": null, "e": 2014, "s": 1679, "text": "The request library that we downloaded goes and gets a response, to get a request from the webpage, we use requests.get(website URL) method. If the request is successful, it will be stored as a giant python string. We will be able to fetch the complete webpage source code when we run result.text. But the code will not be structured." }, { "code": null, "e": 2147, "s": 2014, "text": "Note: This may fail if you have a firewall blocking Python/Jupyter. Sometimes you need to run this twice if it fails the first time." }, { "code": null, "e": 2214, "s": 2147, "text": "Step 2) Use BeautifulSoap() method to extract data from websites. " }, { "code": null, "e": 2536, "s": 2214, "text": "bs4 library already has lots of built-in tools and methods to grab information from a string of this nature (basically an HTML file). It is a Python library for pulling data out of HTML and XML files. Using BeautifulSoup() method of bs4 module we can create a soup object that contains all the ingredients of the webpage." }, { "code": null, "e": 2544, "s": 2536, "text": "Python3" }, { "code": "# Import required modulesimport bs4 # Creating soap objectsoup = bs4.BeautifulSoup(result.text,'lxml')", "e": 2647, "s": 2544, "text": null }, { "code": null, "e": 2925, "s": 2647, "text": "Importing bs4 is to create a BeautifulSoup object. And we’re going to pass on two things here, result.text string and lxml as a string as a constructor argument. lxml goes through this HTML document and then figures out different CSS classes, ids, HTML elements, and tags, etc." }, { "code": null, "e": 3070, "s": 2925, "text": "Extracting the data, to find the element, you need to right-click and hit inspect on the number of cases. Refer to the attached snapshot below. " }, { "code": null, "e": 3093, "s": 3070, "text": "inspecting the website" }, { "code": null, "e": 3218, "s": 3093, "text": "We need to find the right class i.e. class_= ‘maincounter-number’ serves our purpose. Refer to the attached snapshot below. " }, { "code": null, "e": 3242, "s": 3218, "text": "Finding the right class" }, { "code": null, "e": 3452, "s": 3242, "text": "The BeautifulSoup object has been created in our Python script and the HTML data of the website has been scraped off of the page. Next, we need to get the data that we are interested in, out of the HTML code. " }, { "code": null, "e": 3460, "s": 3452, "text": "Python3" }, { "code": "# Searching div tags having maincounter-number classcases = soup.find_all('div' ,class_= 'maincounter-number')", "e": 3571, "s": 3460, "text": null }, { "code": null, "e": 3608, "s": 3571, "text": "Input Screenshot (Inspect element): " }, { "code": null, "e": 3828, "s": 3608, "text": "There is still a lot of HTML code that we do not want. Our desired data entries is wrapped in the HTML div element and inside class_= ‘maincounter-number’. We can use this knowledge to further clean up the scraped data." }, { "code": null, "e": 3853, "s": 3828, "text": "Step 3) Storing the data" }, { "code": null, "e": 3993, "s": 3853, "text": "We need to save the scraped data in some form that can be used effectively. For this project, all the data will be saved in a Python list. " }, { "code": null, "e": 4001, "s": 3993, "text": "Python3" }, { "code": "# List to store number of casesdata = [] # Find the span and get data from itfor i in cases: span = i.find('span') data.append(span.string) # Display number of casesprint(data)", "e": 4184, "s": 4001, "text": null }, { "code": null, "e": 4220, "s": 4184, "text": "Input Screenshot (inspect element):" }, { "code": null, "e": 4228, "s": 4220, "text": "Output:" }, { "code": null, "e": 4402, "s": 4228, "text": "We will use span to fetch data from div. We need the number of cases only, not the tags. So we will use span.string to get those numbers, and then they are stored in data[]." }, { "code": null, "e": 4492, "s": 4402, "text": "Now that we have the number of cases, we are ready to export our data into an Excel file." }, { "code": null, "e": 4520, "s": 4492, "text": "Step 4) Processing the data" }, { "code": null, "e": 4693, "s": 4520, "text": "Our last step is to export the data to Ms-excel, for which we are going to use the pandas module. To load the pandas module and start working with it, import the package. " }, { "code": null, "e": 4701, "s": 4693, "text": "Python3" }, { "code": "import pandas as pd # Creating dataframedf = pd.DataFrame({\"CoronaData\": data}) # Naming the columnsdf.index = ['TotalCases', ' Deaths', 'Recovered']", "e": 4851, "s": 4701, "text": null }, { "code": null, "e": 4980, "s": 4851, "text": "DataFrame is a 2D labeled data structure, potentially heterogeneous tabular data structure with labeled axes (rows and columns)." }, { "code": null, "e": 5122, "s": 4980, "text": "df = pd.DataFrame({“CoronaData”: data}) is used to create a DataFrame and give it a name and map it to the data list that we created earlier." }, { "code": null, "e": 5169, "s": 5122, "text": "Next, we will give column names with df.index." }, { "code": null, "e": 5178, "s": 5169, "text": "Output: " }, { "code": null, "e": 5212, "s": 5178, "text": "Step 5) Exporting data into Excel" }, { "code": null, "e": 5303, "s": 5212, "text": "We are ready to export the data into Excel. We will use df.to_csv() method for this task. " }, { "code": null, "e": 5311, "s": 5303, "text": "Python3" }, { "code": "# Exporting data into Exceldf.to_csv('Corona_Data.csv')", "e": 5367, "s": 5311, "text": null }, { "code": null, "e": 5376, "s": 5367, "text": "Output: " }, { "code": null, "e": 5429, "s": 5376, "text": "Below is the complete program from the above steps: " }, { "code": null, "e": 5437, "s": 5429, "text": "Python3" }, { "code": "# Import required modulesimport requestsimport bs4import pandas as pd # Make requests from webpageurl = 'https://www.worldometers.info/coronavirus/country/india/'result = requests.get(url) # Creating soap objectsoup = bs4.BeautifulSoup(result.text,'lxml') # Searching div tags having maincounter-number classcases = soup.find_all('div' ,class_= 'maincounter-number') # List to store number of casesdata = [] # Find the span and get data from itfor i in cases: span = i.find('span') data.append(span.string) # Display number of casesprint(data) # Creating dataframedf = pd.DataFrame({\"CoronaData\": data}) # Naming the columnsdf.index = ['TotalCases', ' Deaths', 'Recovered'] # Exporting data into Exceldf.to_csv('Corona_Data.csv')", "e": 6187, "s": 5437, "text": null }, { "code": null, "e": 6202, "s": 6187, "text": "Final Result: " }, { "code": null, "e": 6213, "s": 6204, "text": "gabaa406" }, { "code": null, "e": 6230, "s": 6213, "text": "surinderdawra388" }, { "code": null, "e": 6239, "s": 6230, "text": "sweetyty" }, { "code": null, "e": 6248, "s": 6239, "text": "rkbhola5" }, { "code": null, "e": 6278, "s": 6248, "text": "Python web-scraping-exercises" }, { "code": null, "e": 6294, "s": 6278, "text": "Python-projects" }, { "code": null, "e": 6307, "s": 6294, "text": "Web-scraping" }, { "code": null, "e": 6314, "s": 6307, "text": "Python" }, { "code": null, "e": 6412, "s": 6314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6430, "s": 6412, "text": "Python Dictionary" }, { "code": null, "e": 6472, "s": 6430, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6494, "s": 6472, "text": "Enumerate() in Python" }, { "code": null, "e": 6520, "s": 6494, "text": "Python String | replace()" }, { "code": null, "e": 6552, "s": 6520, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6581, "s": 6552, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6608, "s": 6581, "text": "Python Classes and Objects" }, { "code": null, "e": 6629, "s": 6608, "text": "Python OOPs Concepts" }, { "code": null, "e": 6652, "s": 6629, "text": "Introduction To PYTHON" } ]
Python | Pandas Dataframe.duplicated()
29 Sep, 2021 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.An important part of Data analysis is analyzing Duplicate Values and removing them. Pandas duplicated() method helps in analyzing duplicate values only. It returns a boolean series which is True only for Unique elements.Syntax: DataFrame.duplicated(subset=None, keep='first') Parameters: subset: Takes a column or list of column label. It’s default value is none. After passing columns, it will consider them only for duplicates. keep: Controls how to consider duplicate value. It has only three distinct value and default is ‘first’. –> If ‘first’, it considers first value as unique and rest of the same values as duplicate. –> If ‘last’, it considers last value as unique and rest of the same values as duplicate. –> If False, it consider all of the same values as duplicates. To download the CSV file used, Click Here.Example #1: Returning a boolean seriesIn the following example, a boolean series is returned on the basis of duplicate values in the First Name column. Python # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # sorting by first namedata.sort_values("First Name", inplace = True) # making a bool seriesbool_series = data["First Name"].duplicated() # displaying datadata.head() # display datadata[bool_series] Output: As shown in the output image, since the keep parameter was default that is ‘first’, hence whenever the name is occurred, the first one is considered Unique and res Duplicate. Example #2: Removing duplicates In this example, the keep parameter is set to False, so that only Unique values are taken and the duplicate values are removed from data. Python # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # sorting by first namedata.sort_values("First Name", inplace = True) # making a bool seriesbool_series = data["First Name"].duplicated(keep = False) # bool seriesbool_series # passing NOT of bool series to see unique values onlydata = data[~bool_series] # displaying datadata.info()data Output: Since the duplicated() method returns False for Duplicates, the NOT of the series is taken to see unique value in Data Frame. khushboogoyal499 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. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Sep, 2021" }, { "code": null, "e": 497, "s": 54, "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.An important part of Data analysis is analyzing Duplicate Values and removing them. Pandas duplicated() method helps in analyzing duplicate values only. It returns a boolean series which is True only for Unique elements.Syntax: " }, { "code": null, "e": 545, "s": 497, "text": "DataFrame.duplicated(subset=None, keep='first')" }, { "code": null, "e": 559, "s": 545, "text": "Parameters: " }, { "code": null, "e": 1053, "s": 559, "text": "subset: Takes a column or list of column label. It’s default value is none. After passing columns, it will consider them only for duplicates. keep: Controls how to consider duplicate value. It has only three distinct value and default is ‘first’. –> If ‘first’, it considers first value as unique and rest of the same values as duplicate. –> If ‘last’, it considers last value as unique and rest of the same values as duplicate. –> If False, it consider all of the same values as duplicates. " }, { "code": null, "e": 1248, "s": 1053, "text": "To download the CSV file used, Click Here.Example #1: Returning a boolean seriesIn the following example, a boolean series is returned on the basis of duplicate values in the First Name column. " }, { "code": null, "e": 1255, "s": 1248, "text": "Python" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # sorting by first namedata.sort_values(\"First Name\", inplace = True) # making a bool seriesbool_series = data[\"First Name\"].duplicated() # displaying datadata.head() # display datadata[bool_series]", "e": 1569, "s": 1255, "text": null }, { "code": null, "e": 1753, "s": 1569, "text": "Output: As shown in the output image, since the keep parameter was default that is ‘first’, hence whenever the name is occurred, the first one is considered Unique and res Duplicate. " }, { "code": null, "e": 1925, "s": 1753, "text": " Example #2: Removing duplicates In this example, the keep parameter is set to False, so that only Unique values are taken and the duplicate values are removed from data. " }, { "code": null, "e": 1932, "s": 1925, "text": "Python" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # sorting by first namedata.sort_values(\"First Name\", inplace = True) # making a bool seriesbool_series = data[\"First Name\"].duplicated(keep = False) # bool seriesbool_series # passing NOT of bool series to see unique values onlydata = data[~bool_series] # displaying datadata.info()data", "e": 2335, "s": 1932, "text": null }, { "code": null, "e": 2471, "s": 2335, "text": "Output: Since the duplicated() method returns False for Duplicates, the NOT of the series is taken to see unique value in Data Frame. " }, { "code": null, "e": 2490, "s": 2473, "text": "khushboogoyal499" }, { "code": null, "e": 2514, "s": 2490, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2546, "s": 2514, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2560, "s": 2546, "text": "Python-pandas" }, { "code": null, "e": 2567, "s": 2560, "text": "Python" }, { "code": null, "e": 2665, "s": 2567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2683, "s": 2665, "text": "Python Dictionary" }, { "code": null, "e": 2725, "s": 2683, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2747, "s": 2725, "text": "Enumerate() in Python" }, { "code": null, "e": 2779, "s": 2747, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2808, "s": 2779, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2835, "s": 2808, "text": "Python Classes and Objects" }, { "code": null, "e": 2871, "s": 2835, "text": "Convert integer to string in Python" }, { "code": null, "e": 2902, "s": 2871, "text": "Python | os.path.join() method" }, { "code": null, "e": 2939, "s": 2902, "text": "Create a Pandas DataFrame from Lists" } ]
What is right shift (>>) operator in Python?
In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0. >>> bin(a) #binary equivalent 0110 0100 '0b1100100' >>> b=a>>2 #binary equivalent 0001 1101 >>> b 25 >>> bin(b) '0b11001'
[ { "code": null, "e": 1464, "s": 1187, "text": "In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0." }, { "code": null, "e": 1594, "s": 1464, "text": ">>> bin(a) #binary equivalent 0110 0100\n'0b1100100'\n>>> b=a>>2 #binary equivalent 0001 1101\n>>> b\n25\n>>> bin(b)\n'0b11001'" } ]
SQL – SELECT DATE
19 May, 2021 In Microsoft SQL Server, SELECT DATE is used to get the data from the table related to the date, the default format of date is ‘YYYY-MM-DD’. Syntax: SELECT * FROM table_name WHERE condition1, condition2,..; Now we will execute queries on SELECT DATE on database student in detail step-by-step: Step 1: Creating a database university: CREATE DATABASE student; Step 2: Using the database student: USE student; Step 3: Creating a table assignment_details with 5 columns: In MSSQL there is data type DATE which accepts date. CREATE TABLE assignment_details ( stu_id VARCHAR(20), stu_name VARCHAR(20), assn_name VARCHAR(20), due_date DATE, submission_date DATE ); Step 4: Adding rows into table assignment_details : INSERT INTO assignment_details VALUES ('191021','SUJITH','DBMS','2021-04-21','2021-04-25'), ('191022','SUDEEP','DBMS','2021-04-21','2021-04-20'), ('191023','SARASWAT','O.S','2021-04-22','2021-04-24'), ('191024','SATWIK','C++','2021-04-23','2021-04-19'), ('191025','KOUSHIK','C++','2021-04-23','2021-04-21'), ('191026','ABHISHEK','O.S','2021-04-22','2021-04-20'); Step 5: Viewing the rows in the table: SELECT * FROM assignment_details; Query 1: Display students who have submitted on ‘2021-04-20’. SELECT * FROM assignment_details WHERE submission_date='2021-04-20'; Query 2: Display students who have submitted after duedate. SELECT * FROM assignment_details WHERE due_date<submission_date; Query 3: Display students who have submitted before duedate. SELECT * FROM assignment_details WHERE due_date>=submission_date; Query 4: Display students who have submitted O.S assignment on time. SELECT stu_id,stu_name,submission_date FROM assignment_details WHERE assn_name='O.S' AND due_date>=submission_date; Picked SQL-Clauses SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2021" }, { "code": null, "e": 169, "s": 28, "text": "In Microsoft SQL Server, SELECT DATE is used to get the data from the table related to the date, the default format of date is ‘YYYY-MM-DD’." }, { "code": null, "e": 177, "s": 169, "text": "Syntax:" }, { "code": null, "e": 202, "s": 177, "text": "SELECT * FROM table_name" }, { "code": null, "e": 235, "s": 202, "text": "WHERE condition1, condition2,..;" }, { "code": null, "e": 322, "s": 235, "text": "Now we will execute queries on SELECT DATE on database student in detail step-by-step:" }, { "code": null, "e": 362, "s": 322, "text": "Step 1: Creating a database university:" }, { "code": null, "e": 387, "s": 362, "text": "CREATE DATABASE student;" }, { "code": null, "e": 423, "s": 387, "text": "Step 2: Using the database student:" }, { "code": null, "e": 436, "s": 423, "text": "USE student;" }, { "code": null, "e": 496, "s": 436, "text": "Step 3: Creating a table assignment_details with 5 columns:" }, { "code": null, "e": 549, "s": 496, "text": "In MSSQL there is data type DATE which accepts date." }, { "code": null, "e": 707, "s": 549, "text": "CREATE TABLE assignment_details\n(\n stu_id VARCHAR(20),\n stu_name VARCHAR(20),\n assn_name VARCHAR(20),\n due_date DATE,\n submission_date DATE\n);" }, { "code": null, "e": 759, "s": 707, "text": "Step 4: Adding rows into table assignment_details :" }, { "code": null, "e": 1122, "s": 759, "text": "INSERT INTO assignment_details VALUES\n('191021','SUJITH','DBMS','2021-04-21','2021-04-25'),\n('191022','SUDEEP','DBMS','2021-04-21','2021-04-20'),\n('191023','SARASWAT','O.S','2021-04-22','2021-04-24'),\n('191024','SATWIK','C++','2021-04-23','2021-04-19'),\n('191025','KOUSHIK','C++','2021-04-23','2021-04-21'),\n('191026','ABHISHEK','O.S','2021-04-22','2021-04-20');" }, { "code": null, "e": 1161, "s": 1122, "text": "Step 5: Viewing the rows in the table:" }, { "code": null, "e": 1195, "s": 1161, "text": "SELECT * FROM assignment_details;" }, { "code": null, "e": 1258, "s": 1195, "text": "Query 1: Display students who have submitted on ‘2021-04-20’." }, { "code": null, "e": 1327, "s": 1258, "text": "SELECT * FROM assignment_details\nWHERE submission_date='2021-04-20';" }, { "code": null, "e": 1387, "s": 1327, "text": "Query 2: Display students who have submitted after duedate." }, { "code": null, "e": 1452, "s": 1387, "text": "SELECT * FROM assignment_details\nWHERE due_date<submission_date;" }, { "code": null, "e": 1513, "s": 1452, "text": "Query 3: Display students who have submitted before duedate." }, { "code": null, "e": 1579, "s": 1513, "text": "SELECT * FROM assignment_details\nWHERE due_date>=submission_date;" }, { "code": null, "e": 1648, "s": 1579, "text": "Query 4: Display students who have submitted O.S assignment on time." }, { "code": null, "e": 1764, "s": 1648, "text": "SELECT stu_id,stu_name,submission_date FROM assignment_details\nWHERE assn_name='O.S' AND due_date>=submission_date;" }, { "code": null, "e": 1771, "s": 1764, "text": "Picked" }, { "code": null, "e": 1783, "s": 1771, "text": "SQL-Clauses" }, { "code": null, "e": 1787, "s": 1783, "text": "SQL" }, { "code": null, "e": 1791, "s": 1787, "text": "SQL" }, { "code": null, "e": 1889, "s": 1791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1955, "s": 1889, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1979, "s": 1955, "text": "Window functions in SQL" }, { "code": null, "e": 2011, "s": 1979, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2028, "s": 2011, "text": "SQL using Python" }, { "code": null, "e": 2061, "s": 2028, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2139, "s": 2061, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2169, "s": 2139, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2205, "s": 2169, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2236, "s": 2205, "text": "SQL Query to Compare Two Dates" } ]
Union in C
08 Feb, 2019 Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y. #include <stdio.h> // Declaration of union is same as structuresunion test { int x, y;}; int main(){ // A union variable t union test t; t.x = 2; // t.y also gets value 2 printf("After making x = 2:\n x = %d, y = %d\n\n", t.x, t.y); t.y = 10; // t.x is also updated to 10 printf("After making y = 10:\n x = %d, y = %d\n\n", t.x, t.y); return 0;} After making x = 2: x = 2, y = 2 After making y = 10: x = 10, y = 10 How is the size of union decided by compiler?Size of a union is taken according the size of largest member in union. #include <stdio.h> union test1 { int x; int y;} Test1; union test2 { int x; char y;} Test2; union test3 { int arr[10]; char y;} Test3; int main(){ printf("sizeof(test1) = %lu, sizeof(test2) = %lu, " "sizeof(test3) = %lu", sizeof(Test1), sizeof(Test2), sizeof(Test3)); return 0;} sizeof(test1) = 4, sizeof(test2) = 4, sizeof(test3) = 40 Pointers to unions?Like structures, we can have pointers to unions and can access members using the arrow operator (->). The following example demonstrates the same. #include <stdio.h> union test { int x; char y;}; int main(){ union test p1; p1.x = 65; // p2 is a pointer to union p1 union test* p2 = &p1; // Accessing union members using pointer printf("%d %c", p2->x, p2->y); return 0;} 65 A What are applications of union?Unions can be useful in many situations where we want to use the same memory for two or more members. For example, suppose we want to implement a binary tree data structure where each leaf node has a double data value, while each internal node has pointers to two children, but no data. If we declare this as: struct NODE { struct NODE* left; struct NODE* right; double data;}; then every node requires 16 bytes, with half the bytes wasted for each type of node. On the other hand, if we declare a node as following, then we can save space. struct NODE { bool is_leaf; union { struct { struct NODE* left; struct NODE* right; } internal; double data; } info;}; The above example is taken from Computer Systems : A Programmer’s Perspective (English) 2nd Edition book. References:http://en.wikipedia.org/wiki/Union_typeComputer Systems : A Programmer’s Perspective (English) 2nd Edition Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. RajeetGoyal RishabhPrabhu Code_r C Basics C-Struct-Union-Enum cpp-structure C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library rand() and srand() in C/C++ Enumeration (or enum) in C What is the purpose of a function prototype?
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Feb, 2019" }, { "code": null, "e": 158, "s": 52, "text": "Like Structures, union is a user defined data type. In union, all members share the same memory location." }, { "code": null, "e": 297, "s": 158, "text": "For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y." }, { "code": "#include <stdio.h> // Declaration of union is same as structuresunion test { int x, y;}; int main(){ // A union variable t union test t; t.x = 2; // t.y also gets value 2 printf(\"After making x = 2:\\n x = %d, y = %d\\n\\n\", t.x, t.y); t.y = 10; // t.x is also updated to 10 printf(\"After making y = 10:\\n x = %d, y = %d\\n\\n\", t.x, t.y); return 0;}", "e": 693, "s": 297, "text": null }, { "code": null, "e": 766, "s": 693, "text": "After making x = 2:\n x = 2, y = 2\n\nAfter making y = 10:\n x = 10, y = 10\n" }, { "code": null, "e": 884, "s": 766, "text": " How is the size of union decided by compiler?Size of a union is taken according the size of largest member in union." }, { "code": "#include <stdio.h> union test1 { int x; int y;} Test1; union test2 { int x; char y;} Test2; union test3 { int arr[10]; char y;} Test3; int main(){ printf(\"sizeof(test1) = %lu, sizeof(test2) = %lu, \" \"sizeof(test3) = %lu\", sizeof(Test1), sizeof(Test2), sizeof(Test3)); return 0;}", "e": 1221, "s": 884, "text": null }, { "code": null, "e": 1279, "s": 1221, "text": "sizeof(test1) = 4, sizeof(test2) = 4, sizeof(test3) = 40\n" }, { "code": null, "e": 1446, "s": 1279, "text": " Pointers to unions?Like structures, we can have pointers to unions and can access members using the arrow operator (->). The following example demonstrates the same." }, { "code": "#include <stdio.h> union test { int x; char y;}; int main(){ union test p1; p1.x = 65; // p2 is a pointer to union p1 union test* p2 = &p1; // Accessing union members using pointer printf(\"%d %c\", p2->x, p2->y); return 0;}", "e": 1702, "s": 1446, "text": null }, { "code": null, "e": 1708, "s": 1702, "text": "65 A\n" }, { "code": null, "e": 2050, "s": 1708, "text": " What are applications of union?Unions can be useful in many situations where we want to use the same memory for two or more members. For example, suppose we want to implement a binary tree data structure where each leaf node has a double data value, while each internal node has pointers to two children, but no data. If we declare this as:" }, { "code": "struct NODE { struct NODE* left; struct NODE* right; double data;};", "e": 2127, "s": 2050, "text": null }, { "code": null, "e": 2290, "s": 2127, "text": "then every node requires 16 bytes, with half the bytes wasted for each type of node. On the other hand, if we declare a node as following, then we can save space." }, { "code": "struct NODE { bool is_leaf; union { struct { struct NODE* left; struct NODE* right; } internal; double data; } info;};", "e": 2468, "s": 2290, "text": null }, { "code": null, "e": 2574, "s": 2468, "text": "The above example is taken from Computer Systems : A Programmer’s Perspective (English) 2nd Edition book." }, { "code": null, "e": 2692, "s": 2574, "text": "References:http://en.wikipedia.org/wiki/Union_typeComputer Systems : A Programmer’s Perspective (English) 2nd Edition" }, { "code": null, "e": 2817, "s": 2692, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2829, "s": 2817, "text": "RajeetGoyal" }, { "code": null, "e": 2843, "s": 2829, "text": "RishabhPrabhu" }, { "code": null, "e": 2850, "s": 2843, "text": "Code_r" }, { "code": null, "e": 2859, "s": 2850, "text": "C Basics" }, { "code": null, "e": 2879, "s": 2859, "text": "C-Struct-Union-Enum" }, { "code": null, "e": 2893, "s": 2879, "text": "cpp-structure" }, { "code": null, "e": 2904, "s": 2893, "text": "C Language" }, { "code": null, "e": 3002, "s": 2904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3019, "s": 3002, "text": "Substring in C++" }, { "code": null, "e": 3041, "s": 3019, "text": "Function Pointer in C" }, { "code": null, "e": 3076, "s": 3041, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 3122, "s": 3076, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 3167, "s": 3122, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3192, "s": 3167, "text": "std::string class in C++" }, { "code": null, "e": 3240, "s": 3192, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3268, "s": 3240, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 3295, "s": 3268, "text": "Enumeration (or enum) in C" } ]
How to Import a CSV file into a SQLite database Table using Python?
28 Oct, 2021 In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table). Then we connect to our geeks database using the sqlite3.connect() method. At this point, we create a cursor object to handle queries on the database table. We first create our person table and create a csv file with the contents inside which we will be inserting into our table. We open the above-created csv file using the open() function. We extract all the contents of the csv file into our contents variable through csv.reader() method. Then we insert our row-wise contents of csv file into our database through executemany() method which will replace (?,?) with the next two comma-separated data of the csv file and insert it as a record into the person table. Finally, we verify that the data of the csv file has been successfully inserted into our table with the SELECT statement and commit the changes and close the database connection. For the purpose of implementation, we will be creating a person table in our geeks.db database. We are going to insert the content of the person_records.csv in our person table. Below is the CSV file we are going to use: Below is the complete program based on the above approach: Python3 # Import required modulesimport csvimport sqlite3 # Connecting to the geeks databaseconnection = sqlite3.connect('g4g.db') # Creating a cursor object to execute# SQL queries on a database tablecursor = connection.cursor() # Table Definitioncreate_table = '''CREATE TABLE person( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL); ''' # Creating the table into our# databasecursor.execute(create_table) # Opening the person-records.csv filefile = open('person-records.csv') # Reading the contents of the# person-records.csv filecontents = csv.reader(file) # SQL query to insert data into the# person tableinsert_records = "INSERT INTO person (name, age) VALUES(?, ?)" # Importing the contents of the file# into our person tablecursor.executemany(insert_records, contents) # SQL query to retrieve all data from# the person table To verify that the# data of the csv file has been successfully# inserted into the tableselect_all = "SELECT * FROM person"rows = cursor.execute(select_all).fetchall() # Output to the console screenfor r in rows: print(r) # Committing the changesconnection.commit() # closing the database connectionconnection.close() Output: SQLite: gabaa406 Picked Python-SQLite Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2021" }, { "code": null, "e": 146, "s": 28, "text": "In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python." }, { "code": null, "e": 254, "s": 146, "text": "At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table)." }, { "code": null, "e": 328, "s": 254, "text": "Then we connect to our geeks database using the sqlite3.connect() method." }, { "code": null, "e": 410, "s": 328, "text": "At this point, we create a cursor object to handle queries on the database table." }, { "code": null, "e": 533, "s": 410, "text": "We first create our person table and create a csv file with the contents inside which we will be inserting into our table." }, { "code": null, "e": 595, "s": 533, "text": "We open the above-created csv file using the open() function." }, { "code": null, "e": 695, "s": 595, "text": "We extract all the contents of the csv file into our contents variable through csv.reader() method." }, { "code": null, "e": 920, "s": 695, "text": "Then we insert our row-wise contents of csv file into our database through executemany() method which will replace (?,?) with the next two comma-separated data of the csv file and insert it as a record into the person table." }, { "code": null, "e": 1099, "s": 920, "text": "Finally, we verify that the data of the csv file has been successfully inserted into our table with the SELECT statement and commit the changes and close the database connection." }, { "code": null, "e": 1320, "s": 1099, "text": "For the purpose of implementation, we will be creating a person table in our geeks.db database. We are going to insert the content of the person_records.csv in our person table. Below is the CSV file we are going to use:" }, { "code": null, "e": 1379, "s": 1320, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 1387, "s": 1379, "text": "Python3" }, { "code": "# Import required modulesimport csvimport sqlite3 # Connecting to the geeks databaseconnection = sqlite3.connect('g4g.db') # Creating a cursor object to execute# SQL queries on a database tablecursor = connection.cursor() # Table Definitioncreate_table = '''CREATE TABLE person( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL); ''' # Creating the table into our# databasecursor.execute(create_table) # Opening the person-records.csv filefile = open('person-records.csv') # Reading the contents of the# person-records.csv filecontents = csv.reader(file) # SQL query to insert data into the# person tableinsert_records = \"INSERT INTO person (name, age) VALUES(?, ?)\" # Importing the contents of the file# into our person tablecursor.executemany(insert_records, contents) # SQL query to retrieve all data from# the person table To verify that the# data of the csv file has been successfully# inserted into the tableselect_all = \"SELECT * FROM person\"rows = cursor.execute(select_all).fetchall() # Output to the console screenfor r in rows: print(r) # Committing the changesconnection.commit() # closing the database connectionconnection.close()", "e": 2624, "s": 1387, "text": null }, { "code": null, "e": 2632, "s": 2624, "text": "Output:" }, { "code": null, "e": 2640, "s": 2632, "text": "SQLite:" }, { "code": null, "e": 2649, "s": 2640, "text": "gabaa406" }, { "code": null, "e": 2656, "s": 2649, "text": "Picked" }, { "code": null, "e": 2670, "s": 2656, "text": "Python-SQLite" }, { "code": null, "e": 2677, "s": 2670, "text": "Python" } ]
Python OpenCV – Canny() Function
22 Nov, 2021 In this article, we will see the Canny Edge filter in OpenCV. Canny() Function in OpenCV is used to detect the edges in an image. Syntax: cv2.Canny(image, T_lower, T_upper, aperture_size, L2Gradient) Where: Image: Input image to which Canny filter will be applied T_lower: Lower threshold value in Hysteresis Thresholding T_upper: Upper threshold value in Hysteresis Thresholding aperture_size: Aperture size of the Sobel filter. L2Gradient: Boolean parameter used for more precision in calculating Edge Gradient. Reduce Noise using Gaussian Smoothing. Compute image gradient using Sobel filter. Apply Non-Max Suppression or NMS to just jeep the local maxima Finally, apply Hysteresis thresholding which that 2 threshold values T_upper and T_lower which is used in the Canny() function. Input Image: Python3 import cv2 img = cv2.imread("test.jpeg") # Read image # Setting parameter valuest_lower = 50 # Lower Thresholdt_upper = 150 # Upper threshold # Applying the Canny Edge filteredge = cv2.Canny(img, t_lower, t_upper) cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows() Output: This is an optional parameter that is used to specify the order of the Sobel filter used to calculate the gradient in the Canny algorithm. The default value is 3 and its value should be odd between 3 and 7. You can increase the Aperture size when you want to detect more detailed features. Python3 import cv2 img = cv2.imread("test.jpeg") # Read image # Setting All parameterst_lower = 100 # Lower Thresholdt_upper = 200 # Upper thresholdaperture_size = 5 # Aperture size # Applying the Canny Edge filter# with Custom Aperture Sizeedge = cv2.Canny(img, t_lower, t_upper, apertureSize=aperture_size)cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows() Output: It’s a boolean parameter that specifies if you want to calculate the usual gradient equation or the L2Gradient algorithm. Again, it’s an optional parameter. L2gradient is nothing my sqrt(gradient_x_square + gradient_y_square) whereas L1gradient is just abs(gradient_x) + abs(gradient_y). Python3 import cv2 img = cv2.imread("test.jpeg") # Read image t_lower = 100 # Lower Thresholdt_upper = 200 # Upper thresholdaperture_size = 5 # Aperture sizeL2Gradient = True # Boolean # Applying the Canny Edge filter with L2Gradient = Trueedge = cv2.Canny(img, t_lower, t_upper, L2gradient = L2Gradient ) cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows() Output: Here we will use both attributes within the function. Python3 import cv2 img = cv2.imread("test.jpeg") # Read image # Defining all the parameterst_lower = 100 # Lower Thresholdt_upper = 200 # Upper thresholdaperture_size = 5 # Aperture sizeL2Gradient = True # Boolean # Applying the Canny Edge filter # with Aperture Size and L2Gradientedge = cv2.Canny(img, t_lower, t_upper, apertureSize = aperture_size, L2gradient = L2Gradient ) cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows() Output: Picked Python-OpenCV 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 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": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 158, "s": 28, "text": "In this article, we will see the Canny Edge filter in OpenCV. Canny() Function in OpenCV is used to detect the edges in an image." }, { "code": null, "e": 228, "s": 158, "text": "Syntax: cv2.Canny(image, T_lower, T_upper, aperture_size, L2Gradient)" }, { "code": null, "e": 236, "s": 228, "text": "Where: " }, { "code": null, "e": 293, "s": 236, "text": "Image: Input image to which Canny filter will be applied" }, { "code": null, "e": 351, "s": 293, "text": "T_lower: Lower threshold value in Hysteresis Thresholding" }, { "code": null, "e": 409, "s": 351, "text": "T_upper: Upper threshold value in Hysteresis Thresholding" }, { "code": null, "e": 459, "s": 409, "text": "aperture_size: Aperture size of the Sobel filter." }, { "code": null, "e": 543, "s": 459, "text": "L2Gradient: Boolean parameter used for more precision in calculating Edge Gradient." }, { "code": null, "e": 582, "s": 543, "text": "Reduce Noise using Gaussian Smoothing." }, { "code": null, "e": 625, "s": 582, "text": "Compute image gradient using Sobel filter." }, { "code": null, "e": 688, "s": 625, "text": "Apply Non-Max Suppression or NMS to just jeep the local maxima" }, { "code": null, "e": 816, "s": 688, "text": "Finally, apply Hysteresis thresholding which that 2 threshold values T_upper and T_lower which is used in the Canny() function." }, { "code": null, "e": 829, "s": 816, "text": "Input Image:" }, { "code": null, "e": 837, "s": 829, "text": "Python3" }, { "code": "import cv2 img = cv2.imread(\"test.jpeg\") # Read image # Setting parameter valuest_lower = 50 # Lower Thresholdt_upper = 150 # Upper threshold # Applying the Canny Edge filteredge = cv2.Canny(img, t_lower, t_upper) cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows()", "e": 1147, "s": 837, "text": null }, { "code": null, "e": 1155, "s": 1147, "text": "Output:" }, { "code": null, "e": 1445, "s": 1155, "text": "This is an optional parameter that is used to specify the order of the Sobel filter used to calculate the gradient in the Canny algorithm. The default value is 3 and its value should be odd between 3 and 7. You can increase the Aperture size when you want to detect more detailed features." }, { "code": null, "e": 1453, "s": 1445, "text": "Python3" }, { "code": "import cv2 img = cv2.imread(\"test.jpeg\") # Read image # Setting All parameterst_lower = 100 # Lower Thresholdt_upper = 200 # Upper thresholdaperture_size = 5 # Aperture size # Applying the Canny Edge filter# with Custom Aperture Sizeedge = cv2.Canny(img, t_lower, t_upper, apertureSize=aperture_size)cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows()", "e": 1866, "s": 1453, "text": null }, { "code": null, "e": 1875, "s": 1866, "text": "Output: " }, { "code": null, "e": 2163, "s": 1875, "text": "It’s a boolean parameter that specifies if you want to calculate the usual gradient equation or the L2Gradient algorithm. Again, it’s an optional parameter. L2gradient is nothing my sqrt(gradient_x_square + gradient_y_square) whereas L1gradient is just abs(gradient_x) + abs(gradient_y)." }, { "code": null, "e": 2171, "s": 2163, "text": "Python3" }, { "code": "import cv2 img = cv2.imread(\"test.jpeg\") # Read image t_lower = 100 # Lower Thresholdt_upper = 200 # Upper thresholdaperture_size = 5 # Aperture sizeL2Gradient = True # Boolean # Applying the Canny Edge filter with L2Gradient = Trueedge = cv2.Canny(img, t_lower, t_upper, L2gradient = L2Gradient ) cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows()", "e": 2562, "s": 2171, "text": null }, { "code": null, "e": 2572, "s": 2562, "text": " Output: " }, { "code": null, "e": 2626, "s": 2572, "text": "Here we will use both attributes within the function." }, { "code": null, "e": 2634, "s": 2626, "text": "Python3" }, { "code": "import cv2 img = cv2.imread(\"test.jpeg\") # Read image # Defining all the parameterst_lower = 100 # Lower Thresholdt_upper = 200 # Upper thresholdaperture_size = 5 # Aperture sizeL2Gradient = True # Boolean # Applying the Canny Edge filter # with Aperture Size and L2Gradientedge = cv2.Canny(img, t_lower, t_upper, apertureSize = aperture_size, L2gradient = L2Gradient ) cv2.imshow('original', img)cv2.imshow('edge', edge)cv2.waitKey(0)cv2.destroyAllWindows()", "e": 3132, "s": 2634, "text": null }, { "code": null, "e": 3141, "s": 3132, "text": "Output: " }, { "code": null, "e": 3148, "s": 3141, "text": "Picked" }, { "code": null, "e": 3162, "s": 3148, "text": "Python-OpenCV" }, { "code": null, "e": 3169, "s": 3162, "text": "Python" }, { "code": null, "e": 3267, "s": 3169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3299, "s": 3267, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3326, "s": 3299, "text": "Python Classes and Objects" }, { "code": null, "e": 3347, "s": 3326, "text": "Python OOPs Concepts" }, { "code": null, "e": 3370, "s": 3347, "text": "Introduction To PYTHON" }, { "code": null, "e": 3426, "s": 3370, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3457, "s": 3426, "text": "Python | os.path.join() method" }, { "code": null, "e": 3499, "s": 3457, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3541, "s": 3499, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3580, "s": 3541, "text": "Python | Get unique values from a list" } ]
How can we return a dictionary from a Python function?
There can be any number of ways we can return a dictionary from a python function. Consider the one given below. # This function returns a dictionary def foo(): d = dict(); d['str'] = "Tutorialspoint" d['x'] = 50 return d print foo() {'x': 50, 'str': 'Tutorialspoint'}
[ { "code": null, "e": 1300, "s": 1187, "text": "There can be any number of ways we can return a dictionary from a python function. Consider the one given below." }, { "code": null, "e": 1443, "s": 1300, "text": "# This function returns a dictionary\ndef foo():\n d = dict();\n d['str'] = \"Tutorialspoint\"\n d['x'] = 50\n return d\nprint foo()" }, { "code": null, "e": 1478, "s": 1443, "text": "{'x': 50, 'str': 'Tutorialspoint'}" } ]
Smallest number in BST which is greater than or equal to N
16 May, 2022 Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: Input: N = 20 Output: 21 Explanation: 21 is the smallest element greater than 20. Input: N = 18 Output: 19 Explanation: 19 is the smallest element greater than 18. Approach: The idea is to follow the recursive approach for solving the problem i.e. start searching for the element from the root. If there is a leaf node having a value less than N, then element doesn’t exist and return -1. Otherwise, if node’s value is greater than or equal to N and left child is NULL or less than N then return the node value. Else if node’s value is less than N, then search for the element in the right subtree. Else search for the element in the left subtree by calling the function recursively according to the left or right value. C++ Java Python3 C# Javascript // C++ program to find the smallest value// greater than or equal to N#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left, *right;}; // To create new BST NodeNode* createNode(int item){ Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} // To add a new node in BSTNode* add(Node* node, int key){ // if tree is empty return new node if (node == NULL) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node->data) node->left = add(node->left, key); else if (key > node->data) node->right = add(node->right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nint findMinforN(Node* root, int N){ // If leaf node reached and is smaller than N if (root->left == NULL && root->right == NULL && root->data < N) return -1; // If node's value is greater than N and left value // is NULL or smaller then return the node value if ((root->data >= N && root->left == NULL) || (root->data >= N && root->left->data < N)) return root->data; // if node value is smaller than N search in the // right subtree if (root->data <= N) return findMinforN(root->right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root->left, N);} // Drivers codeint main(){ /* 19 / \ 7 21 / \ 3 11 / \ 9 14 */ Node* root = NULL; root = add(root, 19); root = add(root, 7); root = add(root, 3); root = add(root, 11); root = add(root, 9); root = add(root, 13); root = add(root, 21); int N = 18; cout << findMinforN(root, N) << endl; return 0;} // Java program to find the smallest value// greater than or equal to Nimport java.util.*;class GFG{static class Node{ int data; Node left, right;}; // To create new BST Nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // To add a new node in BSTstatic Node add(Node node, int key){ // if tree is empty return new node if (node == null) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node.data) node.left = add(node.left, key); else if (key > node.data) node.right = add(node.right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nstatic int findMinforN(Node root, int N){ // If leaf node reached and is smaller than N if (root.left == null && root.right == null && root.data < N) return -1; // If node's value is greater than N and left value // is null or smaller then return the node value if ((root.data >= N && root.left == null) || (root.data >= N && root.left.data < N)) return root.data; // if node value is smaller than N search in the // right subtree if (root.data <= N) return findMinforN(root.right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root.left, N);} // Driver Codepublic static void main(String[] args){ /* 19 / \ 7 21 / \ 3 11 / \ 9 14 */ Node root = null; root = add(root, 19); root = add(root, 7); root = add(root, 3); root = add(root, 11); root = add(root, 9); root = add(root, 13); root = add(root, 21); int N = 18; System.out.println(findMinforN(root, N));}} // This code is contributed by Rajput-Ji # Python program to find the smallest value# greater than or equal to N class Node: def __init__(self): self.data = 0 self.left = None self.right = None # To create new BST Nodedef createNode(item: int): temp = Node() temp.data = item temp.left = temp.right = None return temp # To add a new node in BSTdef add(node: Node, key: int): # if tree is empty return new node if node is None: return createNode(key) # if key is less than or greater than # node value then recur down the tree if key < node.data: node.left = add(node.left, key) elif key > node.data: node.right = add(node.right, key) # return the (unchanged) node pointer return node # function to find min value less than Ndef findMinforN(root: Node, N: int): # If leaf node reached and is smaller than N if root.left is None and root.right is None and root.data < N: return -1 # If node's value is greater than N and left value # is NULL or smaller then return the node value if root.data >= N and root.left is None or root.data >= N and root.left.data < N: return root.data # if node value is smaller than N search in the # right subtree if root.data <= N: return findMinforN(root.right, N) # if node value is greater than N search in the # left subtree else: return findMinforN(root.left, N) # Driver Codeif __name__ == "__main__": ''' 19 / \ 7 21 / \ 3 11 / \ 9 14 ''' root = Node() root = add(root, 19) root = add(root, 7) root = add(root, 3) root = add(root, 11) root = add(root, 9) root = add(root, 13) root = add(root, 21) N = 18 print(findMinforN(root, N)) # This code is contributed by# sanjeev2552 // C# program to find the smallest value// greater than or equal to Nusing System; class GFG{class Node{ public int data; public Node left, right;}; // To create new BST Nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // To add a new node in BSTstatic Node add(Node node, int key){ // if tree is empty return new node if (node == null) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node.data) node.left = add(node.left, key); else if (key > node.data) node.right = add(node.right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nstatic int findMinforN(Node root, int N){ // If leaf node reached and is smaller than N if (root.left == null && root.right == null && root.data < N) return -1; // If node's value is greater than N and left value // is null or smaller then return the node value if ((root.data >= N && root.left == null) || (root.data >= N && root.left.data < N)) return root.data; // if node value is smaller than N search in the // right subtree if (root.data <= N) return findMinforN(root.right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root.left, N);} // Driver Codepublic static void Main(String[] args){ /* 19 / \ 7 21 / \ 3 11 / \ 9 14 */ Node root = null; root = add(root, 19); root = add(root, 7); root = add(root, 3); root = add(root, 11); root = add(root, 9); root = add(root, 13); root = add(root, 21); int N = 18; Console.WriteLine(findMinforN(root, N));}} // This code is contributed by Princi Singh <script> // javascript program to find the smallest value// greater than or equal to N class Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // To create new BST Nodefunction createNode(item){ var temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // To add a new node in BSTfunction add(node, key){ // if tree is empty return new node if (node == null) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node.data) node.left = add(node.left, key); else if (key > node.data) node.right = add(node.right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nfunction findMinforN(root, N){ // If leaf node reached and is smaller than N if (root.left == null && root.right == null && root.data < N) return -1; // If node's value is greater than N and left value // is null or smaller then return the node value if ((root.data >= N && root.left == null) || (root.data >= N && root.left.data < N)) return root.data; // if node value is smaller than N search in the // right subtree if (root.data <= N) return findMinforN(root.right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root.left, N);} // Driver Code/* 19 / \7 21/ \3 11 / \ 9 14 */var root = null;root = add(root, 19);root = add(root, 7);root = add(root, 3);root = add(root, 11);root = add(root, 9);root = add(root, 13);root = add(root, 21);var N = 18;document.write(findMinforN(root, N)); // This code is contributed by famously.</script> 19 Rajput-Ji princi singh sanjeev2552 famously surinderdawra388 simmytarika5 Searching Quiz Binary Search Tree Recursion Tree Recursion Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 May, 2022" }, { "code": null, "e": 264, "s": 54, "text": "Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Print the value of the element if it exists otherwise print -1. " }, { "code": null, "e": 275, "s": 264, "text": "Examples: " }, { "code": null, "e": 357, "s": 275, "text": "Input: N = 20 Output: 21 Explanation: 21 is the smallest element greater than 20." }, { "code": null, "e": 441, "s": 357, "text": "Input: N = 18 Output: 19 Explanation: 19 is the smallest element greater than 18. " }, { "code": null, "e": 573, "s": 441, "text": "Approach: The idea is to follow the recursive approach for solving the problem i.e. start searching for the element from the root. " }, { "code": null, "e": 667, "s": 573, "text": "If there is a leaf node having a value less than N, then element doesn’t exist and return -1." }, { "code": null, "e": 790, "s": 667, "text": "Otherwise, if node’s value is greater than or equal to N and left child is NULL or less than N then return the node value." }, { "code": null, "e": 877, "s": 790, "text": "Else if node’s value is less than N, then search for the element in the right subtree." }, { "code": null, "e": 999, "s": 877, "text": "Else search for the element in the left subtree by calling the function recursively according to the left or right value." }, { "code": null, "e": 1003, "s": 999, "text": "C++" }, { "code": null, "e": 1008, "s": 1003, "text": "Java" }, { "code": null, "e": 1016, "s": 1008, "text": "Python3" }, { "code": null, "e": 1019, "s": 1016, "text": "C#" }, { "code": null, "e": 1030, "s": 1019, "text": "Javascript" }, { "code": "// C++ program to find the smallest value// greater than or equal to N#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left, *right;}; // To create new BST NodeNode* createNode(int item){ Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} // To add a new node in BSTNode* add(Node* node, int key){ // if tree is empty return new node if (node == NULL) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node->data) node->left = add(node->left, key); else if (key > node->data) node->right = add(node->right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nint findMinforN(Node* root, int N){ // If leaf node reached and is smaller than N if (root->left == NULL && root->right == NULL && root->data < N) return -1; // If node's value is greater than N and left value // is NULL or smaller then return the node value if ((root->data >= N && root->left == NULL) || (root->data >= N && root->left->data < N)) return root->data; // if node value is smaller than N search in the // right subtree if (root->data <= N) return findMinforN(root->right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root->left, N);} // Drivers codeint main(){ /* 19 / \\ 7 21 / \\ 3 11 / \\ 9 14 */ Node* root = NULL; root = add(root, 19); root = add(root, 7); root = add(root, 3); root = add(root, 11); root = add(root, 9); root = add(root, 13); root = add(root, 21); int N = 18; cout << findMinforN(root, N) << endl; return 0;}", "e": 2927, "s": 1030, "text": null }, { "code": "// Java program to find the smallest value// greater than or equal to Nimport java.util.*;class GFG{static class Node{ int data; Node left, right;}; // To create new BST Nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // To add a new node in BSTstatic Node add(Node node, int key){ // if tree is empty return new node if (node == null) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node.data) node.left = add(node.left, key); else if (key > node.data) node.right = add(node.right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nstatic int findMinforN(Node root, int N){ // If leaf node reached and is smaller than N if (root.left == null && root.right == null && root.data < N) return -1; // If node's value is greater than N and left value // is null or smaller then return the node value if ((root.data >= N && root.left == null) || (root.data >= N && root.left.data < N)) return root.data; // if node value is smaller than N search in the // right subtree if (root.data <= N) return findMinforN(root.right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root.left, N);} // Driver Codepublic static void main(String[] args){ /* 19 / \\ 7 21 / \\ 3 11 / \\ 9 14 */ Node root = null; root = add(root, 19); root = add(root, 7); root = add(root, 3); root = add(root, 11); root = add(root, 9); root = add(root, 13); root = add(root, 21); int N = 18; System.out.println(findMinforN(root, N));}} // This code is contributed by Rajput-Ji", "e": 4822, "s": 2927, "text": null }, { "code": "# Python program to find the smallest value# greater than or equal to N class Node: def __init__(self): self.data = 0 self.left = None self.right = None # To create new BST Nodedef createNode(item: int): temp = Node() temp.data = item temp.left = temp.right = None return temp # To add a new node in BSTdef add(node: Node, key: int): # if tree is empty return new node if node is None: return createNode(key) # if key is less than or greater than # node value then recur down the tree if key < node.data: node.left = add(node.left, key) elif key > node.data: node.right = add(node.right, key) # return the (unchanged) node pointer return node # function to find min value less than Ndef findMinforN(root: Node, N: int): # If leaf node reached and is smaller than N if root.left is None and root.right is None and root.data < N: return -1 # If node's value is greater than N and left value # is NULL or smaller then return the node value if root.data >= N and root.left is None or root.data >= N and root.left.data < N: return root.data # if node value is smaller than N search in the # right subtree if root.data <= N: return findMinforN(root.right, N) # if node value is greater than N search in the # left subtree else: return findMinforN(root.left, N) # Driver Codeif __name__ == \"__main__\": ''' 19 / \\ 7 21 / \\ 3 11 / \\ 9 14 ''' root = Node() root = add(root, 19) root = add(root, 7) root = add(root, 3) root = add(root, 11) root = add(root, 9) root = add(root, 13) root = add(root, 21) N = 18 print(findMinforN(root, N)) # This code is contributed by# sanjeev2552", "e": 6631, "s": 4822, "text": null }, { "code": "// C# program to find the smallest value// greater than or equal to Nusing System; class GFG{class Node{ public int data; public Node left, right;}; // To create new BST Nodestatic Node createNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // To add a new node in BSTstatic Node add(Node node, int key){ // if tree is empty return new node if (node == null) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node.data) node.left = add(node.left, key); else if (key > node.data) node.right = add(node.right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nstatic int findMinforN(Node root, int N){ // If leaf node reached and is smaller than N if (root.left == null && root.right == null && root.data < N) return -1; // If node's value is greater than N and left value // is null or smaller then return the node value if ((root.data >= N && root.left == null) || (root.data >= N && root.left.data < N)) return root.data; // if node value is smaller than N search in the // right subtree if (root.data <= N) return findMinforN(root.right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root.left, N);} // Driver Codepublic static void Main(String[] args){ /* 19 / \\ 7 21 / \\ 3 11 / \\ 9 14 */ Node root = null; root = add(root, 19); root = add(root, 7); root = add(root, 3); root = add(root, 11); root = add(root, 9); root = add(root, 13); root = add(root, 21); int N = 18; Console.WriteLine(findMinforN(root, N));}} // This code is contributed by Princi Singh", "e": 8528, "s": 6631, "text": null }, { "code": "<script> // javascript program to find the smallest value// greater than or equal to N class Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // To create new BST Nodefunction createNode(item){ var temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // To add a new node in BSTfunction add(node, key){ // if tree is empty return new node if (node == null) return createNode(key); // if key is less than or greater than // node value then recur down the tree if (key < node.data) node.left = add(node.left, key); else if (key > node.data) node.right = add(node.right, key); // return the (unchanged) node pointer return node;} // function to find min value less than Nfunction findMinforN(root, N){ // If leaf node reached and is smaller than N if (root.left == null && root.right == null && root.data < N) return -1; // If node's value is greater than N and left value // is null or smaller then return the node value if ((root.data >= N && root.left == null) || (root.data >= N && root.left.data < N)) return root.data; // if node value is smaller than N search in the // right subtree if (root.data <= N) return findMinforN(root.right, N); // if node value is greater than N search in the // left subtree else return findMinforN(root.left, N);} // Driver Code/* 19 / \\7 21/ \\3 11 / \\ 9 14 */var root = null;root = add(root, 19);root = add(root, 7);root = add(root, 3);root = add(root, 11);root = add(root, 9);root = add(root, 13);root = add(root, 21);var N = 18;document.write(findMinforN(root, N)); // This code is contributed by famously.</script>", "e": 10327, "s": 8528, "text": null }, { "code": null, "e": 10330, "s": 10327, "text": "19" }, { "code": null, "e": 10342, "s": 10332, "text": "Rajput-Ji" }, { "code": null, "e": 10355, "s": 10342, "text": "princi singh" }, { "code": null, "e": 10367, "s": 10355, "text": "sanjeev2552" }, { "code": null, "e": 10376, "s": 10367, "text": "famously" }, { "code": null, "e": 10393, "s": 10376, "text": "surinderdawra388" }, { "code": null, "e": 10406, "s": 10393, "text": "simmytarika5" }, { "code": null, "e": 10421, "s": 10406, "text": "Searching Quiz" }, { "code": null, "e": 10440, "s": 10421, "text": "Binary Search Tree" }, { "code": null, "e": 10450, "s": 10440, "text": "Recursion" }, { "code": null, "e": 10455, "s": 10450, "text": "Tree" }, { "code": null, "e": 10465, "s": 10455, "text": "Recursion" }, { "code": null, "e": 10484, "s": 10465, "text": "Binary Search Tree" }, { "code": null, "e": 10489, "s": 10484, "text": "Tree" } ]
Removing Direct and Indirect Left Recursion in a Grammar
25 Mar, 2022 Prerequisite – Classification of Context Free Grammars, Ambiguity and Parsers Left Recursion: Grammar of the form, S --> S / a / b It is called left recursive where S is any non Terminal and a, and b are any set of terminals. Problem with Left Recursion: If a left recursion is present in any grammar then, during parsing in the syntax analysis part of compilation there is a chance that the grammar will create infinite loop. This is because at every time of production of grammar S will produce another S without checking any condition. Algorithm to Remove Left Recursion with an example: Suppose we have a grammar which contains left recursion: S-->S a / S b / c / d Check if the given grammar contains left recursion, if present then separate the production and start working on it. In our example, Check if the given grammar contains left recursion, if present then separate the production and start working on it. In our example, S-->S a/ S b /c / d Introduce a new nonterminal and write it at the last of every terminal. We produce a new nonterminal S’and write new production as, Introduce a new nonterminal and write it at the last of every terminal. We produce a new nonterminal S’and write new production as, S-->cS' / dS' Write newly produced nonterminal in LHS and in RHS it can either produce or it can produce new production in which the terminals or non terminals which followed the previous LHS will be replaced by new nonterminal at last. Write newly produced nonterminal in LHS and in RHS it can either produce or it can produce new production in which the terminals or non terminals which followed the previous LHS will be replaced by new nonterminal at last. S'-->? / aS' / bS' So after conversion the new equivalent production is So after conversion the new equivalent production is S-->cS' / dS' S'-->? / aS' / bS' Indirect Left Recursion: A grammar is said to have indirect left recursion if, starting from any symbol of the grammar, it is possible to derive a string whose head is that symbol. For example, A --> Br B --> Cd C --> At Where A, B, C are non-terminals and r, d, t are terminals. Here, starting with A, we can derive A again on substituting C to B and B to A. Algorithm to remove Indirect Recursion with help of an example: A1 --> A2 A3 A2 --> A3 A1 / b A3 --> A1 A1 / a Where A1, A2, A3 are non terminals and a, b are terminals. Identify the productions which can cause indirect left recursion. In our case, Identify the productions which can cause indirect left recursion. In our case, A3--&gt A1 A1 / a Substitute its production at the place the terminal is present in any other production substitute A1–> A2 A3 in production of A3. A3 –> A2 A3 A1. Now in this production substitute A2–> A3 A1 / b and then replace this by, Substitute its production at the place the terminal is present in any other production substitute A1–> A2 A3 in production of A3. A3 –> A2 A3 A1. Now in this production substitute A2–> A3 A1 / b and then replace this by, A3 --> A3 A1 A3 A1 / b A3 A1 Now the new production is converted in form of direct left recursion, solve this by direct left recursion method. Eliminating direct left recursion in the above, Now the new production is converted in form of direct left recursion, solve this by direct left recursion method. Eliminating direct left recursion in the above, A3 --> a | b A3 A1 | aA' | b A3 A1A' A' --> A1 A3 A1 | A1 A3 A1A' The resulting grammar is then: The resulting grammar is then: A1 --> A2 A3 A2 --> A3 A1 | b A3 --> a | b A3 A1 | aA' | b A3 A1A' A' --> A1 A3 A1 | A1 A3 A1A' simmytarika5 Compiler Design GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Runtime Environments in Compiler Design Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Normal Forms in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Mar, 2022" }, { "code": null, "e": 167, "s": 52, "text": "Prerequisite – Classification of Context Free Grammars, Ambiguity and Parsers Left Recursion: Grammar of the form," }, { "code": null, "e": 184, "s": 167, "text": "S --> S / a / b " }, { "code": null, "e": 702, "s": 184, "text": "It is called left recursive where S is any non Terminal and a, and b are any set of terminals. Problem with Left Recursion: If a left recursion is present in any grammar then, during parsing in the syntax analysis part of compilation there is a chance that the grammar will create infinite loop. This is because at every time of production of grammar S will produce another S without checking any condition. Algorithm to Remove Left Recursion with an example: Suppose we have a grammar which contains left recursion:" }, { "code": null, "e": 725, "s": 702, "text": "S-->S a / S b / c / d " }, { "code": null, "e": 858, "s": 725, "text": "Check if the given grammar contains left recursion, if present then separate the production and start working on it. In our example," }, { "code": null, "e": 991, "s": 858, "text": "Check if the given grammar contains left recursion, if present then separate the production and start working on it. In our example," }, { "code": null, "e": 1014, "s": 991, "text": "S-->S a/ S b /c / d " }, { "code": null, "e": 1146, "s": 1014, "text": "Introduce a new nonterminal and write it at the last of every terminal. We produce a new nonterminal S’and write new production as," }, { "code": null, "e": 1278, "s": 1146, "text": "Introduce a new nonterminal and write it at the last of every terminal. We produce a new nonterminal S’and write new production as," }, { "code": null, "e": 1293, "s": 1278, "text": "S-->cS' / dS' " }, { "code": null, "e": 1516, "s": 1293, "text": "Write newly produced nonterminal in LHS and in RHS it can either produce or it can produce new production in which the terminals or non terminals which followed the previous LHS will be replaced by new nonterminal at last." }, { "code": null, "e": 1739, "s": 1516, "text": "Write newly produced nonterminal in LHS and in RHS it can either produce or it can produce new production in which the terminals or non terminals which followed the previous LHS will be replaced by new nonterminal at last." }, { "code": null, "e": 1759, "s": 1739, "text": "S'-->? / aS' / bS' " }, { "code": null, "e": 1812, "s": 1759, "text": "So after conversion the new equivalent production is" }, { "code": null, "e": 1865, "s": 1812, "text": "So after conversion the new equivalent production is" }, { "code": null, "e": 1901, "s": 1865, "text": "S-->cS' / dS'\nS'-->? / aS' / bS' " }, { "code": null, "e": 2095, "s": 1901, "text": "Indirect Left Recursion: A grammar is said to have indirect left recursion if, starting from any symbol of the grammar, it is possible to derive a string whose head is that symbol. For example," }, { "code": null, "e": 2124, "s": 2095, "text": "A --> Br \nB --> Cd\nC --> At " }, { "code": null, "e": 2327, "s": 2124, "text": "Where A, B, C are non-terminals and r, d, t are terminals. Here, starting with A, we can derive A again on substituting C to B and B to A. Algorithm to remove Indirect Recursion with help of an example:" }, { "code": null, "e": 2378, "s": 2327, "text": "A1 --> A2 A3\nA2 --> A3 A1 / b\nA3 --> A1 A1 / a " }, { "code": null, "e": 2437, "s": 2378, "text": "Where A1, A2, A3 are non terminals and a, b are terminals." }, { "code": null, "e": 2516, "s": 2437, "text": "Identify the productions which can cause indirect left recursion. In our case," }, { "code": null, "e": 2595, "s": 2516, "text": "Identify the productions which can cause indirect left recursion. In our case," }, { "code": null, "e": 2614, "s": 2595, "text": "A3--&gt A1 A1 / a " }, { "code": null, "e": 2835, "s": 2614, "text": "Substitute its production at the place the terminal is present in any other production substitute A1–> A2 A3 in production of A3. A3 –> A2 A3 A1. Now in this production substitute A2–> A3 A1 / b and then replace this by," }, { "code": null, "e": 3056, "s": 2835, "text": "Substitute its production at the place the terminal is present in any other production substitute A1–> A2 A3 in production of A3. A3 –> A2 A3 A1. Now in this production substitute A2–> A3 A1 / b and then replace this by," }, { "code": null, "e": 3087, "s": 3056, "text": "A3 --> A3 A1 A3 A1 / b A3 A1 " }, { "code": null, "e": 3249, "s": 3087, "text": "Now the new production is converted in form of direct left recursion, solve this by direct left recursion method. Eliminating direct left recursion in the above," }, { "code": null, "e": 3411, "s": 3249, "text": "Now the new production is converted in form of direct left recursion, solve this by direct left recursion method. Eliminating direct left recursion in the above," }, { "code": null, "e": 3479, "s": 3411, "text": "A3 --> a | b A3 A1 | aA' | b A3 A1A' \nA' --> A1 A3 A1 | A1 A3 A1A' " }, { "code": null, "e": 3510, "s": 3479, "text": "The resulting grammar is then:" }, { "code": null, "e": 3541, "s": 3510, "text": "The resulting grammar is then:" }, { "code": null, "e": 3640, "s": 3541, "text": "A1 --> A2 A3\nA2 --> A3 A1 | b\nA3 --> a | b A3 A1 | aA' | b A3 A1A' \nA' --> A1 A3 A1 | A1 A3 A1A' " }, { "code": null, "e": 3653, "s": 3640, "text": "simmytarika5" }, { "code": null, "e": 3669, "s": 3653, "text": "Compiler Design" }, { "code": null, "e": 3677, "s": 3669, "text": "GATE CS" }, { "code": null, "e": 3710, "s": 3677, "text": "Theory of Computation & Automata" }, { "code": null, "e": 3808, "s": 3710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3866, "s": 3808, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 3899, "s": 3866, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 3930, "s": 3899, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 4000, "s": 3930, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 4040, "s": 4000, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 4060, "s": 4040, "text": "Layers of OSI Model" }, { "code": null, "e": 4084, "s": 4060, "text": "ACID Properties in DBMS" }, { "code": null, "e": 4111, "s": 4084, "text": "Types of Operating Systems" }, { "code": null, "e": 4124, "s": 4111, "text": "TCP/IP Model" } ]
How to specify that a user can enter more than one value in an input element in HTML5?
12 Apr, 2021 The multiple attribute is used to specify whether the user can enter more than one value in an input element. It is a Boolean attribute. When set to true, the input element can accept more than one value. The multiple properties can be used in the following ways. With the <input> tag only the Email and File type accepts the multiple attribute. With the <select> tag when the multiple attribute is used, most of the browsers display a scrolling list box instead of the simple one line dropdown list. This allows the user to select multiple options. Example 1: This example shows how multiple emails can be entered in the input area. Each email is separated by a comma. Any trailing and leading whitespaces are removed from each address in the list. HTML <html><body> <form action=" "> <p> <label> Write down the E-Mails of the peoples you want to send the mail </label> <br> <sub> (You can enter multiple E-Mail with each seperated by comma) </sub> <input type="email" name="email" id="email" multiple size="50"> </p> <p> <input type="submit" value="Submit"> </p> </form></body></html> Output: Before entering the email addresses After entering the email addresses Example 2: This example shows how multiple files can be selected using the <input> tag. Normally only one file is allowed, however using the multiple, the user can select more than one file. HTML <html><body> <form action=" "> <p> <label for="file"> Upload the image files : </label> <input type="file" name="upload" id="upload" multiple accept=".jpeg,.jpg,.png"> <br><br> <label for="file"> Upload the Text files : </label> <input type="file" name="upload" id="upload" multiple accept=".txt"> </p> <p> <input type="submit" value="Submit"> </p> </form></body></html> Output: Before adding the files: After adding the files: Example 3: This example shows how multiple options can be selected in a <select> input. The user can select zero or more options from the list of options by using the CTRL button or use a solution given by the developer. HTML <html><body> <form action=" "> <p> With multiple attribute: <label for="course"> Select the course you like: </label> <select multiple name="course" id="course"> <option>HTML</option> <option>CSS</option> <option>JavaScript</option> <option>Java</option> <option>C++</option> <option>C</option> <option>Python</option> </select> </p> <p> Without multiple attribute: <label for="course"> Select the course you like: </label> <select name="course" id="course"> <option>HTML</option> <option>CSS</option> <option>JavaScript</option> <option>Java</option> <option>C++</option> <option>C</option> <option>Python</option> </select> </p> <p> <input type="submit" value="Submit"> </p> </form></body></html> Output: jimishravat2802 HTML-Questions HTML5 Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2021" }, { "code": null, "e": 292, "s": 28, "text": "The multiple attribute is used to specify whether the user can enter more than one value in an input element. It is a Boolean attribute. When set to true, the input element can accept more than one value. The multiple properties can be used in the following ways." }, { "code": null, "e": 374, "s": 292, "text": "With the <input> tag only the Email and File type accepts the multiple attribute." }, { "code": null, "e": 578, "s": 374, "text": "With the <select> tag when the multiple attribute is used, most of the browsers display a scrolling list box instead of the simple one line dropdown list. This allows the user to select multiple options." }, { "code": null, "e": 778, "s": 578, "text": "Example 1: This example shows how multiple emails can be entered in the input area. Each email is separated by a comma. Any trailing and leading whitespaces are removed from each address in the list." }, { "code": null, "e": 783, "s": 778, "text": "HTML" }, { "code": "<html><body> <form action=\" \"> <p> <label> Write down the E-Mails of the peoples you want to send the mail </label> <br> <sub> (You can enter multiple E-Mail with each seperated by comma) </sub> <input type=\"email\" name=\"email\" id=\"email\" multiple size=\"50\"> </p> <p> <input type=\"submit\" value=\"Submit\"> </p> </form></body></html>", "e": 1263, "s": 783, "text": null }, { "code": null, "e": 1271, "s": 1263, "text": "Output:" }, { "code": null, "e": 1307, "s": 1271, "text": "Before entering the email addresses" }, { "code": null, "e": 1344, "s": 1309, "text": "After entering the email addresses" }, { "code": null, "e": 1538, "s": 1346, "text": "Example 2: This example shows how multiple files can be selected using the <input> tag. Normally only one file is allowed, however using the multiple, the user can select more than one file. " }, { "code": null, "e": 1543, "s": 1538, "text": "HTML" }, { "code": "<html><body> <form action=\" \"> <p> <label for=\"file\"> Upload the image files : </label> <input type=\"file\" name=\"upload\" id=\"upload\" multiple accept=\".jpeg,.jpg,.png\"> <br><br> <label for=\"file\"> Upload the Text files : </label> <input type=\"file\" name=\"upload\" id=\"upload\" multiple accept=\".txt\"> </p> <p> <input type=\"submit\" value=\"Submit\"> </p> </form></body></html>", "e": 2088, "s": 1543, "text": null }, { "code": null, "e": 2096, "s": 2088, "text": "Output:" }, { "code": null, "e": 2121, "s": 2096, "text": "Before adding the files:" }, { "code": null, "e": 2147, "s": 2123, "text": "After adding the files:" }, { "code": null, "e": 2370, "s": 2149, "text": "Example 3: This example shows how multiple options can be selected in a <select> input. The user can select zero or more options from the list of options by using the CTRL button or use a solution given by the developer." }, { "code": null, "e": 2375, "s": 2370, "text": "HTML" }, { "code": "<html><body> <form action=\" \"> <p> With multiple attribute: <label for=\"course\"> Select the course you like: </label> <select multiple name=\"course\" id=\"course\"> <option>HTML</option> <option>CSS</option> <option>JavaScript</option> <option>Java</option> <option>C++</option> <option>C</option> <option>Python</option> </select> </p> <p> Without multiple attribute: <label for=\"course\"> Select the course you like: </label> <select name=\"course\" id=\"course\"> <option>HTML</option> <option>CSS</option> <option>JavaScript</option> <option>Java</option> <option>C++</option> <option>C</option> <option>Python</option> </select> </p> <p> <input type=\"submit\" value=\"Submit\"> </p> </form></body></html>", "e": 3296, "s": 2375, "text": null }, { "code": null, "e": 3304, "s": 3296, "text": "Output:" }, { "code": null, "e": 3320, "s": 3304, "text": "jimishravat2802" }, { "code": null, "e": 3335, "s": 3320, "text": "HTML-Questions" }, { "code": null, "e": 3341, "s": 3335, "text": "HTML5" }, { "code": null, "e": 3348, "s": 3341, "text": "Picked" }, { "code": null, "e": 3353, "s": 3348, "text": "HTML" }, { "code": null, "e": 3370, "s": 3353, "text": "Web Technologies" }, { "code": null, "e": 3375, "s": 3370, "text": "HTML" }, { "code": null, "e": 3473, "s": 3375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3497, "s": 3473, "text": "REST API (Introduction)" }, { "code": null, "e": 3536, "s": 3497, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3575, "s": 3536, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3612, "s": 3575, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3632, "s": 3612, "text": "Angular File Upload" }, { "code": null, "e": 3665, "s": 3632, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3726, "s": 3665, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3769, "s": 3726, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3841, "s": 3769, "text": "Differences between Functional Components and Class Components in React" } ]
How to keep gap between columns using Bootstrap?
30 Nov, 2020 We can keep gap between columns by using normal CSS but here we will use the Bootstrap framework for that. In this article, we will keep a measured gap between columns by the following methods. Using “div” tag: Simply adding a “div” with padding in between two “div” tags gives spacing between the “div”. Example: <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <style media="screen"> .a { padding: 50px; } </style> </head> <body> <div class="row"> <div class="col-4 bg-success a"> One of two columns </div> <div class="col-4"><!--extra div--></div> <div class="col-4 bg-danger a"> One of two columns </div> </div> </body></html> Output: Image without the extra “div” tag: Image without the extra “div” tag: Image with the extra “div” tag: Image with the extra “div” tag: Method using columns offset: The offset class is used to increase the left margin of a column. The class col-md-offset-2 moves col-md-3 by 3 columns. Example: <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <style media="screen"> .a { padding: 50px; } </style> </head> <body> <!--using offset--> <div class="row"> <div class="col-md-5 bg-success a">geeksforgeeks</div> <div class="col-md-5 bg-danger offset-2 a"> geeksforgeeks </div> </div> </body></html> Output: This output may not match with the given output image because the screen size of the output is smaller. Image without offset:Image with offset: Image without offset: Image without offset: Image with offset: Image with offset: Bootstrap-Misc Bootstrap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2020" }, { "code": null, "e": 222, "s": 28, "text": "We can keep gap between columns by using normal CSS but here we will use the Bootstrap framework for that. In this article, we will keep a measured gap between columns by the following methods." }, { "code": null, "e": 333, "s": 222, "text": "Using “div” tag: Simply adding a “div” with padding in between two “div” tags gives spacing between the “div”." }, { "code": null, "e": 342, "s": 333, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"/> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\" /> <style media=\"screen\"> .a { padding: 50px; } </style> </head> <body> <div class=\"row\"> <div class=\"col-4 bg-success a\"> One of two columns </div> <div class=\"col-4\"><!--extra div--></div> <div class=\"col-4 bg-danger a\"> One of two columns </div> </div> </body></html>", "e": 1318, "s": 342, "text": null }, { "code": null, "e": 1326, "s": 1318, "text": "Output:" }, { "code": null, "e": 1361, "s": 1326, "text": "Image without the extra “div” tag:" }, { "code": null, "e": 1396, "s": 1361, "text": "Image without the extra “div” tag:" }, { "code": null, "e": 1428, "s": 1396, "text": "Image with the extra “div” tag:" }, { "code": null, "e": 1460, "s": 1428, "text": "Image with the extra “div” tag:" }, { "code": null, "e": 1610, "s": 1460, "text": "Method using columns offset: The offset class is used to increase the left margin of a column. The class col-md-offset-2 moves col-md-3 by 3 columns." }, { "code": null, "e": 1619, "s": 1610, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\" /> <style media=\"screen\"> .a { padding: 50px; } </style> </head> <body> <!--using offset--> <div class=\"row\"> <div class=\"col-md-5 bg-success a\">geeksforgeeks</div> <div class=\"col-md-5 bg-danger offset-2 a\"> geeksforgeeks </div> </div> </body></html>", "e": 2542, "s": 1619, "text": null }, { "code": null, "e": 2654, "s": 2542, "text": "Output: This output may not match with the given output image because the screen size of the output is smaller." }, { "code": null, "e": 2694, "s": 2654, "text": "Image without offset:Image with offset:" }, { "code": null, "e": 2716, "s": 2694, "text": "Image without offset:" }, { "code": null, "e": 2738, "s": 2716, "text": "Image without offset:" }, { "code": null, "e": 2757, "s": 2738, "text": "Image with offset:" }, { "code": null, "e": 2776, "s": 2757, "text": "Image with offset:" }, { "code": null, "e": 2791, "s": 2776, "text": "Bootstrap-Misc" }, { "code": null, "e": 2801, "s": 2791, "text": "Bootstrap" } ]