title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Minimum XOR of OR and AND of any pair in the Array - GeeksforGeeks
05 May, 2021 Given an array arr[] of N positive integers the task is to find the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 Explanation: For element 2 & 3: The value of the expression (2&3) xor (2|3) is 1, which is the minimum from all the pairs in the given array.Input : arr[] = {3, 6, 8, 4, 5} Output : 1 Explanation: For element 4 & 5: The value of the expression (4&5) xor (4|5) is 1, which is the minimum from all the pairs in the given array. Approach: For any pairs of elements say X and Y, the value of the expression (X&Y) xor (X|Y) can be written as: => (X.Y)^(X+Y) => (X.Y)(X+Y)’ + (X.Y)'(X+Y) => (X.Y)(X’.Y’) + (X’+Y’)(X+Y) => X.X’.Y.Y’ + X’.X + X’.Y + Y’.X + Y’.Y => 0 + 0 + X’.Y + Y’.X + 0 => X^Y From the above calculations, for any pairs (X, Y) in the given array, the expression (X&Y) xor (X|Y) is reduced to X xor Y. Therefore, the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array is given XOR of minimum value pair which can be calculated using the approach discussed in this article. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// value of XOR of AND and OR of// any pair in the given arrayint maxAndXor(int arr[], int n){ int ans = INT_MAX; // Sort the array sort(arr, arr + n); // Traverse the array arr[] for (int i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans;} // Driver Codeint main(){ // Given array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << maxAndXor(arr, N); return 0;} // Java program to for above approachimport java.io.*;import java.util.Arrays;class GFG { // Function to find the minimum // value of XOR of AND and OR of // any pair in the given array static int maxAndXor(int arr[], int n) { int ans = Integer.MAX_VALUE; // Sort the array Arrays.sort(arr); // Traverse the array arr[] for (int i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = Math.min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans; } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = new int[] { 1, 2, 3, 4, 5 }; int N = arr.length; // Function Call System.out.println(maxAndXor(arr, N)); }} // This code is contributed by Shubham Prakash # Python3 program for the above approach # Function to find the minimum# value of XOR of AND and OR of# any pair in the given array def maxAndXor(arr, n): ans = float('inf') # Sort the array arr.sort() # Traverse the array arr[] for i in range(n - 1): # Compare and Find the minimum # XOR value of an array. ans = min(ans, arr[i] ^ arr[i + 1]) # Return the final answer return ans # Driver Codeif __name__ == '__main__': # Given array arr = [1, 2, 3, 4, 5] N = len(arr) # Function Call print(maxAndXor(arr, N)) # This code is contributed by Shivam Singh // C# program to for above approachusing System;class GFG { // Function to find the minimum // value of XOR of AND and OR of // any pair in the given array static int maxAndXor(int[] arr, int n) { int ans = 9999999; // Sort the array Array.Sort(arr); // Traverse the array arr[] for (int i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = Math.Min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans; } // Driver Code public static void Main() { // Given array arr[] int[] arr = new int[] { 1, 2, 3, 4, 5 }; int N = arr.Length; // Function Call Console.Write(maxAndXor(arr, N)); }} // This code is contributed by Code_Mech <script> // JavaScript program for the above approach // Function to find the minimum // value of XOR of AND and OR of // any pair in the given array function maxAndXor(arr, n) { let ans = Number.MAX_VALUE; // Sort the array arr.sort(); // Traverse the array arr[] for (let i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = Math.min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans; } // Driver Code // Given array arr[] let arr = [ 1, 2, 3, 4, 5 ]; let N = arr.length; // Function Call document.write(maxAndXor(arr, N)); // This code is contributed by sanjoy_62.</script> 1 Time Complexity: O(N*log N) Auxiliary Space: O(1) SHIVAMSINGH67 shubham prakash 1 Code_Mech wwwsidharth56 sanjoy_62 Bitwise-AND Bitwise-OR Bitwise-XOR Arrays Bit Magic Arrays Bit Magic 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 Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 26069, "s": 26041, "text": "\n05 May, 2021" }, { "code": null, "e": 26220, "s": 26069, "text": "Given an array arr[] of N positive integers the task is to find the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array." }, { "code": null, "e": 26232, "s": 26220, "text": "Examples: " }, { "code": null, "e": 26600, "s": 26232, "text": "Input: arr[] = {1, 2, 3, 4, 5} Output: 1 Explanation: For element 2 & 3: The value of the expression (2&3) xor (2|3) is 1, which is the minimum from all the pairs in the given array.Input : arr[] = {3, 6, 8, 4, 5} Output : 1 Explanation: For element 4 & 5: The value of the expression (4&5) xor (4|5) is 1, which is the minimum from all the pairs in the given array. " }, { "code": null, "e": 26714, "s": 26600, "text": "Approach: For any pairs of elements say X and Y, the value of the expression (X&Y) xor (X|Y) can be written as: " }, { "code": null, "e": 26866, "s": 26714, "text": "=> (X.Y)^(X+Y) => (X.Y)(X+Y)’ + (X.Y)'(X+Y) => (X.Y)(X’.Y’) + (X’+Y’)(X+Y) => X.X’.Y.Y’ + X’.X + X’.Y + Y’.X + Y’.Y => 0 + 0 + X’.Y + Y’.X + 0 => X^Y " }, { "code": null, "e": 27193, "s": 26866, "text": "From the above calculations, for any pairs (X, Y) in the given array, the expression (X&Y) xor (X|Y) is reduced to X xor Y. Therefore, the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array is given XOR of minimum value pair which can be calculated using the approach discussed in this article. " }, { "code": null, "e": 27245, "s": 27193, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27249, "s": 27245, "text": "C++" }, { "code": null, "e": 27254, "s": 27249, "text": "Java" }, { "code": null, "e": 27262, "s": 27254, "text": "Python3" }, { "code": null, "e": 27265, "s": 27262, "text": "C#" }, { "code": null, "e": 27276, "s": 27265, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// value of XOR of AND and OR of// any pair in the given arrayint maxAndXor(int arr[], int n){ int ans = INT_MAX; // Sort the array sort(arr, arr + n); // Traverse the array arr[] for (int i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans;} // Driver Codeint main(){ // Given array int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << maxAndXor(arr, N); return 0;}", "e": 27974, "s": 27276, "text": null }, { "code": "// Java program to for above approachimport java.io.*;import java.util.Arrays;class GFG { // Function to find the minimum // value of XOR of AND and OR of // any pair in the given array static int maxAndXor(int arr[], int n) { int ans = Integer.MAX_VALUE; // Sort the array Arrays.sort(arr); // Traverse the array arr[] for (int i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = Math.min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans; } // Driver Code public static void main(String[] args) { // Given array arr[] int arr[] = new int[] { 1, 2, 3, 4, 5 }; int N = arr.length; // Function Call System.out.println(maxAndXor(arr, N)); }} // This code is contributed by Shubham Prakash", "e": 28877, "s": 27974, "text": null }, { "code": "# Python3 program for the above approach # Function to find the minimum# value of XOR of AND and OR of# any pair in the given array def maxAndXor(arr, n): ans = float('inf') # Sort the array arr.sort() # Traverse the array arr[] for i in range(n - 1): # Compare and Find the minimum # XOR value of an array. ans = min(ans, arr[i] ^ arr[i + 1]) # Return the final answer return ans # Driver Codeif __name__ == '__main__': # Given array arr = [1, 2, 3, 4, 5] N = len(arr) # Function Call print(maxAndXor(arr, N)) # This code is contributed by Shivam Singh", "e": 29497, "s": 28877, "text": null }, { "code": "// C# program to for above approachusing System;class GFG { // Function to find the minimum // value of XOR of AND and OR of // any pair in the given array static int maxAndXor(int[] arr, int n) { int ans = 9999999; // Sort the array Array.Sort(arr); // Traverse the array arr[] for (int i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = Math.Min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans; } // Driver Code public static void Main() { // Given array arr[] int[] arr = new int[] { 1, 2, 3, 4, 5 }; int N = arr.Length; // Function Call Console.Write(maxAndXor(arr, N)); }} // This code is contributed by Code_Mech", "e": 30335, "s": 29497, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the minimum // value of XOR of AND and OR of // any pair in the given array function maxAndXor(arr, n) { let ans = Number.MAX_VALUE; // Sort the array arr.sort(); // Traverse the array arr[] for (let i = 0; i < n - 1; i++) { // Compare and Find the minimum // XOR value of an array. ans = Math.min(ans, arr[i] ^ arr[i + 1]); } // Return the final answer return ans; } // Driver Code // Given array arr[] let arr = [ 1, 2, 3, 4, 5 ]; let N = arr.length; // Function Call document.write(maxAndXor(arr, N)); // This code is contributed by sanjoy_62.</script>", "e": 31114, "s": 30335, "text": null }, { "code": null, "e": 31116, "s": 31114, "text": "1" }, { "code": null, "e": 31169, "s": 31118, "text": "Time Complexity: O(N*log N) Auxiliary Space: O(1) " }, { "code": null, "e": 31183, "s": 31169, "text": "SHIVAMSINGH67" }, { "code": null, "e": 31201, "s": 31183, "text": "shubham prakash 1" }, { "code": null, "e": 31211, "s": 31201, "text": "Code_Mech" }, { "code": null, "e": 31225, "s": 31211, "text": "wwwsidharth56" }, { "code": null, "e": 31235, "s": 31225, "text": "sanjoy_62" }, { "code": null, "e": 31247, "s": 31235, "text": "Bitwise-AND" }, { "code": null, "e": 31258, "s": 31247, "text": "Bitwise-OR" }, { "code": null, "e": 31270, "s": 31258, "text": "Bitwise-XOR" }, { "code": null, "e": 31277, "s": 31270, "text": "Arrays" }, { "code": null, "e": 31287, "s": 31277, "text": "Bit Magic" }, { "code": null, "e": 31294, "s": 31287, "text": "Arrays" }, { "code": null, "e": 31304, "s": 31294, "text": "Bit Magic" }, { "code": null, "e": 31402, "s": 31304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31470, "s": 31402, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31514, "s": 31470, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31562, "s": 31514, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31585, "s": 31562, "text": "Introduction to Arrays" }, { "code": null, "e": 31617, "s": 31585, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31644, "s": 31617, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 31690, "s": 31644, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31758, "s": 31690, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 31787, "s": 31758, "text": "Count set bits in an integer" } ]
Generate permutations with only adjacent swaps allowed - GeeksforGeeks
16 Jun, 2021 Given a string on length N. You can swap only the adjacent elements and each element can be swapped atmost once. Find the no of permutations of the string that can be generated after performing the swaps as mentioned.Examples: Input : 12345 Output : 12345 12354 12435 13245 13254 21345 21354 21435 Source: Goldman Sachs Interview Consider any i-th character in the string. There are two possibilities for this character: 1.) Don’t swap it, i.e. don’t do anything with this character and move to the next character. 2.) Swap it. As it can be swapped with its adjacent, ........a.) Swap it with the next character. Because each character can be swapped atmost once, we’ll move to the position (i+2). ....... b.) Swap it with the previous character – we don’t need to consider this case separately as i-th character is the next character of (i-1)th which is same as the case 2.a. C++ Java Python3 C# PHP Javascript // CPP program to generate permutations with only// one swap allowed.#include <cstring>#include <iostream>using namespace std; void findPermutations(char str[], int index, int n){ if (index >= n || (index + 1) >= n) { cout << str << endl; return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str[index], str[index + 1]); findPermutations(str, index + 2, n); swap(str[index], str[index + 1]);} // Driver codeint main(){ char str[] = { "12345" }; int n = strlen(str); findPermutations(str, 0, n); return 0;} // Java program to generate permutations with only// one swap allowed. class GFG { static void findPermutations(char str[], int index, int n) { if (index >= n || (index + 1) >= n) { System.out.println(str); return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str, index); findPermutations(str, index + 2, n); swap(str, index); } static void swap(char arr[], int index) { char temp = arr[index]; arr[index] = arr[index + 1]; arr[index + 1] = temp; }// Driver code public static void main(String[] args) { char str[] = "12345".toCharArray(); int n = str.length; findPermutations(str, 0, n); }}// This code is contributed by 29AjayKumar # Python3 program to generate permutations# with only one swap allowed.def findPermutations(string, index, n): if index >= n or (index + 1) >= n: print(''.join(string)) return # don't swap the current position findPermutations(string, index + 1, n) # Swap with the next character and # revert the changes. As explained # above, swapping with previous is # is not needed as it anyways happens # for next character. string[index], \ string[index + 1] = string[index + 1], \ string[index] findPermutations(string, index + 2, n) string[index], \ string[index + 1] = string[index + 1], \ string[index] # Driver Codeif __name__ == "__main__": string = list("12345") n = len(string) findPermutations(string, 0, n) # This code is contributed by# sanjeev2552 // C# program to generate permutations with only// one swap allowed.using System;public class GFG { static void findPermutations(char []str, int index, int n) { if (index >= n || (index + 1) >= n) { Console.WriteLine(str); return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str, index); findPermutations(str, index + 2, n); swap(str, index); } static void swap(char []arr, int index) { char temp = arr[index]; arr[index] = arr[index + 1]; arr[index + 1] = temp; }// Driver code public static void Main() { char []str = "12345".ToCharArray(); int n = str.Length; findPermutations(str, 0, n); }} // This code is contributed by Rajput-Ji <?php// PHP program to generate permutations// with only one swap allowed. function findPermutations($str, $index, $n){ if ($index >= $n || ($index + 1) >= $n) { echo $str, "\n"; return; } // don't swap the current position findPermutations($str, $index + 1, $n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. list($str[$index], $str[$index + 1]) = array($str[$index + 1], $str[$index]); findPermutations($str, $index + 2, $n); list($str[$index], $str[$index + 1]) = array($str[$index + 1], $str[$index]);} // Driver code$str = "12345" ;$n = strlen($str);findPermutations($str, 0, $n); // This code is contributed by Sach_Code?> <script> // JavaScript program to generate // permutations with only // one swap allowed. function findPermutations(str, index, n) { if (index >= n || index + 1 >= n) { document.write(str.join("") + "<br>"); return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str, index); findPermutations(str, index + 2, n); swap(str, index); } function swap(arr, index) { var temp = arr[index]; arr[index] = arr[index + 1]; arr[index + 1] = temp; } // Driver code var str = "12345".split(""); var n = str.length; findPermutations(str, 0, n); </script> Output: 12345 12354 12435 13245 13254 21345 21354 21435 This article is contributed by ekta1994. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sach_Code 29AjayKumar Rajput-Ji sanjeev2552 rdtank Goldman Sachs Combinatorial Strings Goldman Sachs Strings Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ways to sum to N using Natural Numbers up to K with repetitions allowed Generate all possible combinations of K numbers that sums to N Combinations with repetitions Largest substring with same Characters Generate all possible combinations of at most X characters from a given array Write a program to reverse an array or string Reverse a string in Java C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26723, "s": 26695, "text": "\n16 Jun, 2021" }, { "code": null, "e": 26952, "s": 26723, "text": "Given a string on length N. You can swap only the adjacent elements and each element can be swapped atmost once. Find the no of permutations of the string that can be generated after performing the swaps as mentioned.Examples: " }, { "code": null, "e": 27033, "s": 26952, "text": "Input : 12345\nOutput : 12345 12354 12435 13245 13254 \n 21345 21354 21435" }, { "code": null, "e": 27066, "s": 27033, "text": "Source: Goldman Sachs Interview " }, { "code": null, "e": 27614, "s": 27066, "text": "Consider any i-th character in the string. There are two possibilities for this character: 1.) Don’t swap it, i.e. don’t do anything with this character and move to the next character. 2.) Swap it. As it can be swapped with its adjacent, ........a.) Swap it with the next character. Because each character can be swapped atmost once, we’ll move to the position (i+2). ....... b.) Swap it with the previous character – we don’t need to consider this case separately as i-th character is the next character of (i-1)th which is same as the case 2.a. " }, { "code": null, "e": 27618, "s": 27614, "text": "C++" }, { "code": null, "e": 27623, "s": 27618, "text": "Java" }, { "code": null, "e": 27631, "s": 27623, "text": "Python3" }, { "code": null, "e": 27634, "s": 27631, "text": "C#" }, { "code": null, "e": 27638, "s": 27634, "text": "PHP" }, { "code": null, "e": 27649, "s": 27638, "text": "Javascript" }, { "code": "// CPP program to generate permutations with only// one swap allowed.#include <cstring>#include <iostream>using namespace std; void findPermutations(char str[], int index, int n){ if (index >= n || (index + 1) >= n) { cout << str << endl; return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str[index], str[index + 1]); findPermutations(str, index + 2, n); swap(str[index], str[index + 1]);} // Driver codeint main(){ char str[] = { \"12345\" }; int n = strlen(str); findPermutations(str, 0, n); return 0;}", "e": 28423, "s": 27649, "text": null }, { "code": "// Java program to generate permutations with only// one swap allowed. class GFG { static void findPermutations(char str[], int index, int n) { if (index >= n || (index + 1) >= n) { System.out.println(str); return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str, index); findPermutations(str, index + 2, n); swap(str, index); } static void swap(char arr[], int index) { char temp = arr[index]; arr[index] = arr[index + 1]; arr[index + 1] = temp; }// Driver code public static void main(String[] args) { char str[] = \"12345\".toCharArray(); int n = str.length; findPermutations(str, 0, n); }}// This code is contributed by 29AjayKumar", "e": 29433, "s": 28423, "text": null }, { "code": "# Python3 program to generate permutations# with only one swap allowed.def findPermutations(string, index, n): if index >= n or (index + 1) >= n: print(''.join(string)) return # don't swap the current position findPermutations(string, index + 1, n) # Swap with the next character and # revert the changes. As explained # above, swapping with previous is # is not needed as it anyways happens # for next character. string[index], \\ string[index + 1] = string[index + 1], \\ string[index] findPermutations(string, index + 2, n) string[index], \\ string[index + 1] = string[index + 1], \\ string[index] # Driver Codeif __name__ == \"__main__\": string = list(\"12345\") n = len(string) findPermutations(string, 0, n) # This code is contributed by# sanjeev2552", "e": 30323, "s": 29433, "text": null }, { "code": "// C# program to generate permutations with only// one swap allowed.using System;public class GFG { static void findPermutations(char []str, int index, int n) { if (index >= n || (index + 1) >= n) { Console.WriteLine(str); return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str, index); findPermutations(str, index + 2, n); swap(str, index); } static void swap(char []arr, int index) { char temp = arr[index]; arr[index] = arr[index + 1]; arr[index + 1] = temp; }// Driver code public static void Main() { char []str = \"12345\".ToCharArray(); int n = str.Length; findPermutations(str, 0, n); }} // This code is contributed by Rajput-Ji", "e": 31335, "s": 30323, "text": null }, { "code": "<?php// PHP program to generate permutations// with only one swap allowed. function findPermutations($str, $index, $n){ if ($index >= $n || ($index + 1) >= $n) { echo $str, \"\\n\"; return; } // don't swap the current position findPermutations($str, $index + 1, $n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. list($str[$index], $str[$index + 1]) = array($str[$index + 1], $str[$index]); findPermutations($str, $index + 2, $n); list($str[$index], $str[$index + 1]) = array($str[$index + 1], $str[$index]);} // Driver code$str = \"12345\" ;$n = strlen($str);findPermutations($str, 0, $n); // This code is contributed by Sach_Code?>", "e": 32228, "s": 31335, "text": null }, { "code": "<script> // JavaScript program to generate // permutations with only // one swap allowed. function findPermutations(str, index, n) { if (index >= n || index + 1 >= n) { document.write(str.join(\"\") + \"<br>\"); return; } // don't swap the current position findPermutations(str, index + 1, n); // Swap with the next character and // revert the changes. As explained // above, swapping with previous is // is not needed as it anyways happens // for next character. swap(str, index); findPermutations(str, index + 2, n); swap(str, index); } function swap(arr, index) { var temp = arr[index]; arr[index] = arr[index + 1]; arr[index + 1] = temp; } // Driver code var str = \"12345\".split(\"\"); var n = str.length; findPermutations(str, 0, n); </script>", "e": 33160, "s": 32228, "text": null }, { "code": null, "e": 33170, "s": 33160, "text": "Output: " }, { "code": null, "e": 33218, "s": 33170, "text": "12345\n12354\n12435\n13245\n13254\n21345\n21354\n21435" }, { "code": null, "e": 33635, "s": 33218, "text": "This article is contributed by ekta1994. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33645, "s": 33635, "text": "Sach_Code" }, { "code": null, "e": 33657, "s": 33645, "text": "29AjayKumar" }, { "code": null, "e": 33667, "s": 33657, "text": "Rajput-Ji" }, { "code": null, "e": 33679, "s": 33667, "text": "sanjeev2552" }, { "code": null, "e": 33686, "s": 33679, "text": "rdtank" }, { "code": null, "e": 33700, "s": 33686, "text": "Goldman Sachs" }, { "code": null, "e": 33714, "s": 33700, "text": "Combinatorial" }, { "code": null, "e": 33722, "s": 33714, "text": "Strings" }, { "code": null, "e": 33736, "s": 33722, "text": "Goldman Sachs" }, { "code": null, "e": 33744, "s": 33736, "text": "Strings" }, { "code": null, "e": 33758, "s": 33744, "text": "Combinatorial" }, { "code": null, "e": 33856, "s": 33758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33928, "s": 33856, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 33991, "s": 33928, "text": "Generate all possible combinations of K numbers that sums to N" }, { "code": null, "e": 34021, "s": 33991, "text": "Combinations with repetitions" }, { "code": null, "e": 34060, "s": 34021, "text": "Largest substring with same Characters" }, { "code": null, "e": 34138, "s": 34060, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 34184, "s": 34138, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34209, "s": 34184, "text": "Reverse a string in Java" }, { "code": null, "e": 34224, "s": 34209, "text": "C++ Data Types" }, { "code": null, "e": 34258, "s": 34224, "text": "Longest Common Subsequence | DP-4" } ]
Check if the given decimal number has 0 and 1 digits only - GeeksforGeeks
26 May, 2021 Given an integer n, the task is to check whether n is in binary or not. Print true if n is the binary representation else print false. Examples: Input: n = 1000111 Output: true Input: n = 123 Output: false Method #1: Using Set First add all the digits of n into a set after that remove 0 and 1 from the set, if the size of the set becomes 0 then the number is in binary format. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check whether the given number// is in binary format#include<bits/stdc++.h>using namespace std; // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's bool isBinary(int number) { set<int> set; // Put all the digits of the number in the set while (number > 0) { int digit = number % 10; set.insert(digit); number /= 10; } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.erase(0); set.erase(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.size() == 0) { return true; } return false; } // Driver code int main() { int n = 1000111; if(isBinary(n)==1) cout<<"true"<<endl; else cout<<"No"<<endl; }//contributed by Arnab Kundu // Java program to check whether the given number// is in binary formatimport java.util.HashSet;import java.util.Set; class GFG { // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's static boolean isBinary(int number) { Set<Integer> set = new HashSet<>(); // Put all the digits of the number in the set while (number > 0) { int digit = number % 10; set.add(digit); number /= 10; } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.remove(0); set.remove(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.size() == 0) { return true; } return false; } // Driver code public static void main(String a[]) { int n = 1000111; System.out.println(isBinary(n)); }} # Python 3 program to check whether# the given number is in binary format # Function that returns true if given# number is in binary format i.e. number# contains only 0's and/or 1'sdef isBinary(number): set1 = set() # Put all the digits of the # number in the set while(number > 0): digit = number % 10 set1.add(digit) number = int(number / 10) # Since a HashSet does not allow # duplicates so only a single copy # of '0' and '1' will be stored set1.discard(0) set1.discard(1) # If the original number only # contained 0's and 1's then # size of the set must be 0 if (len(set1) == 0): return True return False # Driver codeif __name__ == '__main__': n = 1000111 if(isBinary(n) == 1): print("true") else: print("No") # This code is contributed by# Surendra_Gangwar // C# program to check whether the given number// is in binary formatusing System;using System.Collections.Generic;public class GFG { // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's static bool isBinary(int number) { HashSet<int> set = new HashSet<int>(); // Put all the digits of the number in the set while (number > 0) { int digit = number % 10; set.Add(digit); number /= 10; } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.Remove(0); set.Remove(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.Count == 0) { return true; } return false; } // Driver code public static void Main() { int n = 1000111; Console.WriteLine(isBinary(n)); }}//This code is contributed by Rajput-Ji <script>// Javascript program to check whether the given number// is in binary format // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's function isBinary(number) { let set = new Set(); // Put all the digits of the number in the set while (number > 0) { let digit = number % 10; set.add(digit); number = Math.floor(number/10); } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.delete(0); set.delete(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.size == 0) { return true; } return false; } // Driver code let n = 1000111; document.write(isBinary(n)); // This code is contributed by rag2127</script> true Method #2: Native Way C++ Java Python3 C# PHP Javascript // C++ program to check whether the// given number is in binary format#include<bits/stdc++.h>using namespace std; // Function that returns true if// given number is in binary format// i.e. number contains only 0's and/or 1'sint isBinary(int number){ while (number > 0) { int digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number /= 10; } return true;} // Driver codeint main(){ int n = 1000111; if (isBinary(n) == 1) cout << "true"; else cout << "false"; // This code is contributed// by Shivi_Aggarwal} // Java program to check whether the// given number is in binary format class GFG { // Function that returns true if // given number is in binary format // i.e. number contains only 0's and/or 1's static boolean isBinary(int number) { while (number > 0) { int digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number /= 10; } return true; } // Driver code public static void main(String a[]) { int n = 1000111; System.out.println(isBinary(n)); }} # Python3 program to check whether the# given number is in binary format # Function that returns true if# given number is in binary format# i.e. number contains only 0's and/or 1'sdef isBinary(number): while (number > 0): digit = number % 10 # If digit is other than 0 and 1 if (digit > 1): return False number //= 10 return True # Driver codeif __name__ == "__main__": n = 1000111 if (isBinary(n) == 1): print ("true") else: print ("false") # This code is contributed by ita_c // C# program to check whether the// given number is in binary format using System; class GFG { // Function that returns true if // given number is in binary format // i.e. number contains only 0's and/or 1's static bool isBinary(int number) { while (number > 0) { int digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number /= 10; } return true; } // Driver code static void Main() { int n = 1000111; Console.WriteLine(isBinary(n)); } // This code is contributed by Ryuga} <?php// PHP program to check whether the// given number is in binary format // Function that returns true if// given number is in binary format// i.e. number contains only 0's and/or 1'sfunction isBinary($number){ while ($number > 0) { $digit = $number % 10; // If digit is other than 0 and 1 if ($digit > 1) return false; $number /= 10; } return true;} // Driver code$n = 1000111;if (isBinary($n) == 1) echo "true";else echo "false"; // This code is contributed// by Mukul Singh <script> // Javascript program to check whether the// given number is in binary format // Function that returns true if// given number is in binary format// i.e. number contains only 0's and/or 1'sfunction isBinary(number){ while (number > 0) { let digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number = Math.floor(number / 10); } return true;} // Driver codelet n = 1000111; document.write(isBinary(n)); // This code is contributed by avanitrachhadiya2155 </script> true ankthon Code_Mech ukasp Shivi_Aggarwal andrew1234 SURENDRA_GANGWAR Rajput-Ji rag2127 avanitrachhadiya2155 number-digits Technical Scripter 2018 Java Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Java Program to Read a File to String How to Replace a Element in Java ArrayList? Java Program to Find Sum of Array Elements How to Write Data into Excel Sheet using Java? Removing last element from ArrayList in Java Tic-Tac-Toe Game in Java Java Program to Write an Array of Strings to the Output Console
[ { "code": null, "e": 26131, "s": 26103, "text": "\n26 May, 2021" }, { "code": null, "e": 26266, "s": 26131, "text": "Given an integer n, the task is to check whether n is in binary or not. Print true if n is the binary representation else print false." }, { "code": null, "e": 26277, "s": 26266, "text": "Examples: " }, { "code": null, "e": 26309, "s": 26277, "text": "Input: n = 1000111 Output: true" }, { "code": null, "e": 26340, "s": 26309, "text": "Input: n = 123 Output: false " }, { "code": null, "e": 26512, "s": 26340, "text": "Method #1: Using Set First add all the digits of n into a set after that remove 0 and 1 from the set, if the size of the set becomes 0 then the number is in binary format." }, { "code": null, "e": 26565, "s": 26512, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26569, "s": 26565, "text": "C++" }, { "code": null, "e": 26574, "s": 26569, "text": "Java" }, { "code": null, "e": 26582, "s": 26574, "text": "Python3" }, { "code": null, "e": 26585, "s": 26582, "text": "C#" }, { "code": null, "e": 26596, "s": 26585, "text": "Javascript" }, { "code": "// C++ program to check whether the given number// is in binary format#include<bits/stdc++.h>using namespace std; // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's bool isBinary(int number) { set<int> set; // Put all the digits of the number in the set while (number > 0) { int digit = number % 10; set.insert(digit); number /= 10; } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.erase(0); set.erase(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.size() == 0) { return true; } return false; } // Driver code int main() { int n = 1000111; if(isBinary(n)==1) cout<<\"true\"<<endl; else cout<<\"No\"<<endl; }//contributed by Arnab Kundu", "e": 27616, "s": 26596, "text": null }, { "code": "// Java program to check whether the given number// is in binary formatimport java.util.HashSet;import java.util.Set; class GFG { // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's static boolean isBinary(int number) { Set<Integer> set = new HashSet<>(); // Put all the digits of the number in the set while (number > 0) { int digit = number % 10; set.add(digit); number /= 10; } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.remove(0); set.remove(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.size() == 0) { return true; } return false; } // Driver code public static void main(String a[]) { int n = 1000111; System.out.println(isBinary(n)); }}", "e": 28620, "s": 27616, "text": null }, { "code": "# Python 3 program to check whether# the given number is in binary format # Function that returns true if given# number is in binary format i.e. number# contains only 0's and/or 1'sdef isBinary(number): set1 = set() # Put all the digits of the # number in the set while(number > 0): digit = number % 10 set1.add(digit) number = int(number / 10) # Since a HashSet does not allow # duplicates so only a single copy # of '0' and '1' will be stored set1.discard(0) set1.discard(1) # If the original number only # contained 0's and 1's then # size of the set must be 0 if (len(set1) == 0): return True return False # Driver codeif __name__ == '__main__': n = 1000111 if(isBinary(n) == 1): print(\"true\") else: print(\"No\") # This code is contributed by# Surendra_Gangwar", "e": 29489, "s": 28620, "text": null }, { "code": " // C# program to check whether the given number// is in binary formatusing System;using System.Collections.Generic;public class GFG { // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's static bool isBinary(int number) { HashSet<int> set = new HashSet<int>(); // Put all the digits of the number in the set while (number > 0) { int digit = number % 10; set.Add(digit); number /= 10; } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.Remove(0); set.Remove(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.Count == 0) { return true; } return false; } // Driver code public static void Main() { int n = 1000111; Console.WriteLine(isBinary(n)); }}//This code is contributed by Rajput-Ji", "e": 30534, "s": 29489, "text": null }, { "code": "<script>// Javascript program to check whether the given number// is in binary format // Function that returns true if given number // is in binary format i.e. number contains // only 0's and/or 1's function isBinary(number) { let set = new Set(); // Put all the digits of the number in the set while (number > 0) { let digit = number % 10; set.add(digit); number = Math.floor(number/10); } // Since a HashSet does not allow duplicates so only // a single copy of '0' and '1' will be stored set.delete(0); set.delete(1); // If the original number only contained 0's and 1's // then size of the set must be 0 if (set.size == 0) { return true; } return false; } // Driver code let n = 1000111; document.write(isBinary(n)); // This code is contributed by rag2127</script>", "e": 31494, "s": 30534, "text": null }, { "code": null, "e": 31499, "s": 31494, "text": "true" }, { "code": null, "e": 31524, "s": 31501, "text": "Method #2: Native Way " }, { "code": null, "e": 31528, "s": 31524, "text": "C++" }, { "code": null, "e": 31533, "s": 31528, "text": "Java" }, { "code": null, "e": 31541, "s": 31533, "text": "Python3" }, { "code": null, "e": 31544, "s": 31541, "text": "C#" }, { "code": null, "e": 31548, "s": 31544, "text": "PHP" }, { "code": null, "e": 31559, "s": 31548, "text": "Javascript" }, { "code": "// C++ program to check whether the// given number is in binary format#include<bits/stdc++.h>using namespace std; // Function that returns true if// given number is in binary format// i.e. number contains only 0's and/or 1'sint isBinary(int number){ while (number > 0) { int digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number /= 10; } return true;} // Driver codeint main(){ int n = 1000111; if (isBinary(n) == 1) cout << \"true\"; else cout << \"false\"; // This code is contributed// by Shivi_Aggarwal}", "e": 32161, "s": 31559, "text": null }, { "code": "// Java program to check whether the// given number is in binary format class GFG { // Function that returns true if // given number is in binary format // i.e. number contains only 0's and/or 1's static boolean isBinary(int number) { while (number > 0) { int digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number /= 10; } return true; } // Driver code public static void main(String a[]) { int n = 1000111; System.out.println(isBinary(n)); }}", "e": 32769, "s": 32161, "text": null }, { "code": "# Python3 program to check whether the# given number is in binary format # Function that returns true if# given number is in binary format# i.e. number contains only 0's and/or 1'sdef isBinary(number): while (number > 0): digit = number % 10 # If digit is other than 0 and 1 if (digit > 1): return False number //= 10 return True # Driver codeif __name__ == \"__main__\": n = 1000111 if (isBinary(n) == 1): print (\"true\") else: print (\"false\") # This code is contributed by ita_c", "e": 33323, "s": 32769, "text": null }, { "code": "// C# program to check whether the// given number is in binary format using System; class GFG { // Function that returns true if // given number is in binary format // i.e. number contains only 0's and/or 1's static bool isBinary(int number) { while (number > 0) { int digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number /= 10; } return true; } // Driver code static void Main() { int n = 1000111; Console.WriteLine(isBinary(n)); } // This code is contributed by Ryuga}", "e": 33962, "s": 33323, "text": null }, { "code": "<?php// PHP program to check whether the// given number is in binary format // Function that returns true if// given number is in binary format// i.e. number contains only 0's and/or 1'sfunction isBinary($number){ while ($number > 0) { $digit = $number % 10; // If digit is other than 0 and 1 if ($digit > 1) return false; $number /= 10; } return true;} // Driver code$n = 1000111;if (isBinary($n) == 1) echo \"true\";else echo \"false\"; // This code is contributed// by Mukul Singh", "e": 34500, "s": 33962, "text": null }, { "code": "<script> // Javascript program to check whether the// given number is in binary format // Function that returns true if// given number is in binary format// i.e. number contains only 0's and/or 1'sfunction isBinary(number){ while (number > 0) { let digit = number % 10; // If digit is other than 0 and 1 if (digit > 1) return false; number = Math.floor(number / 10); } return true;} // Driver codelet n = 1000111; document.write(isBinary(n)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 35074, "s": 34500, "text": null }, { "code": null, "e": 35079, "s": 35074, "text": "true" }, { "code": null, "e": 35089, "s": 35081, "text": "ankthon" }, { "code": null, "e": 35099, "s": 35089, "text": "Code_Mech" }, { "code": null, "e": 35105, "s": 35099, "text": "ukasp" }, { "code": null, "e": 35120, "s": 35105, "text": "Shivi_Aggarwal" }, { "code": null, "e": 35131, "s": 35120, "text": "andrew1234" }, { "code": null, "e": 35148, "s": 35131, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 35158, "s": 35148, "text": "Rajput-Ji" }, { "code": null, "e": 35166, "s": 35158, "text": "rag2127" }, { "code": null, "e": 35187, "s": 35166, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35201, "s": 35187, "text": "number-digits" }, { "code": null, "e": 35225, "s": 35201, "text": "Technical Scripter 2018" }, { "code": null, "e": 35239, "s": 35225, "text": "Java Programs" }, { "code": null, "e": 35258, "s": 35239, "text": "Technical Scripter" }, { "code": null, "e": 35356, "s": 35258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35404, "s": 35356, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 35455, "s": 35404, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 35489, "s": 35455, "text": "Java Program to Write into a File" }, { "code": null, "e": 35527, "s": 35489, "text": "Java Program to Read a File to String" }, { "code": null, "e": 35571, "s": 35527, "text": "How to Replace a Element in Java ArrayList?" }, { "code": null, "e": 35614, "s": 35571, "text": "Java Program to Find Sum of Array Elements" }, { "code": null, "e": 35661, "s": 35614, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 35706, "s": 35661, "text": "Removing last element from ArrayList in Java" }, { "code": null, "e": 35731, "s": 35706, "text": "Tic-Tac-Toe Game in Java" } ]
Replace every element with the greatest element on right side - GeeksforGeeks
17 Jan, 2022 Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is {16, 17, 4, 3, 5, 2}, then it should be modified to {17, 5, 5, 5, 2, -1}. The question is very similar to this post and solutions are also similar. A naive method is to run two loops. The outer loop will one by one pick array elements from left to right. The inner loop will find the greatest element present after the picked element. Finally the outer loop will replace the picked element with the greatest element found by inner loop. The time complexity of this method will be O(n*n). A tricky method is to replace all elements using one traversal of the array. The idea is to start from the rightmost element, move to the left side one by one, and keep track of the maximum element. Replace every element with the maximum element. C++ C Java Python3 C# PHP Javascript // C++ Program to replace every element with the greatest// element on right side#include <bits/stdc++.h>using namespace std; /* Function to replace every element with thenext greatest element */void nextGreatest(int arr[], int size){ //Initialise maxFromRight with -1 int maxFromRight = -1; int n = arr.length; // run loop from last and replace maxFromRight with the element in the array for(int i= n-1; i>=0;i--) { int temp = maxFromRight; if(arr[i]> maxFromRight){ //replacing only array element with maxFromRight in case element is bigger maxFromRight = arr[i]; } arr[i] = temp; } return arr;} /* A utility Function that prints an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) cout << arr[i] << " "; cout << endl;} /* Driver program to test above function */int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int size = sizeof(arr)/sizeof(arr[0]); nextGreatest (arr, size); cout << "The modified array is: \n"; printArray (arr, size); return (0);} // This is code is contributed by rathbhupendra // C Program to replace every element with the greatest// element on right side#include <stdio.h> /* Function to replace every element with the next greatest element */void nextGreatest(int arr[], int size){ // Initialize the next greatest element int max_from_right = arr[size-1]; // The next greatest element for the rightmost element // is always -1 arr[size-1] = -1; // Replace all other elements with the next greatest for(int i = size-2; i >= 0; i--) { // Store the current element (needed later for updating // the next greatest element) int temp = arr[i]; // Replace current element with the next greatest arr[i] = max_from_right; // Update the greatest element, if needed if(max_from_right < temp) max_from_right = temp; }} /* A utility Function that prints an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n");} /* Driver program to test above function */int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int size = sizeof(arr)/sizeof(arr[0]); nextGreatest (arr, size); printf ("The modified array is: \n"); printArray (arr, size); return (0);} // Java Program to replace every element with the// greatest element on right sideimport java.io.*; class NextGreatest{ /* Function to replace every element with the next greatest element */ static void nextGreatest(int arr[]) { int size = arr.length; // Initialize the next greatest element int max_from_right = arr[size-1]; // The next greatest element for the rightmost // element is always -1 arr[size-1] = -1; // Replace all other elements with the next greatest for (int i = size-2; i >= 0; i--) { // Store the current element (needed later for // updating the next greatest element) int temp = arr[i]; // Replace current element with the next greatest arr[i] = max_from_right; // Update the greatest element, if needed if(max_from_right < temp) max_from_right = temp; } } /* A utility Function that prints an array */ static void printArray(int arr[]) { for (int i=0; i < arr.length; i++) System.out.print(arr[i]+" "); } public static void main (String[] args) { int arr[] = {16, 17, 4, 3, 5, 2}; nextGreatest (arr); System.out.println("The modified array:"); printArray (arr); }}/*This code is contributed by Devesh Agrawal*/ # Python Program to replace every element with the# greatest element on right side # Function to replace every element with the next greatest# elementdef nextGreatest(arr): size = len(arr) # Initialize the next greatest element max_from_right = arr[size-1] # The next greatest element for the rightmost element # is always -1 arr[size-1] = -1 # Replace all other elements with the next greatest for i in range(size-2,-1,-1): # Store the current element (needed later for updating # the next greatest element) temp = arr[i] # Replace current element with the next greatest arr[i]=max_from_right # Update the greatest element, if needed if max_from_right< temp: max_from_right=temp # Utility function to print an arraydef printArray(arr): for i in range(0,len(arr)): print (arr[i],end=" ") # Driver function to test above functionarr = [16, 17, 4, 3, 5, 2]nextGreatest(arr)print ("Modified array is")printArray(arr)# This code is contributed by Devesh Agrawal // C# Program to replace every element with the// greatest element on right sideusing System; class GFG { /* Function to replace every element with the next greatest element */ static void nextGreatest(int []arr) { int size = arr.Length; // Initialize the next greatest element int max_from_right = arr[size-1]; // The next greatest element for the // rightmost element is always -1 arr[size-1] = -1; // Replace all other elements with the // next greatest for (int i = size-2; i >= 0; i--) { // Store the current element (needed // later for updating the next // greatest element) int temp = arr[i]; // Replace current element with // the next greatest arr[i] = max_from_right; // Update the greatest element, if // needed if(max_from_right < temp) max_from_right = temp; } } /* A utility Function that prints an array */ static void printArray(int []arr) { for (int i=0; i < arr.Length; i++) Console.Write(arr[i]+" "); } public static void Main () { int []arr = {16, 17, 4, 3, 5, 2}; nextGreatest (arr); Console.WriteLine("The modified array:"); printArray (arr); }} /* This code is contributed by vt_m.*/ <?php// PHP Program to replace every element with// the greatest element on right side /* Function to replace every elementwith the next greatest element */function nextGreatest(&$arr, $size){ // Initialize the next greatest element $max_from_right = $arr[$size - 1]; // The next greatest element for the // rightmost element is always -1 $arr[$size - 1] = -1; // Replace all other elements with // the next greatest for($i = $size - 2; $i >= 0; $i--) { // Store the current element (needed // later for updating the next // greatest element) $temp = $arr[$i]; // Replace current element with the // next greatest $arr[$i] = $max_from_right; // Update the greatest element, // if needed if($max_from_right < $temp) $max_from_right = $temp; }} // A utility Function that prints an arrayfunction printArray($arr, $size){ for ($i = 0; $i < $size; $i++) echo $arr[$i] . " "; echo "\n";} // Driver Code$arr = array(16, 17, 4, 3, 5, 2);$size = count($arr);nextGreatest ($arr, $size);echo "The modified array is: \n";printArray ($arr, $size); // This code is contributed by// rathbhupendra?> <script> // JavaScript Program to replace every element with the greatest// element on right side /* Function to replace every element with thenext greatest element */ function nextGreatest(arr,size){ // Initialize the next greatest element max_from_right = arr[size-1]; // The next greatest element for the rightmost element // is always -1 arr[size-1] = -1; // Replace all other elements with the next greatest for(let i = size-2; i >= 0; i--) { // Store the current element (needed later for updating // the next greatest element) temp = arr[i]; // Replace current element with the next greatest arr[i] = max_from_right; // Update the greatest element, if needed if(max_from_right < temp) max_from_right = temp; }} /* A utility Function that prints an array */ function printArray(arr,size){ var i; for ( let i = 0; i < size; i++) document.write(arr[i] + " " );} /* Driver program to test above function */ arr = new Array (16, 17, 4, 3, 5, 2); size = arr.length; nextGreatest (arr, size); document.write ("The modified array is: " + "<br>"+ " \n"); printArray (arr, size); // This code is contributed by simranarora5sos </script> Output: The modified array is: 17 5 5 5 2 -1 Time Complexity: O(n) where n is the number of elements in array. YouTubeGeeksforGeeks507K subscribersReplace every element with the greatest element on right side | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:19•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bLb8e83OK7o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. rathbhupendra simranarora5sos rajeevkri sweetyty amartyaghoshgfg Amazon Arrays Amazon Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 26481, "s": 26453, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26790, "s": 26481, "text": "Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is {16, 17, 4, 3, 5, 2}, then it should be modified to {17, 5, 5, 5, 2, -1}. " }, { "code": null, "e": 27453, "s": 26790, "text": "The question is very similar to this post and solutions are also similar. A naive method is to run two loops. The outer loop will one by one pick array elements from left to right. The inner loop will find the greatest element present after the picked element. Finally the outer loop will replace the picked element with the greatest element found by inner loop. The time complexity of this method will be O(n*n). A tricky method is to replace all elements using one traversal of the array. The idea is to start from the rightmost element, move to the left side one by one, and keep track of the maximum element. Replace every element with the maximum element. " }, { "code": null, "e": 27457, "s": 27453, "text": "C++" }, { "code": null, "e": 27459, "s": 27457, "text": "C" }, { "code": null, "e": 27464, "s": 27459, "text": "Java" }, { "code": null, "e": 27472, "s": 27464, "text": "Python3" }, { "code": null, "e": 27475, "s": 27472, "text": "C#" }, { "code": null, "e": 27479, "s": 27475, "text": "PHP" }, { "code": null, "e": 27490, "s": 27479, "text": "Javascript" }, { "code": "// C++ Program to replace every element with the greatest// element on right side#include <bits/stdc++.h>using namespace std; /* Function to replace every element with thenext greatest element */void nextGreatest(int arr[], int size){ //Initialise maxFromRight with -1 int maxFromRight = -1; int n = arr.length; // run loop from last and replace maxFromRight with the element in the array for(int i= n-1; i>=0;i--) { int temp = maxFromRight; if(arr[i]> maxFromRight){ //replacing only array element with maxFromRight in case element is bigger maxFromRight = arr[i]; } arr[i] = temp; } return arr;} /* A utility Function that prints an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} /* Driver program to test above function */int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int size = sizeof(arr)/sizeof(arr[0]); nextGreatest (arr, size); cout << \"The modified array is: \\n\"; printArray (arr, size); return (0);} // This is code is contributed by rathbhupendra", "e": 28610, "s": 27490, "text": null }, { "code": "// C Program to replace every element with the greatest// element on right side#include <stdio.h> /* Function to replace every element with the next greatest element */void nextGreatest(int arr[], int size){ // Initialize the next greatest element int max_from_right = arr[size-1]; // The next greatest element for the rightmost element // is always -1 arr[size-1] = -1; // Replace all other elements with the next greatest for(int i = size-2; i >= 0; i--) { // Store the current element (needed later for updating // the next greatest element) int temp = arr[i]; // Replace current element with the next greatest arr[i] = max_from_right; // Update the greatest element, if needed if(max_from_right < temp) max_from_right = temp; }} /* A utility Function that prints an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} /* Driver program to test above function */int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int size = sizeof(arr)/sizeof(arr[0]); nextGreatest (arr, size); printf (\"The modified array is: \\n\"); printArray (arr, size); return (0);}", "e": 29780, "s": 28610, "text": null }, { "code": "// Java Program to replace every element with the// greatest element on right sideimport java.io.*; class NextGreatest{ /* Function to replace every element with the next greatest element */ static void nextGreatest(int arr[]) { int size = arr.length; // Initialize the next greatest element int max_from_right = arr[size-1]; // The next greatest element for the rightmost // element is always -1 arr[size-1] = -1; // Replace all other elements with the next greatest for (int i = size-2; i >= 0; i--) { // Store the current element (needed later for // updating the next greatest element) int temp = arr[i]; // Replace current element with the next greatest arr[i] = max_from_right; // Update the greatest element, if needed if(max_from_right < temp) max_from_right = temp; } } /* A utility Function that prints an array */ static void printArray(int arr[]) { for (int i=0; i < arr.length; i++) System.out.print(arr[i]+\" \"); } public static void main (String[] args) { int arr[] = {16, 17, 4, 3, 5, 2}; nextGreatest (arr); System.out.println(\"The modified array:\"); printArray (arr); }}/*This code is contributed by Devesh Agrawal*/", "e": 31161, "s": 29780, "text": null }, { "code": "# Python Program to replace every element with the# greatest element on right side # Function to replace every element with the next greatest# elementdef nextGreatest(arr): size = len(arr) # Initialize the next greatest element max_from_right = arr[size-1] # The next greatest element for the rightmost element # is always -1 arr[size-1] = -1 # Replace all other elements with the next greatest for i in range(size-2,-1,-1): # Store the current element (needed later for updating # the next greatest element) temp = arr[i] # Replace current element with the next greatest arr[i]=max_from_right # Update the greatest element, if needed if max_from_right< temp: max_from_right=temp # Utility function to print an arraydef printArray(arr): for i in range(0,len(arr)): print (arr[i],end=\" \") # Driver function to test above functionarr = [16, 17, 4, 3, 5, 2]nextGreatest(arr)print (\"Modified array is\")printArray(arr)# This code is contributed by Devesh Agrawal", "e": 32220, "s": 31161, "text": null }, { "code": "// C# Program to replace every element with the// greatest element on right sideusing System; class GFG { /* Function to replace every element with the next greatest element */ static void nextGreatest(int []arr) { int size = arr.Length; // Initialize the next greatest element int max_from_right = arr[size-1]; // The next greatest element for the // rightmost element is always -1 arr[size-1] = -1; // Replace all other elements with the // next greatest for (int i = size-2; i >= 0; i--) { // Store the current element (needed // later for updating the next // greatest element) int temp = arr[i]; // Replace current element with // the next greatest arr[i] = max_from_right; // Update the greatest element, if // needed if(max_from_right < temp) max_from_right = temp; } } /* A utility Function that prints an array */ static void printArray(int []arr) { for (int i=0; i < arr.Length; i++) Console.Write(arr[i]+\" \"); } public static void Main () { int []arr = {16, 17, 4, 3, 5, 2}; nextGreatest (arr); Console.WriteLine(\"The modified array:\"); printArray (arr); }} /* This code is contributed by vt_m.*/", "e": 33619, "s": 32220, "text": null }, { "code": "<?php// PHP Program to replace every element with// the greatest element on right side /* Function to replace every elementwith the next greatest element */function nextGreatest(&$arr, $size){ // Initialize the next greatest element $max_from_right = $arr[$size - 1]; // The next greatest element for the // rightmost element is always -1 $arr[$size - 1] = -1; // Replace all other elements with // the next greatest for($i = $size - 2; $i >= 0; $i--) { // Store the current element (needed // later for updating the next // greatest element) $temp = $arr[$i]; // Replace current element with the // next greatest $arr[$i] = $max_from_right; // Update the greatest element, // if needed if($max_from_right < $temp) $max_from_right = $temp; }} // A utility Function that prints an arrayfunction printArray($arr, $size){ for ($i = 0; $i < $size; $i++) echo $arr[$i] . \" \"; echo \"\\n\";} // Driver Code$arr = array(16, 17, 4, 3, 5, 2);$size = count($arr);nextGreatest ($arr, $size);echo \"The modified array is: \\n\";printArray ($arr, $size); // This code is contributed by// rathbhupendra?>", "e": 34844, "s": 33619, "text": null }, { "code": "<script> // JavaScript Program to replace every element with the greatest// element on right side /* Function to replace every element with thenext greatest element */ function nextGreatest(arr,size){ // Initialize the next greatest element max_from_right = arr[size-1]; // The next greatest element for the rightmost element // is always -1 arr[size-1] = -1; // Replace all other elements with the next greatest for(let i = size-2; i >= 0; i--) { // Store the current element (needed later for updating // the next greatest element) temp = arr[i]; // Replace current element with the next greatest arr[i] = max_from_right; // Update the greatest element, if needed if(max_from_right < temp) max_from_right = temp; }} /* A utility Function that prints an array */ function printArray(arr,size){ var i; for ( let i = 0; i < size; i++) document.write(arr[i] + \" \" );} /* Driver program to test above function */ arr = new Array (16, 17, 4, 3, 5, 2); size = arr.length; nextGreatest (arr, size); document.write (\"The modified array is: \" + \"<br>\"+ \" \\n\"); printArray (arr, size); // This code is contributed by simranarora5sos </script>", "e": 36167, "s": 34844, "text": null }, { "code": null, "e": 36176, "s": 36167, "text": "Output: " }, { "code": null, "e": 36213, "s": 36176, "text": "The modified array is:\n17 5 5 5 2 -1" }, { "code": null, "e": 36280, "s": 36213, "text": "Time Complexity: O(n) where n is the number of elements in array. " }, { "code": null, "e": 37140, "s": 36280, "text": "YouTubeGeeksforGeeks507K subscribersReplace every element with the greatest element on right side | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:19•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=bLb8e83OK7o\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 37266, "s": 37140, "text": "Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 37280, "s": 37266, "text": "rathbhupendra" }, { "code": null, "e": 37296, "s": 37280, "text": "simranarora5sos" }, { "code": null, "e": 37306, "s": 37296, "text": "rajeevkri" }, { "code": null, "e": 37315, "s": 37306, "text": "sweetyty" }, { "code": null, "e": 37331, "s": 37315, "text": "amartyaghoshgfg" }, { "code": null, "e": 37338, "s": 37331, "text": "Amazon" }, { "code": null, "e": 37345, "s": 37338, "text": "Arrays" }, { "code": null, "e": 37352, "s": 37345, "text": "Amazon" }, { "code": null, "e": 37359, "s": 37352, "text": "Arrays" }, { "code": null, "e": 37457, "s": 37359, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37525, "s": 37457, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37569, "s": 37525, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37617, "s": 37569, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37640, "s": 37617, "text": "Introduction to Arrays" }, { "code": null, "e": 37672, "s": 37640, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37686, "s": 37672, "text": "Linear Search" }, { "code": null, "e": 37707, "s": 37686, "text": "Linked List vs Array" }, { "code": null, "e": 37792, "s": 37707, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37837, "s": 37792, "text": "Python | Using 2D arrays/lists the right way" } ]
Minimum edges to reverse to make path from a source to a destination - GeeksforGeeks
04 Mar, 2022 Given a directed graph and a source node and destination node, we need to find how many edges we need to reverse in order to make at least 1 path from the source node to the destination node. Examples: In above graph there were two paths from node 0 to node 6, 0 -> 1 -> 2 -> 3 -> 6 0 -> 1 -> 5 -> 4 -> 6 But for first path only two edges need to be reversed, so answer will be 2 only. This problem can be solved assuming a different version of the given graph. In this version we make a reverse edge corresponding to every edge and we assign that a weight 1 and assign a weight 0 to original edge. After this modification above graph looks something like below, Now we can see that we have modified the graph in such a way that, if we move towards original edge, no cost is incurred, but if we move toward reverse edge 1 cost is added. So if we apply Dijkstra’s shortest path on this modified graph from given source, then that will give us minimum cost to reach from source to destination i.e. minimum edge reversal from source to destination. Below is the code based on above concept. C++ Java Python3 // C++ Program to find minimum edge reversal to get// atleast one path from source to destination#include <bits/stdc++.h>using namespace std;#define INF 0x3f3f3f3f // This class represents a directed graph using// adjacency list representationclass Graph{ int V; list<pair<int, int>> *graph; public: // Constructor: Graph(int V) { this->V = V; graph = new list<pair<int, int>>[V]; } // Adding edges into the graph: void addEdge(int u, int v, int w) { graph[u].push_back(make_pair(v, w)); } // Returns shortest path from source to all other vertices. vector<int> shortestPath(int source) { // Create a set to store vertices that are being preprocessed set<pair<int, int>> setds; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> distance(V, INF); // Insert source itself in Set and initialize its distance as 0. setds.insert(make_pair(0, source)); distance = 0; /* Looping till all shortest distance are finalized then setds will become empty */ while (!setds.empty()) { // The first vertex in Set is the minimum distance // vertex, extract it from set. pair<int, int> tmp = *(setds.begin()); setds.erase(setds.begin()); // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; list<pair<int, int>>::iterator i; for (i = graph[u].begin(); i != graph[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If there is shorter path to v through u. if (distance[v] > distance[u] + weight) { /* If distance of v is not INF then it must be in our set, so removing it and inserting again with updated less distance. Note : We extract only those vertices from Set for which distance is finalized. So for them, we would never reach here. */ if (distance[v] != INF) setds.erase(setds.find(make_pair(distance[v], v))); // Updating distance of v distance[v] = distance[u] + weight; setds.insert(make_pair(distance[v], v)); } } } return distance; } Graph modelGraphWithEdgeWeight(int edge[][2], int E, int V) { Graph g(V); for (int i = 0; i < E; i++) { // original edge : weight 0 g.addEdge(edge[i][0], edge[i][1], 0); // reverse edge : weight 1 g.addEdge(edge[i][1], edge[i][0], 1); } return g; } int getMinEdgeReversal(int edge[][2], int E, int V, int source, int destination) { // get modified graph with edge weight. Graph g = modelGraphWithEdgeWeight(edge, E, V); // distance vector stores shortest path. vector<int> dist = g.shortestPath(source); // If distance of destination is still INF then we cannot reach destination. Hence, not possible. if (dist[destination] == INF) return -1; else return dist[destination]; }}; int main(){ int V = 7; Graph g(V); int edge[][2] = {{0, 1}, {2, 1}, {2, 3}, {5, 1}, {4, 5}, {6, 4}, {6, 3}}; int E = sizeof(edge) / sizeof(edge[0]); int minEdgeToReverse = g.getMinEdgeReversal(edge, E, V, 0, 6); if (minEdgeToReverse != -1) cout << minEdgeToReverse << endl; else cout << "Not Possible." << endl; return 0;} // Java program to find minimum edge reversal to get// atleast one path from source to destinationimport java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set; class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} // This class represents a directed graph using// adjacency list representationclass Graph{ final int INF = (int)0x3f3f3f3f; // No. of verticesint V; // In a weighted graph, we need to store vertex// and weight pair for every edgeList<Pair>[] adj; // Allocates memory for adjacency list@SuppressWarnings("unchecked")public Graph(int V){ this.V = V; adj = new ArrayList[V]; for(int i = 0; i < V; i++) { adj[i] = new ArrayList(); }} // Function adds a directed edge from// u to v with weight wvoid addEdge(int u, int v, int w){ adj[u].add(new Pair(v, w));} // Prints shortest paths from// src to all other verticesint[] shortestPath(int src){ // Create a set to store vertices // that are being preprocessed Set<Pair> setds = new HashSet<Pair>(); // Create a vector for distances and // initialize all distances as infinite(INF) int[] dist = new int[V]; Arrays.fill(dist, INF); // Insert source itself in Set and initialize // its distance as 0. setds.add(new Pair(0, src)); dist[src] = 0; // Looping till all shortest distance are // finalized then setds will become empty while (!setds.isEmpty()) { // The first vertex in Set is the minimum // distance vertex, extract it from set. Iterator<Pair> itr = setds.iterator(); Pair tmp = itr.next(); itr.remove(); // Vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; // 'i' is used to get all adjacent // vertices of a vertex for(Pair p : adj[u]) { // Get vertex label and weight of // current adjacent of u. int v = p.first; int weight = p.second; // If there is shorter path to v through u. if (dist[v] > dist[u] + weight) { // If distance of v is not INF then it // must be in our set, so removing it // and inserting again with updated // less distance. Note : We extract // only those vertices from Set for // which distance is finalized. So // for them, we would never reach here. if (dist[v] != INF) { setds.remove(new Pair(dist[v], v)); } // setds.erase(setds.find(new Pair(dist[v], v))); // Updating distance of v dist[v] = dist[u] + weight; setds.add(new Pair(dist[v], v)); } } } return dist;}} class GFG{static final int INF = (int)0x3f3f3f3f; // Function adds reverse edge of each original// edge in the graph. It gives reverse edge// a weight = 1 and all original edges a// weight of 0. Now, the length of the// shortest path will give us the answer.// If shortest path is p: it means we// used p reverse edges in the shortest path.static Graph modelGraphWithEdgeWeight(int edge[][], int E, int V){ Graph g = new Graph(V); for(int i = 0; i < E; i++) { // Original edge : weight 0 g.addEdge(edge[i][0], edge[i][1], 0); // Reverse edge : weight 1 g.addEdge(edge[i][1], edge[i][0], 1); } return g;} // Function returns minimum number of edges to be// reversed to reach from src to deststatic int getMinEdgeReversal(int edge[][], int E, int V, int src, int dest){ // Get modified graph with edge weight Graph g = modelGraphWithEdgeWeight(edge, E, V); // Get shortes path vector int[] dist = g.shortestPath(src); // If distance of destination is still INF, // not possible if (dist[dest] == INF) return -1; else return dist[dest];} // Driver codepublic static void main(String[] args){ int V = 7; int edge[][] = { { 0, 1 }, { 2, 1 }, { 2, 3 }, { 5, 1 }, { 4, 5 }, { 6, 4 }, { 6, 3 } }; int E = edge.length; int minEdgeToReverse = getMinEdgeReversal( edge, E, V, 0, 6); if (minEdgeToReverse != -1) System.out.println(minEdgeToReverse); else System.out.println("Not possible");}} // This code is contributed by sanjeev2552 # Python3 Program to find minimum edge reversal to get# atleast one path from source to destination # method adds a directed edge from u to v with weight wdef addEdge(u, v, w): global adj adj[u].append((v, w)) # Prints shortest paths from src to all other verticesdef shortestPath(src): # Create a set to store vertices that are being # preprocessed setds = {} # Create a vector for distances and initialize all # distances as infinite (INF) dist = [10**18 for i in range(V)] # Insert source itself in Set and initialize its global adj setds[(0, src)] = 1 dist[src] = 0 # /* Looping till all shortest distance are finalized # then setds will become empty */ while (len(setds) > 0): # The first vertex in Set is the minimum distance # vertex, extract it from set. tmp = list(setds.keys())[0] del setds[tmp] # vertex label is stored in second of pair (it # has to be done this way to keep the vertices # sorted distance (distance must be first item # in pair) u = tmp[1] # 'i' is used to get all adjacent vertices of a vertex # list< pair<int, int> >::iterator i; for i in adj[u]: # Get vertex label and weight of current adjacent # of u. v = i[0]; weight = i[1] # If there is shorter path to v through u. if (dist[v] > dist[u] + weight): # /* If distance of v is not INF then it must be in # our set, so removing it and inserting again # with updated less distance. # Note : We extract only those vertices from Set # for which distance is finalized. So for them, # we would never reach here. */ if (dist[v] != 10**18): del setds[(dist[v], v)] # Updating distance of v dist[v] = dist[u] + weight setds[(dist[v], v)] = 1 return dist # /* method adds reverse edge of each original edge# in the graph. It gives reverse edge a weight = 1# and all original edges a weight of 0. Now, the# length of the shortest path will give us the answer.# If shortest path is p: it means we used p reverse# edges in the shortest path. */def modelGraphWithEdgeWeight(edge, E, V): global adj for i in range(E): # original edge : weight 0 addEdge(edge[i][0], edge[i][1], 0) # reverse edge : weight 1 addEdge(edge[i][1], edge[i][0], 1) # Method returns minimum number of edges to be# reversed to reach from src to destdef getMinEdgeReversal(edge, E, V,src, dest): # get modified graph with edge weight modelGraphWithEdgeWeight(edge, E, V) # get shortes path vector dist = shortestPath(src) # If distance of destination is still INF, # not possible if (dist[dest] == 10**18): return -1 else: return dist[dest] # Driver codeif __name__ == '__main__': V = 7 edge = [[0, 1], [2, 1], [2, 3], [5, 1],[4, 5], [6, 4], [6, 3]] E, adj = len(edge), [[] for i in range(V + 1)] minEdgeToReverse = getMinEdgeReversal(edge, E, V, 0, 6) if (minEdgeToReverse != -1): print(minEdgeToReverse) else: print("Not possible") # This code is contributed by mohit kumar 29 Output: 2 One more efficient approach to this problem would be by using 0-1 BFS concept. Below is the implementation of that algorithm: Java //Java code to find minimum edge reversal to get//atleast one path from source to destination using 0-1 BFS//Code By: Sparsh_CBSimport java.util.*; class Node{ private int val; private int weight; private Integer parent; Node(int val, int weight){ this.val = val; this.weight = weight; parent = null; } //We have used the concept of parent to avoid //a child revisiting its parent and pushing it in //the deque during the 0-1 BFS Node(int val, int distance, Integer parent){ this.val = val; this.weight = distance; this.parent = parent; } public int getVal(){ return val; } public int getWeight(){ return weight; } public Integer getParent(){ return parent; }} public class Gfg{ public static void main(String[] args) { List<List<Integer>> adj = new ArrayList<>(); for(int i = 0; i < 7; i++) adj.add(new ArrayList<>()); adj.get(0).add(1); adj.get(2).add(1); adj.get(5).add(1); adj.get(2).add(3); adj.get(6).add(3); adj.get(6).add(4); adj.get(4).add(5); int ans = getMinRevEdges(adj, 0, 6); if(ans == Integer.MAX_VALUE) System.out.println(-1); else System.out.println(ans); } private static int getMinRevEdges(List<List<Integer>> adj, int src, int dest){ int n = adj.size(); //Create the given graph into bidirectional graph List<List<Node>> newAdj = getBiDirectionalGraph(adj); //Now, Apply 0-1 BFS using Deque to get the shortest path //In the implementation, we will only add the //encountered node into the deque if and only if //the distance at which it was earlier explored was //strictly larger than the currently encountered distance Deque<Node> dq = new LinkedList<>(); //Here Node is made up of : Node(int node_val, int node_distance, int node_parent) dq.offer(new Node(src,0,0)); int[] dist = new int[n]; //Set the distance of all nodes to infinity(Integer.MAX_VALUE) Arrays.fill(dist, Integer.MAX_VALUE); //set distance of source node as 0 dist[src] = 0; while(!dq.isEmpty()){ Node curr = dq.pollFirst(); int currVal = curr.getVal(); int currWeight = curr.getWeight(); int currParent = curr.getParent(); //If we encounter the destination node, we return if(currVal == dest) return currWeight; //Iterate over the neighbours of the current Node for(Node neighbourNode: newAdj.get(currVal)){ int neighbour = neighbourNode.getVal(); if(neighbour == currParent) continue; int wt = neighbourNode.getWeight(); if(wt == 0 && dist[neighbour] > currWeight){ dist[neighbour] = currWeight; dq.offerFirst(new Node(neighbour,currWeight, currVal)); } else if(dist[neighbour] > currWeight+wt){ dist[neighbour] = currWeight+wt; dq.offerLast(new Node(neighbour, currWeight+wt, currVal)); } } } return Integer.MAX_VALUE; } private static List<List<Node>> getBiDirectionalGraph(List<List<Integer>> adj){ int n = adj.size(); List<List<Node>> newAdj = new ArrayList<>(); for(int i = 0; i < n; i++) newAdj.add(new ArrayList<>()); boolean[] visited = new boolean[n]; Queue<Integer> queue = new LinkedList<>(); for(int i = 0; i < n; i++){ if(!visited[i]){ visited[i] = true; queue.offer(i); while(!queue.isEmpty()){ int curr = queue.poll(); for(int neighbour: adj.get(curr)){ //original edges are to be assigned a weight of 0 newAdj.get(curr).add(new Node(neighbour, 0)); //make a fake edge and assign a weight of 1 newAdj.get(neighbour).add(new Node(curr, 1)); if(visited[neighbour]){ //if the neighbour was visited, then dont // add it again in the queue continue; } visited[neighbour] = true; queue.offer(neighbour); } } } } return newAdj; }} Output: 2 Time Complexity: O(V+E) Space Complexity: O(V+2*E) This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 mohit kumar 29 jyoti369 anikakapoor imsushant12 simmytarika5 sparshsharma2510 surinderdawra388 Reverse Graph Greedy Greedy Graph Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Program for array rotation Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Activity Selection Problem | Greedy Algo-1
[ { "code": null, "e": 26475, "s": 26447, "text": "\n04 Mar, 2022" }, { "code": null, "e": 26667, "s": 26475, "text": "Given a directed graph and a source node and destination node, we need to find how many edges we need to reverse in order to make at least 1 path from the source node to the destination node." }, { "code": null, "e": 26679, "s": 26667, "text": "Examples: " }, { "code": null, "e": 26863, "s": 26679, "text": "In above graph there were two paths from node 0 to node 6,\n0 -> 1 -> 2 -> 3 -> 6\n0 -> 1 -> 5 -> 4 -> 6\nBut for first path only two edges need to be reversed, so answer will be 2 only." }, { "code": null, "e": 27142, "s": 26863, "text": "This problem can be solved assuming a different version of the given graph. In this version we make a reverse edge corresponding to every edge and we assign that a weight 1 and assign a weight 0 to original edge. After this modification above graph looks something like below, " }, { "code": null, "e": 27526, "s": 27142, "text": "Now we can see that we have modified the graph in such a way that, if we move towards original edge, no cost is incurred, but if we move toward reverse edge 1 cost is added. So if we apply Dijkstra’s shortest path on this modified graph from given source, then that will give us minimum cost to reach from source to destination i.e. minimum edge reversal from source to destination. " }, { "code": null, "e": 27569, "s": 27526, "text": "Below is the code based on above concept. " }, { "code": null, "e": 27573, "s": 27569, "text": "C++" }, { "code": null, "e": 27578, "s": 27573, "text": "Java" }, { "code": null, "e": 27586, "s": 27578, "text": "Python3" }, { "code": "// C++ Program to find minimum edge reversal to get// atleast one path from source to destination#include <bits/stdc++.h>using namespace std;#define INF 0x3f3f3f3f // This class represents a directed graph using// adjacency list representationclass Graph{ int V; list<pair<int, int>> *graph; public: // Constructor: Graph(int V) { this->V = V; graph = new list<pair<int, int>>[V]; } // Adding edges into the graph: void addEdge(int u, int v, int w) { graph[u].push_back(make_pair(v, w)); } // Returns shortest path from source to all other vertices. vector<int> shortestPath(int source) { // Create a set to store vertices that are being preprocessed set<pair<int, int>> setds; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> distance(V, INF); // Insert source itself in Set and initialize its distance as 0. setds.insert(make_pair(0, source)); distance = 0; /* Looping till all shortest distance are finalized then setds will become empty */ while (!setds.empty()) { // The first vertex in Set is the minimum distance // vertex, extract it from set. pair<int, int> tmp = *(setds.begin()); setds.erase(setds.begin()); // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; list<pair<int, int>>::iterator i; for (i = graph[u].begin(); i != graph[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If there is shorter path to v through u. if (distance[v] > distance[u] + weight) { /* If distance of v is not INF then it must be in our set, so removing it and inserting again with updated less distance. Note : We extract only those vertices from Set for which distance is finalized. So for them, we would never reach here. */ if (distance[v] != INF) setds.erase(setds.find(make_pair(distance[v], v))); // Updating distance of v distance[v] = distance[u] + weight; setds.insert(make_pair(distance[v], v)); } } } return distance; } Graph modelGraphWithEdgeWeight(int edge[][2], int E, int V) { Graph g(V); for (int i = 0; i < E; i++) { // original edge : weight 0 g.addEdge(edge[i][0], edge[i][1], 0); // reverse edge : weight 1 g.addEdge(edge[i][1], edge[i][0], 1); } return g; } int getMinEdgeReversal(int edge[][2], int E, int V, int source, int destination) { // get modified graph with edge weight. Graph g = modelGraphWithEdgeWeight(edge, E, V); // distance vector stores shortest path. vector<int> dist = g.shortestPath(source); // If distance of destination is still INF then we cannot reach destination. Hence, not possible. if (dist[destination] == INF) return -1; else return dist[destination]; }}; int main(){ int V = 7; Graph g(V); int edge[][2] = {{0, 1}, {2, 1}, {2, 3}, {5, 1}, {4, 5}, {6, 4}, {6, 3}}; int E = sizeof(edge) / sizeof(edge[0]); int minEdgeToReverse = g.getMinEdgeReversal(edge, E, V, 0, 6); if (minEdgeToReverse != -1) cout << minEdgeToReverse << endl; else cout << \"Not Possible.\" << endl; return 0;}", "e": 31545, "s": 27586, "text": null }, { "code": "// Java program to find minimum edge reversal to get// atleast one path from source to destinationimport java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set; class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} // This class represents a directed graph using// adjacency list representationclass Graph{ final int INF = (int)0x3f3f3f3f; // No. of verticesint V; // In a weighted graph, we need to store vertex// and weight pair for every edgeList<Pair>[] adj; // Allocates memory for adjacency list@SuppressWarnings(\"unchecked\")public Graph(int V){ this.V = V; adj = new ArrayList[V]; for(int i = 0; i < V; i++) { adj[i] = new ArrayList(); }} // Function adds a directed edge from// u to v with weight wvoid addEdge(int u, int v, int w){ adj[u].add(new Pair(v, w));} // Prints shortest paths from// src to all other verticesint[] shortestPath(int src){ // Create a set to store vertices // that are being preprocessed Set<Pair> setds = new HashSet<Pair>(); // Create a vector for distances and // initialize all distances as infinite(INF) int[] dist = new int[V]; Arrays.fill(dist, INF); // Insert source itself in Set and initialize // its distance as 0. setds.add(new Pair(0, src)); dist[src] = 0; // Looping till all shortest distance are // finalized then setds will become empty while (!setds.isEmpty()) { // The first vertex in Set is the minimum // distance vertex, extract it from set. Iterator<Pair> itr = setds.iterator(); Pair tmp = itr.next(); itr.remove(); // Vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; // 'i' is used to get all adjacent // vertices of a vertex for(Pair p : adj[u]) { // Get vertex label and weight of // current adjacent of u. int v = p.first; int weight = p.second; // If there is shorter path to v through u. if (dist[v] > dist[u] + weight) { // If distance of v is not INF then it // must be in our set, so removing it // and inserting again with updated // less distance. Note : We extract // only those vertices from Set for // which distance is finalized. So // for them, we would never reach here. if (dist[v] != INF) { setds.remove(new Pair(dist[v], v)); } // setds.erase(setds.find(new Pair(dist[v], v))); // Updating distance of v dist[v] = dist[u] + weight; setds.add(new Pair(dist[v], v)); } } } return dist;}} class GFG{static final int INF = (int)0x3f3f3f3f; // Function adds reverse edge of each original// edge in the graph. It gives reverse edge// a weight = 1 and all original edges a// weight of 0. Now, the length of the// shortest path will give us the answer.// If shortest path is p: it means we// used p reverse edges in the shortest path.static Graph modelGraphWithEdgeWeight(int edge[][], int E, int V){ Graph g = new Graph(V); for(int i = 0; i < E; i++) { // Original edge : weight 0 g.addEdge(edge[i][0], edge[i][1], 0); // Reverse edge : weight 1 g.addEdge(edge[i][1], edge[i][0], 1); } return g;} // Function returns minimum number of edges to be// reversed to reach from src to deststatic int getMinEdgeReversal(int edge[][], int E, int V, int src, int dest){ // Get modified graph with edge weight Graph g = modelGraphWithEdgeWeight(edge, E, V); // Get shortes path vector int[] dist = g.shortestPath(src); // If distance of destination is still INF, // not possible if (dist[dest] == INF) return -1; else return dist[dest];} // Driver codepublic static void main(String[] args){ int V = 7; int edge[][] = { { 0, 1 }, { 2, 1 }, { 2, 3 }, { 5, 1 }, { 4, 5 }, { 6, 4 }, { 6, 3 } }; int E = edge.length; int minEdgeToReverse = getMinEdgeReversal( edge, E, V, 0, 6); if (minEdgeToReverse != -1) System.out.println(minEdgeToReverse); else System.out.println(\"Not possible\");}} // This code is contributed by sanjeev2552", "e": 36365, "s": 31545, "text": null }, { "code": "# Python3 Program to find minimum edge reversal to get# atleast one path from source to destination # method adds a directed edge from u to v with weight wdef addEdge(u, v, w): global adj adj[u].append((v, w)) # Prints shortest paths from src to all other verticesdef shortestPath(src): # Create a set to store vertices that are being # preprocessed setds = {} # Create a vector for distances and initialize all # distances as infinite (INF) dist = [10**18 for i in range(V)] # Insert source itself in Set and initialize its global adj setds[(0, src)] = 1 dist[src] = 0 # /* Looping till all shortest distance are finalized # then setds will become empty */ while (len(setds) > 0): # The first vertex in Set is the minimum distance # vertex, extract it from set. tmp = list(setds.keys())[0] del setds[tmp] # vertex label is stored in second of pair (it # has to be done this way to keep the vertices # sorted distance (distance must be first item # in pair) u = tmp[1] # 'i' is used to get all adjacent vertices of a vertex # list< pair<int, int> >::iterator i; for i in adj[u]: # Get vertex label and weight of current adjacent # of u. v = i[0]; weight = i[1] # If there is shorter path to v through u. if (dist[v] > dist[u] + weight): # /* If distance of v is not INF then it must be in # our set, so removing it and inserting again # with updated less distance. # Note : We extract only those vertices from Set # for which distance is finalized. So for them, # we would never reach here. */ if (dist[v] != 10**18): del setds[(dist[v], v)] # Updating distance of v dist[v] = dist[u] + weight setds[(dist[v], v)] = 1 return dist # /* method adds reverse edge of each original edge# in the graph. It gives reverse edge a weight = 1# and all original edges a weight of 0. Now, the# length of the shortest path will give us the answer.# If shortest path is p: it means we used p reverse# edges in the shortest path. */def modelGraphWithEdgeWeight(edge, E, V): global adj for i in range(E): # original edge : weight 0 addEdge(edge[i][0], edge[i][1], 0) # reverse edge : weight 1 addEdge(edge[i][1], edge[i][0], 1) # Method returns minimum number of edges to be# reversed to reach from src to destdef getMinEdgeReversal(edge, E, V,src, dest): # get modified graph with edge weight modelGraphWithEdgeWeight(edge, E, V) # get shortes path vector dist = shortestPath(src) # If distance of destination is still INF, # not possible if (dist[dest] == 10**18): return -1 else: return dist[dest] # Driver codeif __name__ == '__main__': V = 7 edge = [[0, 1], [2, 1], [2, 3], [5, 1],[4, 5], [6, 4], [6, 3]] E, adj = len(edge), [[] for i in range(V + 1)] minEdgeToReverse = getMinEdgeReversal(edge, E, V, 0, 6) if (minEdgeToReverse != -1): print(minEdgeToReverse) else: print(\"Not possible\") # This code is contributed by mohit kumar 29", "e": 39744, "s": 36365, "text": null }, { "code": null, "e": 39753, "s": 39744, "text": "Output: " }, { "code": null, "e": 39755, "s": 39753, "text": "2" }, { "code": null, "e": 39835, "s": 39755, "text": "One more efficient approach to this problem would be by using 0-1 BFS concept. " }, { "code": null, "e": 39882, "s": 39835, "text": "Below is the implementation of that algorithm:" }, { "code": null, "e": 39887, "s": 39882, "text": "Java" }, { "code": "//Java code to find minimum edge reversal to get//atleast one path from source to destination using 0-1 BFS//Code By: Sparsh_CBSimport java.util.*; class Node{ private int val; private int weight; private Integer parent; Node(int val, int weight){ this.val = val; this.weight = weight; parent = null; } //We have used the concept of parent to avoid //a child revisiting its parent and pushing it in //the deque during the 0-1 BFS Node(int val, int distance, Integer parent){ this.val = val; this.weight = distance; this.parent = parent; } public int getVal(){ return val; } public int getWeight(){ return weight; } public Integer getParent(){ return parent; }} public class Gfg{ public static void main(String[] args) { List<List<Integer>> adj = new ArrayList<>(); for(int i = 0; i < 7; i++) adj.add(new ArrayList<>()); adj.get(0).add(1); adj.get(2).add(1); adj.get(5).add(1); adj.get(2).add(3); adj.get(6).add(3); adj.get(6).add(4); adj.get(4).add(5); int ans = getMinRevEdges(adj, 0, 6); if(ans == Integer.MAX_VALUE) System.out.println(-1); else System.out.println(ans); } private static int getMinRevEdges(List<List<Integer>> adj, int src, int dest){ int n = adj.size(); //Create the given graph into bidirectional graph List<List<Node>> newAdj = getBiDirectionalGraph(adj); //Now, Apply 0-1 BFS using Deque to get the shortest path //In the implementation, we will only add the //encountered node into the deque if and only if //the distance at which it was earlier explored was //strictly larger than the currently encountered distance Deque<Node> dq = new LinkedList<>(); //Here Node is made up of : Node(int node_val, int node_distance, int node_parent) dq.offer(new Node(src,0,0)); int[] dist = new int[n]; //Set the distance of all nodes to infinity(Integer.MAX_VALUE) Arrays.fill(dist, Integer.MAX_VALUE); //set distance of source node as 0 dist[src] = 0; while(!dq.isEmpty()){ Node curr = dq.pollFirst(); int currVal = curr.getVal(); int currWeight = curr.getWeight(); int currParent = curr.getParent(); //If we encounter the destination node, we return if(currVal == dest) return currWeight; //Iterate over the neighbours of the current Node for(Node neighbourNode: newAdj.get(currVal)){ int neighbour = neighbourNode.getVal(); if(neighbour == currParent) continue; int wt = neighbourNode.getWeight(); if(wt == 0 && dist[neighbour] > currWeight){ dist[neighbour] = currWeight; dq.offerFirst(new Node(neighbour,currWeight, currVal)); } else if(dist[neighbour] > currWeight+wt){ dist[neighbour] = currWeight+wt; dq.offerLast(new Node(neighbour, currWeight+wt, currVal)); } } } return Integer.MAX_VALUE; } private static List<List<Node>> getBiDirectionalGraph(List<List<Integer>> adj){ int n = adj.size(); List<List<Node>> newAdj = new ArrayList<>(); for(int i = 0; i < n; i++) newAdj.add(new ArrayList<>()); boolean[] visited = new boolean[n]; Queue<Integer> queue = new LinkedList<>(); for(int i = 0; i < n; i++){ if(!visited[i]){ visited[i] = true; queue.offer(i); while(!queue.isEmpty()){ int curr = queue.poll(); for(int neighbour: adj.get(curr)){ //original edges are to be assigned a weight of 0 newAdj.get(curr).add(new Node(neighbour, 0)); //make a fake edge and assign a weight of 1 newAdj.get(neighbour).add(new Node(curr, 1)); if(visited[neighbour]){ //if the neighbour was visited, then dont // add it again in the queue continue; } visited[neighbour] = true; queue.offer(neighbour); } } } } return newAdj; }}", "e": 44617, "s": 39887, "text": null }, { "code": null, "e": 44626, "s": 44617, "text": "Output: " }, { "code": null, "e": 44628, "s": 44626, "text": "2" }, { "code": null, "e": 44652, "s": 44628, "text": "Time Complexity: O(V+E)" }, { "code": null, "e": 44679, "s": 44652, "text": "Space Complexity: O(V+2*E)" }, { "code": null, "e": 45103, "s": 44679, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 45115, "s": 45103, "text": "sanjeev2552" }, { "code": null, "e": 45130, "s": 45115, "text": "mohit kumar 29" }, { "code": null, "e": 45139, "s": 45130, "text": "jyoti369" }, { "code": null, "e": 45151, "s": 45139, "text": "anikakapoor" }, { "code": null, "e": 45163, "s": 45151, "text": "imsushant12" }, { "code": null, "e": 45176, "s": 45163, "text": "simmytarika5" }, { "code": null, "e": 45193, "s": 45176, "text": "sparshsharma2510" }, { "code": null, "e": 45210, "s": 45193, "text": "surinderdawra388" }, { "code": null, "e": 45218, "s": 45210, "text": "Reverse" }, { "code": null, "e": 45224, "s": 45218, "text": "Graph" }, { "code": null, "e": 45231, "s": 45224, "text": "Greedy" }, { "code": null, "e": 45238, "s": 45231, "text": "Greedy" }, { "code": null, "e": 45244, "s": 45238, "text": "Graph" }, { "code": null, "e": 45252, "s": 45244, "text": "Reverse" }, { "code": null, "e": 45350, "s": 45252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45370, "s": 45350, "text": "Topological Sorting" }, { "code": null, "e": 45403, "s": 45370, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 45471, "s": 45403, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 45521, "s": 45471, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 45596, "s": 45521, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 45623, "s": 45596, "text": "Program for array rotation" }, { "code": null, "e": 45683, "s": 45623, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 45714, "s": 45683, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 45733, "s": 45714, "text": "Coin Change | DP-7" } ]
Perl | glob() Function - GeeksforGeeks
12 Jun, 2019 glob() function in Perl is used to print the files present in a directory passed to it as an argument. This function can print all or the specific files whose extension has been passed to it. Syntax: glob(Directory_name/File_type); Parameter: path of the directory of which files are to be printed. Returns: the list of files present in the given directory Example 1: Printing names of all the files in the directory #!/usr/bin/perl # To store the files# from the directory in the array@files = glob('C:/Users/GeeksForGeeks/Folder/*'); # Printing the created arrayprint "@files\n"; Output:Above example will print all the files of the requested directory. Example 2: Printing names of the specific files in the directory #!/usr/bin/perl # To store the files of a specific extension# from the directory in the array@Array = glob('C:/Users/GeeksForGeeks/Folder/*.txt'); # Printing the created arrayprint "@Array\n"; Output:Above example will print all the files of the requested directory that end with .txt extension. Perl-File-Functions Perl-function Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Arrays Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | length() Function Perl | join() Function Perl | Basic Syntax of a Perl Program Perl | Boolean Values Perl | sleep() Function Perl | Subroutines or Functions
[ { "code": null, "e": 25355, "s": 25327, "text": "\n12 Jun, 2019" }, { "code": null, "e": 25547, "s": 25355, "text": "glob() function in Perl is used to print the files present in a directory passed to it as an argument. This function can print all or the specific files whose extension has been passed to it." }, { "code": null, "e": 25587, "s": 25547, "text": "Syntax: glob(Directory_name/File_type);" }, { "code": null, "e": 25654, "s": 25587, "text": "Parameter: path of the directory of which files are to be printed." }, { "code": null, "e": 25712, "s": 25654, "text": "Returns: the list of files present in the given directory" }, { "code": null, "e": 25772, "s": 25712, "text": "Example 1: Printing names of all the files in the directory" }, { "code": "#!/usr/bin/perl # To store the files# from the directory in the array@files = glob('C:/Users/GeeksForGeeks/Folder/*'); # Printing the created arrayprint \"@files\\n\";", "e": 25939, "s": 25772, "text": null }, { "code": null, "e": 26013, "s": 25939, "text": "Output:Above example will print all the files of the requested directory." }, { "code": null, "e": 26078, "s": 26013, "text": "Example 2: Printing names of the specific files in the directory" }, { "code": "#!/usr/bin/perl # To store the files of a specific extension# from the directory in the array@Array = glob('C:/Users/GeeksForGeeks/Folder/*.txt'); # Printing the created arrayprint \"@Array\\n\";", "e": 26273, "s": 26078, "text": null }, { "code": null, "e": 26376, "s": 26273, "text": "Output:Above example will print all the files of the requested directory that end with .txt extension." }, { "code": null, "e": 26396, "s": 26376, "text": "Perl-File-Functions" }, { "code": null, "e": 26410, "s": 26396, "text": "Perl-function" }, { "code": null, "e": 26415, "s": 26410, "text": "Perl" }, { "code": null, "e": 26420, "s": 26415, "text": "Perl" }, { "code": null, "e": 26518, "s": 26420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26560, "s": 26518, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 26574, "s": 26560, "text": "Perl | Arrays" }, { "code": null, "e": 26615, "s": 26574, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 26648, "s": 26615, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 26673, "s": 26648, "text": "Perl | length() Function" }, { "code": null, "e": 26696, "s": 26673, "text": "Perl | join() Function" }, { "code": null, "e": 26734, "s": 26696, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 26756, "s": 26734, "text": "Perl | Boolean Values" }, { "code": null, "e": 26780, "s": 26756, "text": "Perl | sleep() Function" } ]
How to Capture Screenshot of a View and Save it to Gallery in Android? - GeeksforGeeks
14 Feb, 2021 In this article, we will capture a screenshot of a view and store the image in the gallery. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a new project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language Step 2: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. Notice that it has a Material Card View with id card_View, we will take a screenshot of this view in this article. 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:id="@+id/parentLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <com.google.android.material.card.MaterialCardView android:id="@+id/card_View" android:layout_width="match_parent" android:layout_height="300dp" android:layout_margin="20dp" android:elevation="10dp" app:cardBackgroundColor="@color/black" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="center" android:src="@drawable/gfg" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="20dp" android:text="Geeks For Geeks" android:textColor="@color/white" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> <Button android:id="@+id/btn_capture" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_marginTop="20dp" android:backgroundTint="#0F9D58" android:text="Capture View" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/card_View" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3. Add permission in the manifest. Go to the AndroidManifest.xml file and the following code. It has two permissions Read and Write to external storage. and inside application tag it has android:usesCleartextTraffic=”true”. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.geeksforgeeks.captureview"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" /> <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/Theme.CaptureView" android:usesCleartextTraffic="true"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.Manifestimport android.content.ContentValuesimport android.graphics.Bitmapimport android.graphics.Canvasimport android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.os.Environmentimport android.provider.MediaStoreimport android.util.Logimport android.view.Viewimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.cardview.widget.CardViewimport androidx.core.app.ActivityCompatimport java.io.Fileimport java.io.FileOutputStreamimport java.io.OutputStream class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // write permission to access the storage ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) // this is the card view whose screenshot // we will take in this article // get the view using fin view bt id val cardView = findViewById<CardView>(R.id.card_View) // on click of this button it will capture // screenshot and save into gallery val captureButton = findViewById<Button>(R.id.btn_capture) captureButton.setOnClickListener { // get the bitmap of the view using // getScreenShotFromView method it is // implemented below val bitmap = getScreenShotFromView(cardView) // if bitmap is not null then // save it to gallery if (bitmap != null) { saveMediaToStorage(bitmap) } } } private fun getScreenShotFromView(v: View): Bitmap? { // create a bitmap object var screenshot: Bitmap? = null try { // inflate screenshot object // with Bitmap.createBitmap it // requires three parameters // width and height of the view and // the background color screenshot = Bitmap.createBitmap(v.measuredWidth, v.measuredHeight, Bitmap.Config.ARGB_8888) // Now draw this bitmap on a canvas val canvas = Canvas(screenshot) v.draw(canvas) } catch (e: Exception) { Log.e("GFG", "Failed to capture screenshot because:" + e.message) } // return the bitmap return screenshot } // this method saves the image to gallery private fun saveMediaToStorage(bitmap: Bitmap) { // Generating a file name val filename = "${System.currentTimeMillis()}.jpg" // Output stream var fos: OutputStream? = null // For devices running android >= Q if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // getting the contentResolver this.contentResolver?.also { resolver -> // Content resolver will process the contentvalues val contentValues = ContentValues().apply { // putting file information in content values put(MediaStore.MediaColumns.DISPLAY_NAME, filename) put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg") put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES) } // Inserting the contentValues to // contentResolver and getting the Uri val imageUri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues) // Opening an outputstream with the Uri that we got fos = imageUri?.let { resolver.openOutputStream(it) } } } else { // These for devices running on android < Q val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) val image = File(imagesDir, filename) fos = FileOutputStream(image) } fos?.use { // Finally writing the bitmap to the output stream that we opened bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it) Toast.makeText(this , "Captured View and saved to Gallery" , Toast.LENGTH_SHORT).show() } }} Github repo here android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Setters and Getters
[ { "code": null, "e": 26405, "s": 26377, "text": "\n14 Feb, 2021" }, { "code": null, "e": 26666, "s": 26405, "text": "In this article, we will capture a screenshot of a view and store the image in the gallery. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 26695, "s": 26666, "text": "Step 1: Create a new project" }, { "code": null, "e": 26858, "s": 26695, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language" }, { "code": null, "e": 26906, "s": 26858, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 27137, "s": 26906, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. Notice that it has a Material Card View with id card_View, we will take a screenshot of this view in this article." }, { "code": null, "e": 27141, "s": 27137, "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:id=\"@+id/parentLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" tools:context=\".MainActivity\"> <com.google.android.material.card.MaterialCardView android:id=\"@+id/card_View\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_margin=\"20dp\" android:elevation=\"10dp\" app:cardBackgroundColor=\"@color/black\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <ImageView android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:scaleType=\"center\" android:src=\"@drawable/gfg\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"20dp\" android:text=\"Geeks For Geeks\" android:textColor=\"@color/white\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> <Button android:id=\"@+id/btn_capture\" android:layout_width=\"wrap_content\" android:layout_height=\"50dp\" android:layout_marginTop=\"20dp\" android:backgroundTint=\"#0F9D58\" android:text=\"Capture View\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@id/card_View\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 29321, "s": 27141, "text": null }, { "code": null, "e": 29361, "s": 29321, "text": "Step 3. Add permission in the manifest." }, { "code": null, "e": 29550, "s": 29361, "text": "Go to the AndroidManifest.xml file and the following code. It has two permissions Read and Write to external storage. and inside application tag it has android:usesCleartextTraffic=”true”." }, { "code": null, "e": 29554, "s": 29550, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" package=\"com.geeksforgeeks.captureview\"> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" tools:ignore=\"ScopedStorage\" /> <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/Theme.CaptureView\" android:usesCleartextTraffic=\"true\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 30574, "s": 29554, "text": null }, { "code": null, "e": 30620, "s": 30574, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 30806, "s": 30620, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 30813, "s": 30806, "text": "Kotlin" }, { "code": "import android.Manifestimport android.content.ContentValuesimport android.graphics.Bitmapimport android.graphics.Canvasimport android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.os.Environmentimport android.provider.MediaStoreimport android.util.Logimport android.view.Viewimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.cardview.widget.CardViewimport androidx.core.app.ActivityCompatimport java.io.Fileimport java.io.FileOutputStreamimport java.io.OutputStream class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // write permission to access the storage ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) // this is the card view whose screenshot // we will take in this article // get the view using fin view bt id val cardView = findViewById<CardView>(R.id.card_View) // on click of this button it will capture // screenshot and save into gallery val captureButton = findViewById<Button>(R.id.btn_capture) captureButton.setOnClickListener { // get the bitmap of the view using // getScreenShotFromView method it is // implemented below val bitmap = getScreenShotFromView(cardView) // if bitmap is not null then // save it to gallery if (bitmap != null) { saveMediaToStorage(bitmap) } } } private fun getScreenShotFromView(v: View): Bitmap? { // create a bitmap object var screenshot: Bitmap? = null try { // inflate screenshot object // with Bitmap.createBitmap it // requires three parameters // width and height of the view and // the background color screenshot = Bitmap.createBitmap(v.measuredWidth, v.measuredHeight, Bitmap.Config.ARGB_8888) // Now draw this bitmap on a canvas val canvas = Canvas(screenshot) v.draw(canvas) } catch (e: Exception) { Log.e(\"GFG\", \"Failed to capture screenshot because:\" + e.message) } // return the bitmap return screenshot } // this method saves the image to gallery private fun saveMediaToStorage(bitmap: Bitmap) { // Generating a file name val filename = \"${System.currentTimeMillis()}.jpg\" // Output stream var fos: OutputStream? = null // For devices running android >= Q if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // getting the contentResolver this.contentResolver?.also { resolver -> // Content resolver will process the contentvalues val contentValues = ContentValues().apply { // putting file information in content values put(MediaStore.MediaColumns.DISPLAY_NAME, filename) put(MediaStore.MediaColumns.MIME_TYPE, \"image/jpg\") put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES) } // Inserting the contentValues to // contentResolver and getting the Uri val imageUri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues) // Opening an outputstream with the Uri that we got fos = imageUri?.let { resolver.openOutputStream(it) } } } else { // These for devices running on android < Q val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) val image = File(imagesDir, filename) fos = FileOutputStream(image) } fos?.use { // Finally writing the bitmap to the output stream that we opened bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it) Toast.makeText(this , \"Captured View and saved to Gallery\" , Toast.LENGTH_SHORT).show() } }}", "e": 35162, "s": 30813, "text": null }, { "code": null, "e": 35179, "s": 35162, "text": "Github repo here" }, { "code": null, "e": 35187, "s": 35179, "text": "android" }, { "code": null, "e": 35195, "s": 35187, "text": "Android" }, { "code": null, "e": 35202, "s": 35195, "text": "Kotlin" }, { "code": null, "e": 35210, "s": 35202, "text": "Android" }, { "code": null, "e": 35308, "s": 35210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35346, "s": 35308, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35385, "s": 35346, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35435, "s": 35385, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 35486, "s": 35435, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 35528, "s": 35486, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35547, "s": 35528, "text": "Android UI Layouts" }, { "code": null, "e": 35560, "s": 35547, "text": "Kotlin Array" }, { "code": null, "e": 35602, "s": 35560, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35642, "s": 35602, "text": "How to Get Current Location in Android?" } ]
How to install XAMPP on Windows ? - GeeksforGeeks
28 Jan, 2022 XAMPP is the most popular software package which is used to set up a PHP development environment for web services by providing all the required software components. During the process of software deployment, most of the web servers use almost similar components, so use of XAMPP provides easy transition from local server to live server. XAMPP is a AMP stack which stands for Cross platform, Apache, MySQL, PHP, perl with some additional administrative software tools such as PHPMyAdmin (for database access), FileZilla FTP server, Mercury mail server and JSP Tomcat server. Other commonly known software packages like XAMPP are WAMP, LAMP, and others.The XAMPP server is used to test PHP pages. It works as local server. It contains a MySQL database to manage or save data on a local server.Advantages of XAMPP: It is free and easy to use and easily available for Windows, Linux and Mac OS . It is a beginners friendly solution package for full stack web development. It is a open source software package which gives a easy installation experience. It is very simple and lightweight to create set up for development, testing and deployment. It is a time-saver and provides several ways for managing configuration changes. It handles many administrative tasks like checking the status and security. Software components of XAMPP: Apache plays the role of processing the HTTP request. It is the actual default web server application. It is the most popular web servers maintained by Apache Software Foundation. MySQL The role of database management system in XAMPP is played by MySQL. It helps to store and manage collected data very efficiently. It is an open-source and most popular. PHP is the server-side scripting language which stand for Hypertext Preprocessor. It is embedded with HTML code which interacts with the webserver. It is an open-source and work well with MySQL and has become a common choice for web developers. Perl is the high-level programming language designed for text editing which serves purpose like web development and network programming. Steps to install XAMPP on Windows: In the web browser, visit Apache Friends and download XAMPP installer. During the installation process, select the required components like MySQL, FileZilla ftp server, PHP, phpMyAdmin or leave the default options and click the Next button. Uncheck the Learn more about bitnami option and click Next button. Choose the root directory path to set up the htdocs folder for our applications. For example ‘C:\xampp’. Click the Allow access button to allow the XAMPP modules from the Windows firewall. After the installation process, click the Finish button of the XAMPP Setup wizard. Now the XAMPP icon is clearly visible on the right side of start menu. Show or Hide can be set by using the control panel by clicking on the icon. To start Apache and MySql, just click on the Start button on the control panel. Note: Suppose Apache is not starting, it means some other service is running at port 80. In this case, stop the other service temporarily and restart it.Making server request: Open your web browser and check whether the XAMPP service has properly installed or not. Type in the URL: http://localhost. If you are able to see the default page for XAMPP, you have successfully installed your XAMPP Server.To Check if PHP is Working: All the website related files are organized in a folder called htdocs and then run index.php file by using http://localhost/index.php or http://localhost.Note: For every new website or application, its always better to create a different folder inside htdocs, to keep it organized and avoid confusion.For example, if we create a folder geeksforgeeks and then create a file named as ‘helloWorld.php’. All the contents related to it are put inside the folder ‘geeksforgeeks’. So the root ‘URL’ of the website will be ‘http://localhost/geeksforgeeks/’. So any home page is accessed by typing the root URL in the browser. To see the output, just type ‘http://localhost/geeksforgeeks/helloWorld.php’.Generally web servers look for index file (landing page) namely index.html or index.php in the root of the website folder. Go to /xampp/htdocs/ folder and create a file with .php extension (test.php) and type or copy the below code and save it. php <?phpphpinfo();?> Now open your browser and go to “http://localhost/test.php” if you see the page same as below then PHP has successfully installed. Note: In XAMPP, the configuration files of Apache, MySQL, PHP are located in C:\Program Files\xampp. For any configuration file changes, you need to restart Apache and MySQL. saurabh1990aror how-to-install How To Installation Guide Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Align Text in HTML? How to filter object array based on attributes? How to Install OpenCV for Python on Windows? Java Tutorial How to Install FFmpeg on Windows? Installation of Node.js on Linux How to Install OpenCV for Python on Windows? How to Install FFmpeg on Windows? How to Install Anaconda on Windows? How to Install Pygame on Windows ?
[ { "code": null, "e": 25912, "s": 25884, "text": "\n28 Jan, 2022" }, { "code": null, "e": 26727, "s": 25912, "text": "XAMPP is the most popular software package which is used to set up a PHP development environment for web services by providing all the required software components. During the process of software deployment, most of the web servers use almost similar components, so use of XAMPP provides easy transition from local server to live server. XAMPP is a AMP stack which stands for Cross platform, Apache, MySQL, PHP, perl with some additional administrative software tools such as PHPMyAdmin (for database access), FileZilla FTP server, Mercury mail server and JSP Tomcat server. Other commonly known software packages like XAMPP are WAMP, LAMP, and others.The XAMPP server is used to test PHP pages. It works as local server. It contains a MySQL database to manage or save data on a local server.Advantages of XAMPP: " }, { "code": null, "e": 26807, "s": 26727, "text": "It is free and easy to use and easily available for Windows, Linux and Mac OS ." }, { "code": null, "e": 26883, "s": 26807, "text": "It is a beginners friendly solution package for full stack web development." }, { "code": null, "e": 26964, "s": 26883, "text": "It is a open source software package which gives a easy installation experience." }, { "code": null, "e": 27056, "s": 26964, "text": "It is very simple and lightweight to create set up for development, testing and deployment." }, { "code": null, "e": 27137, "s": 27056, "text": "It is a time-saver and provides several ways for managing configuration changes." }, { "code": null, "e": 27213, "s": 27137, "text": "It handles many administrative tasks like checking the status and security." }, { "code": null, "e": 27245, "s": 27213, "text": "Software components of XAMPP: " }, { "code": null, "e": 27425, "s": 27245, "text": "Apache plays the role of processing the HTTP request. It is the actual default web server application. It is the most popular web servers maintained by Apache Software Foundation." }, { "code": null, "e": 27600, "s": 27425, "text": "MySQL The role of database management system in XAMPP is played by MySQL. It helps to store and manage collected data very efficiently. It is an open-source and most popular." }, { "code": null, "e": 27845, "s": 27600, "text": "PHP is the server-side scripting language which stand for Hypertext Preprocessor. It is embedded with HTML code which interacts with the webserver. It is an open-source and work well with MySQL and has become a common choice for web developers." }, { "code": null, "e": 27982, "s": 27845, "text": "Perl is the high-level programming language designed for text editing which serves purpose like web development and network programming." }, { "code": null, "e": 28019, "s": 27982, "text": "Steps to install XAMPP on Windows: " }, { "code": null, "e": 28092, "s": 28019, "text": "In the web browser, visit Apache Friends and download XAMPP installer. " }, { "code": null, "e": 28264, "s": 28092, "text": "During the installation process, select the required components like MySQL, FileZilla ftp server, PHP, phpMyAdmin or leave the default options and click the Next button. " }, { "code": null, "e": 28331, "s": 28264, "text": "Uncheck the Learn more about bitnami option and click Next button." }, { "code": null, "e": 28436, "s": 28331, "text": "Choose the root directory path to set up the htdocs folder for our applications. For example ‘C:\\xampp’." }, { "code": null, "e": 28520, "s": 28436, "text": "Click the Allow access button to allow the XAMPP modules from the Windows firewall." }, { "code": null, "e": 28603, "s": 28520, "text": "After the installation process, click the Finish button of the XAMPP Setup wizard." }, { "code": null, "e": 28750, "s": 28603, "text": "Now the XAMPP icon is clearly visible on the right side of start menu. Show or Hide can be set by using the control panel by clicking on the icon." }, { "code": null, "e": 28832, "s": 28750, "text": "To start Apache and MySql, just click on the Start button on the control panel. " }, { "code": null, "e": 30202, "s": 28832, "text": "Note: Suppose Apache is not starting, it means some other service is running at port 80. In this case, stop the other service temporarily and restart it.Making server request: Open your web browser and check whether the XAMPP service has properly installed or not. Type in the URL: http://localhost. If you are able to see the default page for XAMPP, you have successfully installed your XAMPP Server.To Check if PHP is Working: All the website related files are organized in a folder called htdocs and then run index.php file by using http://localhost/index.php or http://localhost.Note: For every new website or application, its always better to create a different folder inside htdocs, to keep it organized and avoid confusion.For example, if we create a folder geeksforgeeks and then create a file named as ‘helloWorld.php’. All the contents related to it are put inside the folder ‘geeksforgeeks’. So the root ‘URL’ of the website will be ‘http://localhost/geeksforgeeks/’. So any home page is accessed by typing the root URL in the browser. To see the output, just type ‘http://localhost/geeksforgeeks/helloWorld.php’.Generally web servers look for index file (landing page) namely index.html or index.php in the root of the website folder. Go to /xampp/htdocs/ folder and create a file with .php extension (test.php) and type or copy the below code and save it. " }, { "code": null, "e": 30206, "s": 30202, "text": "php" }, { "code": "<?phpphpinfo();?>", "e": 30224, "s": 30206, "text": null }, { "code": null, "e": 30357, "s": 30224, "text": "Now open your browser and go to “http://localhost/test.php” if you see the page same as below then PHP has successfully installed. " }, { "code": null, "e": 30533, "s": 30357, "text": "Note: In XAMPP, the configuration files of Apache, MySQL, PHP are located in C:\\Program Files\\xampp. For any configuration file changes, you need to restart Apache and MySQL. " }, { "code": null, "e": 30549, "s": 30533, "text": "saurabh1990aror" }, { "code": null, "e": 30564, "s": 30549, "text": "how-to-install" }, { "code": null, "e": 30571, "s": 30564, "text": "How To" }, { "code": null, "e": 30590, "s": 30571, "text": "Installation Guide" }, { "code": null, "e": 30607, "s": 30590, "text": "Web Technologies" }, { "code": null, "e": 30634, "s": 30607, "text": "Web technologies Questions" }, { "code": null, "e": 30732, "s": 30634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30759, "s": 30732, "text": "How to Align Text in HTML?" }, { "code": null, "e": 30807, "s": 30759, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 30852, "s": 30807, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 30866, "s": 30852, "text": "Java Tutorial" }, { "code": null, "e": 30900, "s": 30866, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 30933, "s": 30900, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30978, "s": 30933, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 31012, "s": 30978, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 31048, "s": 31012, "text": "How to Install Anaconda on Windows?" } ]
Python | Last occurrence of some element in a list - GeeksforGeeks
30 Dec, 2018 There are many ways to find out the first index of element in the list as Python in its language provides index() function that returns the index of first occurrence of element in list. But if one desires to get the last occurrence of element in list, usually a longer method has to be applied. Let’s discuss certain shorthands to achieve this particular task. Method #1 : Using join() + rfind()This is usually the hack that we can employ to achieve this task. Joining the entire list and then employing string function rfind() to get the first element from right i.e last index of element in list. # Python3 code to demonstrate # to get last element occurrence# using join() + rfind() # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # using join() + rfind()# to get last element occurrenceres = ''.join(test_list).rindex('e') # printing resultprint ("The index of last element occurrence: " + str(res)) The index of last element occurrence: 10 Method #2 : Using List Slice + index()Using list slicing we reverse the list and use the conventional index method to get the index of first occurrence of element. Due to the reversed list, the last occurrence is returned rather than the first index of list. # Python3 code to demonstrate # to get last element occurrence# using List Slice + index() # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # using List Slice + index()# to get last element occurrenceres = len(test_list) - 1 - test_list[::-1].index('e') # printing resultprint ("The index of last element occurrence: " + str(res)) The index of last element occurrence: 10 Method #3 : Using max() + enumerate()We use enumerate function to get the list of all the elements having the particular element and then max() is employed to get max i.e last index of the list. # Python3 code to demonstrate # to get last element occurrence# using max() + enumerate() # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # using max() + enumerate()# to get last element occurrenceres = max(idx for idx, val in enumerate(test_list) if val == 'e') # printing resultprint ("The index of last element occurrence: " + str(res)) The index of last element occurrence: 10 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25731, "s": 25703, "text": "\n30 Dec, 2018" }, { "code": null, "e": 26026, "s": 25731, "text": "There are many ways to find out the first index of element in the list as Python in its language provides index() function that returns the index of first occurrence of element in list. But if one desires to get the last occurrence of element in list, usually a longer method has to be applied." }, { "code": null, "e": 26092, "s": 26026, "text": "Let’s discuss certain shorthands to achieve this particular task." }, { "code": null, "e": 26330, "s": 26092, "text": "Method #1 : Using join() + rfind()This is usually the hack that we can employ to achieve this task. Joining the entire list and then employing string function rfind() to get the first element from right i.e last index of element in list." }, { "code": "# Python3 code to demonstrate # to get last element occurrence# using join() + rfind() # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # using join() + rfind()# to get last element occurrenceres = ''.join(test_list).rindex('e') # printing resultprint (\"The index of last element occurrence: \" + str(res))", "e": 26714, "s": 26330, "text": null }, { "code": null, "e": 26756, "s": 26714, "text": "The index of last element occurrence: 10\n" }, { "code": null, "e": 27016, "s": 26756, "text": " Method #2 : Using List Slice + index()Using list slicing we reverse the list and use the conventional index method to get the index of first occurrence of element. Due to the reversed list, the last occurrence is returned rather than the first index of list." }, { "code": "# Python3 code to demonstrate # to get last element occurrence# using List Slice + index() # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # using List Slice + index()# to get last element occurrenceres = len(test_list) - 1 - test_list[::-1].index('e') # printing resultprint (\"The index of last element occurrence: \" + str(res))", "e": 27425, "s": 27016, "text": null }, { "code": null, "e": 27467, "s": 27425, "text": "The index of last element occurrence: 10\n" }, { "code": null, "e": 27663, "s": 27467, "text": " Method #3 : Using max() + enumerate()We use enumerate function to get the list of all the elements having the particular element and then max() is employed to get max i.e last index of the list." }, { "code": "# Python3 code to demonstrate # to get last element occurrence# using max() + enumerate() # initializing listtest_list = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # using max() + enumerate()# to get last element occurrenceres = max(idx for idx, val in enumerate(test_list) if val == 'e') # printing resultprint (\"The index of last element occurrence: \" + str(res))", "e": 28118, "s": 27663, "text": null }, { "code": null, "e": 28160, "s": 28118, "text": "The index of last element occurrence: 10\n" }, { "code": null, "e": 28181, "s": 28160, "text": "Python list-programs" }, { "code": null, "e": 28188, "s": 28181, "text": "Python" }, { "code": null, "e": 28204, "s": 28188, "text": "Python Programs" }, { "code": null, "e": 28302, "s": 28204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28320, "s": 28302, "text": "Python Dictionary" }, { "code": null, "e": 28352, "s": 28320, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28374, "s": 28352, "text": "Enumerate() in Python" }, { "code": null, "e": 28416, "s": 28374, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28442, "s": 28416, "text": "Python String | replace()" }, { "code": null, "e": 28485, "s": 28442, "text": "Python program to convert a list to string" }, { "code": null, "e": 28507, "s": 28485, "text": "Defaultdict in Python" }, { "code": null, "e": 28546, "s": 28507, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28592, "s": 28546, "text": "Python | Split string into list of characters" } ]
Why use Guzzle Instead of cURL in PHP ? - GeeksforGeeks
17 Jan, 2022 What is cURL? cURL is a module in PHP with we can use libcurl. The libcurl is a library that is used in PHP to create connection and communicate with various kinds of different servers which may have different type of protocols. cURl provide us various pre-built functions like – curl_init(), curl_setopt(), curl_exec(), curl_close().Limitations of cURL: cURL does not support any recursive download logic. cURL requires extra options to download. Does not provide us with asynchronus and synchronous requests. Example: These are the request made by using cURL. PHP <?php> // Get cURL resource$curl = curl_init();// Set some optionscurl_setopt($ch, CURLOPT_POST, "https://jsonplaceholder.typicode.com/users"); curl_setopt($ch, CURLOPT_POST, false) ; curl_setopt($ch, CURLOPT_RETURNTANSFER, false) ;$result = curl_exec($ch);curl_close($ch); ?> Output: What is Guzzle? Guzzle is a Microframework (abstraction layer) that is a PHP HTTP client due to which the HTTP request is sent easily and it is trivial to integrate with web services. Guzzle can be used with any HTTP handler like cURL, socket, PHP’s stream wrapper. Guzzle by default uses cURL as Http handler. Why use Guzzle Instead of cURL in PHP? It provides easy user interface. Guzzle can use various kinds of HTTP clients . It allows us with the facility of asynchronus and synchronous requests. Guzzle has built-in unit testing support which makes it easier to write unit tests for app and mock the http requests. Example: These are the request made by using Guzzle. PHP <?php use GuzzleHTTP\Client;require '>>/vendor/autoload.php'; $client = new Client([ 'base_uri'=>'http://httpbin.org', 'timeout' => 2.0]); $response = $client->request('GET', 'ip'); echo $response->getStatusCOde(), "<br>";$body = $response->getBody();echo $body->getContents(), "<br>"; echo "<pre>";print_r(get_class_methods($body));echo "</pre>";echo "<pre>";print_r(get_class_methods($response));echo "</pre>";?> Output: saurabh1990aror PHP-Misc Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function Different ways for passing data to view in Laravel How to pass form variables from one page to other page in PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26217, "s": 26189, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26574, "s": 26217, "text": "What is cURL? cURL is a module in PHP with we can use libcurl. The libcurl is a library that is used in PHP to create connection and communicate with various kinds of different servers which may have different type of protocols. cURl provide us various pre-built functions like – curl_init(), curl_setopt(), curl_exec(), curl_close().Limitations of cURL: " }, { "code": null, "e": 26626, "s": 26574, "text": "cURL does not support any recursive download logic." }, { "code": null, "e": 26667, "s": 26626, "text": "cURL requires extra options to download." }, { "code": null, "e": 26730, "s": 26667, "text": "Does not provide us with asynchronus and synchronous requests." }, { "code": null, "e": 26782, "s": 26730, "text": "Example: These are the request made by using cURL. " }, { "code": null, "e": 26786, "s": 26782, "text": "PHP" }, { "code": "<?php> // Get cURL resource$curl = curl_init();// Set some optionscurl_setopt($ch, CURLOPT_POST, \"https://jsonplaceholder.typicode.com/users\"); curl_setopt($ch, CURLOPT_POST, false) ; curl_setopt($ch, CURLOPT_RETURNTANSFER, false) ;$result = curl_exec($ch);curl_close($ch); ?>", "e": 27066, "s": 26786, "text": null }, { "code": null, "e": 27076, "s": 27066, "text": "Output: " }, { "code": null, "e": 27428, "s": 27076, "text": "What is Guzzle? Guzzle is a Microframework (abstraction layer) that is a PHP HTTP client due to which the HTTP request is sent easily and it is trivial to integrate with web services. Guzzle can be used with any HTTP handler like cURL, socket, PHP’s stream wrapper. Guzzle by default uses cURL as Http handler. Why use Guzzle Instead of cURL in PHP? " }, { "code": null, "e": 27461, "s": 27428, "text": "It provides easy user interface." }, { "code": null, "e": 27508, "s": 27461, "text": "Guzzle can use various kinds of HTTP clients ." }, { "code": null, "e": 27580, "s": 27508, "text": "It allows us with the facility of asynchronus and synchronous requests." }, { "code": null, "e": 27699, "s": 27580, "text": "Guzzle has built-in unit testing support which makes it easier to write unit tests for app and mock the http requests." }, { "code": null, "e": 27753, "s": 27699, "text": "Example: These are the request made by using Guzzle. " }, { "code": null, "e": 27757, "s": 27753, "text": "PHP" }, { "code": "<?php use GuzzleHTTP\\Client;require '>>/vendor/autoload.php'; $client = new Client([ 'base_uri'=>'http://httpbin.org', 'timeout' => 2.0]); $response = $client->request('GET', 'ip'); echo $response->getStatusCOde(), \"<br>\";$body = $response->getBody();echo $body->getContents(), \"<br>\"; echo \"<pre>\";print_r(get_class_methods($body));echo \"</pre>\";echo \"<pre>\";print_r(get_class_methods($response));echo \"</pre>\";?>", "e": 28178, "s": 27757, "text": null }, { "code": null, "e": 28188, "s": 28178, "text": "Output: " }, { "code": null, "e": 28206, "s": 28190, "text": "saurabh1990aror" }, { "code": null, "e": 28215, "s": 28206, "text": "PHP-Misc" }, { "code": null, "e": 28222, "s": 28215, "text": "Picked" }, { "code": null, "e": 28226, "s": 28222, "text": "PHP" }, { "code": null, "e": 28243, "s": 28226, "text": "Web Technologies" }, { "code": null, "e": 28247, "s": 28243, "text": "PHP" }, { "code": null, "e": 28345, "s": 28247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28427, "s": 28345, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28469, "s": 28427, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 28496, "s": 28469, "text": "PHP str_replace() Function" }, { "code": null, "e": 28547, "s": 28496, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 28611, "s": 28547, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 28651, "s": 28611, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28684, "s": 28651, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28729, "s": 28684, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28772, "s": 28729, "text": "How to fetch data from an API in ReactJS ?" } ]
Create Heatmap in R - GeeksforGeeks
29 Dec, 2021 Heatmap is a graphical way to represent data. It is most commonly used in data analysis. In data analysis, we explore the dataset and draws insight from the dataset, we try to find the hidden patterns in the data by doing a visual analysis of the data. Heatmap visualizes the value of the matrix with colours, where brighter the colour means the higher the value is, and lighter the colour means the lower the value is. In Heatmap, we use warmth to cool colour scheme. Heatmap is a so-called heatmap because in heatmap we map the colours onto the different values that we have in our dataset. In this article, we will discuss how to create heatmaps in R Programming Language. geom_tile() is used to create a 2-Dimensional heatmap with the plane rectangular tiles in it. It comes pre-installed with the ggplot2 package for R programming. Syntax: geom_tile( mapping =NULL, data=NULL, stat=”Identity”,...) Parameter: mapping: It can be “aes”. “aes” is an acronym for aesthetic mapping. It describes how variables in the data are mapped to the visual properties of the geometry. data: It holds the dataset variable, a variable where we have stored our dataset in the script. stat: It is used to perform any kind of statistical operation on the dataset. To create a heatmap, first, import the required libraries and then either create or load a dataset. Now simply call geom_tile() function with the appropriate values for parameters. Example: R # Plotting Heatmap in R # adding ggplot2 library for plottinglibrary(ggplot2) # Creating random dataset# with 20 alphabets and 20 animal names letters <- LETTERS[1:20]animal_names <- c("Canidae","Felidae","Cat","Cattle", "Dog","Donkey","Goat","Guinea pig", "Horse","Pig","Rabbit","Badger", "Bald eagle","Bandicoot","Barnacle", "Bass","Bat","Bear","Beaver","Bedbug", "Bee","Beetle") data <- expand.grid(X=letters, Y=animal_names)data$count <- runif(440, 0, 6) # plotting the heatmapplt <- ggplot(data,aes( X, Y,fill=count))plt <- plt + geom_tile() # further customizing the heatmap by# applying colors and titleplt <- plt + theme_minimal() # setting gradient color as red and whiteplt <- plt + scale_fill_gradient(low="white", high="red") # setting the title and subtitles using# title and subtitleplt <- plt + labs(title = "Heatmap")plt <- plt + labs(subtitle = "A simple heatmap using geom_tile()") # setting x and y labels using labsplt <- plt + labs(x ="Alphabets", y ="Random column names") # plotting the Heatmapplt R # Plotting Heatmap in R # adding ggplot2 library for plottinglibrary(ggplot2) # Creating random dataset# with 20 alphabets and 20 animal names letters <- LETTERS[1:20]animal_names <- c("Canidae","Felidae","Cat","Cattle", "Dog","Donkey","Goat","Guinea pig", "Horse","Pig","Rabbit","Badger", "Bald eagle","Bandicoot","Barnacle", "Bass","Bat","Bear","Beaver","Bedbug", "Bee","Beetle") data <- expand.grid(X=letters, Y=animal_names)data$count <- runif(440, 0, 6) # plotting the heatmapplt <- ggplot(data,aes( X, Y,fill=count))plt <- plt + geom_tile() # further customizing the heatmap by# applying colors and titleplt <- plt + theme_minimal() # setting gradient color as red and whiteplt <- plt + scale_fill_gradient(low="white", high="red") # setting the title and subtitles using# title and subtitleplt <- plt + labs(title = "Heatmap")plt <- plt + labs(subtitle = "A simple heatmap using geom_tile()") # setting x and y labels using labsplt <- plt + labs(x ="Alphabets", y ="Random column names") # plotting the Heatmapplt Output: Heatmap using ggplot2 heatmap() function comes with the default installation of the Base R. One can use the default heatmap() also if he does not want to install any extra package. We can plot heatmap of the dataset using this heatmap function from the R. Syntax: heatmap(data,main = NULL, xlab = NULL, ylab = NULL,...) Parameter: data: data specifies the matrix of the data for which we wanted to plot a Heatmap. main: main is a string argument, and it specifies the title of the plot. xlab: xlab is used to specify the x-axis labels. ylab: ylab is used to specify the y-axis labels. Here the task is straightforward. You only need to put in the values that the function heatmap() requires. Example: R # Heatplot from Base R# using default mtcars dataset from the Rx <- as.matrix(mtcars) # custom colorsnew_colors <- colorRampPalette(c("cyan", "darkgreen")) # plotting the heatmapplt <- heatmap(x, # assigning new colors col = new_colors(100), # adding title main = "Heatmap for mtcars dataset", # adding some margin so that # it doesn not drawn over the # y-axis label margins = c(5,10), # adding x-axis labels xlab = "variables", # adding y-axis labels ylab = "Car Models", # to scaled the values into # column direction scale = "column") Output: Heatmap rajeev0719singh simranarora5sos arorakashish0911 Picked R-Charts R-ggplot R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R Logistic Regression in R Programming R - if statement
[ { "code": null, "e": 26487, "s": 26459, "text": "\n29 Dec, 2021" }, { "code": null, "e": 27080, "s": 26487, "text": "Heatmap is a graphical way to represent data. It is most commonly used in data analysis. In data analysis, we explore the dataset and draws insight from the dataset, we try to find the hidden patterns in the data by doing a visual analysis of the data. Heatmap visualizes the value of the matrix with colours, where brighter the colour means the higher the value is, and lighter the colour means the lower the value is. In Heatmap, we use warmth to cool colour scheme. Heatmap is a so-called heatmap because in heatmap we map the colours onto the different values that we have in our dataset." }, { "code": null, "e": 27163, "s": 27080, "text": "In this article, we will discuss how to create heatmaps in R Programming Language." }, { "code": null, "e": 27324, "s": 27163, "text": "geom_tile() is used to create a 2-Dimensional heatmap with the plane rectangular tiles in it. It comes pre-installed with the ggplot2 package for R programming." }, { "code": null, "e": 27332, "s": 27324, "text": "Syntax:" }, { "code": null, "e": 27390, "s": 27332, "text": "geom_tile( mapping =NULL, data=NULL, stat=”Identity”,...)" }, { "code": null, "e": 27401, "s": 27390, "text": "Parameter:" }, { "code": null, "e": 27562, "s": 27401, "text": "mapping: It can be “aes”. “aes” is an acronym for aesthetic mapping. It describes how variables in the data are mapped to the visual properties of the geometry." }, { "code": null, "e": 27658, "s": 27562, "text": "data: It holds the dataset variable, a variable where we have stored our dataset in the script." }, { "code": null, "e": 27736, "s": 27658, "text": "stat: It is used to perform any kind of statistical operation on the dataset." }, { "code": null, "e": 27917, "s": 27736, "text": "To create a heatmap, first, import the required libraries and then either create or load a dataset. Now simply call geom_tile() function with the appropriate values for parameters." }, { "code": null, "e": 27926, "s": 27917, "text": "Example:" }, { "code": null, "e": 27928, "s": 27926, "text": "R" }, { "code": "# Plotting Heatmap in R # adding ggplot2 library for plottinglibrary(ggplot2) # Creating random dataset# with 20 alphabets and 20 animal names letters <- LETTERS[1:20]animal_names <- c(\"Canidae\",\"Felidae\",\"Cat\",\"Cattle\", \"Dog\",\"Donkey\",\"Goat\",\"Guinea pig\", \"Horse\",\"Pig\",\"Rabbit\",\"Badger\", \"Bald eagle\",\"Bandicoot\",\"Barnacle\", \"Bass\",\"Bat\",\"Bear\",\"Beaver\",\"Bedbug\", \"Bee\",\"Beetle\") data <- expand.grid(X=letters, Y=animal_names)data$count <- runif(440, 0, 6) # plotting the heatmapplt <- ggplot(data,aes( X, Y,fill=count))plt <- plt + geom_tile() # further customizing the heatmap by# applying colors and titleplt <- plt + theme_minimal() # setting gradient color as red and whiteplt <- plt + scale_fill_gradient(low=\"white\", high=\"red\") # setting the title and subtitles using# title and subtitleplt <- plt + labs(title = \"Heatmap\")plt <- plt + labs(subtitle = \"A simple heatmap using geom_tile()\") # setting x and y labels using labsplt <- plt + labs(x =\"Alphabets\", y =\"Random column names\") # plotting the Heatmapplt", "e": 29043, "s": 27928, "text": null }, { "code": null, "e": 29049, "s": 29047, "text": "R" }, { "code": "# Plotting Heatmap in R # adding ggplot2 library for plottinglibrary(ggplot2) # Creating random dataset# with 20 alphabets and 20 animal names letters <- LETTERS[1:20]animal_names <- c(\"Canidae\",\"Felidae\",\"Cat\",\"Cattle\", \"Dog\",\"Donkey\",\"Goat\",\"Guinea pig\", \"Horse\",\"Pig\",\"Rabbit\",\"Badger\", \"Bald eagle\",\"Bandicoot\",\"Barnacle\", \"Bass\",\"Bat\",\"Bear\",\"Beaver\",\"Bedbug\", \"Bee\",\"Beetle\") data <- expand.grid(X=letters, Y=animal_names)data$count <- runif(440, 0, 6) # plotting the heatmapplt <- ggplot(data,aes( X, Y,fill=count))plt <- plt + geom_tile() # further customizing the heatmap by# applying colors and titleplt <- plt + theme_minimal() # setting gradient color as red and whiteplt <- plt + scale_fill_gradient(low=\"white\", high=\"red\") # setting the title and subtitles using# title and subtitleplt <- plt + labs(title = \"Heatmap\")plt <- plt + labs(subtitle = \"A simple heatmap using geom_tile()\") # setting x and y labels using labsplt <- plt + labs(x =\"Alphabets\", y =\"Random column names\") # plotting the Heatmapplt", "e": 30164, "s": 29049, "text": null }, { "code": null, "e": 30172, "s": 30164, "text": "Output:" }, { "code": null, "e": 30196, "s": 30174, "text": "Heatmap using ggplot2" }, { "code": null, "e": 30434, "s": 30198, "text": "heatmap() function comes with the default installation of the Base R. One can use the default heatmap() also if he does not want to install any extra package. We can plot heatmap of the dataset using this heatmap function from the R. " }, { "code": null, "e": 30444, "s": 30436, "text": "Syntax:" }, { "code": null, "e": 30500, "s": 30444, "text": "heatmap(data,main = NULL, xlab = NULL, ylab = NULL,...)" }, { "code": null, "e": 30511, "s": 30500, "text": "Parameter:" }, { "code": null, "e": 30594, "s": 30511, "text": "data: data specifies the matrix of the data for which we wanted to plot a Heatmap." }, { "code": null, "e": 30667, "s": 30594, "text": "main: main is a string argument, and it specifies the title of the plot." }, { "code": null, "e": 30716, "s": 30667, "text": "xlab: xlab is used to specify the x-axis labels." }, { "code": null, "e": 30765, "s": 30716, "text": "ylab: ylab is used to specify the y-axis labels." }, { "code": null, "e": 30874, "s": 30767, "text": "Here the task is straightforward. You only need to put in the values that the function heatmap() requires." }, { "code": null, "e": 30885, "s": 30876, "text": "Example:" }, { "code": null, "e": 30889, "s": 30887, "text": "R" }, { "code": "# Heatplot from Base R# using default mtcars dataset from the Rx <- as.matrix(mtcars) # custom colorsnew_colors <- colorRampPalette(c(\"cyan\", \"darkgreen\")) # plotting the heatmapplt <- heatmap(x, # assigning new colors col = new_colors(100), # adding title main = \"Heatmap for mtcars dataset\", # adding some margin so that # it doesn not drawn over the # y-axis label margins = c(5,10), # adding x-axis labels xlab = \"variables\", # adding y-axis labels ylab = \"Car Models\", # to scaled the values into # column direction scale = \"column\")", "e": 31730, "s": 30889, "text": null }, { "code": null, "e": 31742, "s": 31734, "text": "Output:" }, { "code": null, "e": 31752, "s": 31744, "text": "Heatmap" }, { "code": null, "e": 31770, "s": 31754, "text": "rajeev0719singh" }, { "code": null, "e": 31786, "s": 31770, "text": "simranarora5sos" }, { "code": null, "e": 31803, "s": 31786, "text": "arorakashish0911" }, { "code": null, "e": 31810, "s": 31803, "text": "Picked" }, { "code": null, "e": 31819, "s": 31810, "text": "R-Charts" }, { "code": null, "e": 31828, "s": 31819, "text": "R-ggplot" }, { "code": null, "e": 31837, "s": 31828, "text": "R-Graphs" }, { "code": null, "e": 31845, "s": 31837, "text": "R-plots" }, { "code": null, "e": 31856, "s": 31845, "text": "R Language" }, { "code": null, "e": 31954, "s": 31856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32006, "s": 31954, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32041, "s": 32006, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32079, "s": 32041, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32137, "s": 32079, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32180, "s": 32137, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32217, "s": 32180, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 32266, "s": 32217, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 32292, "s": 32266, "text": "Time Series Analysis in R" }, { "code": null, "e": 32329, "s": 32292, "text": "Logistic Regression in R Programming" } ]
How to Create a Package in Java? - GeeksforGeeks
01 Nov, 2021 Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related classes where some classes are accessible are exposed and others are kept for internal purposes. We can reuse existing classes from the packages as many times as we need them in our program. Package names and directory structure are closely related Ways: There are two types of packages in java: User-defined Package (Create Your Own Package’s)Built-in packages are packages from the java application programming interface that are the packages from Java API for example such as swing, util, net, io, AWT, lang, javax, etc. User-defined Package (Create Your Own Package’s) Built-in packages are packages from the java application programming interface that are the packages from Java API for example such as swing, util, net, io, AWT, lang, javax, etc. In this article, we will see How To Create A Package In Java?. A package is a group of similar types of Classes, Interfaces, and sub-packages. We use Packages in order to avoid name conflicts. Syntax: To import a package import package.name.*; Example: To import a package Java // Java Program to Import a package // Importing java utility packageimport java.util.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Scanner to take input from the user object Scanner myObj = new Scanner(System.in); String userName; // Display message // Enter Your Name And Press Enter System.out.println("Enter You Name"); // Reading the integer age entered using // nextInt() method userName = myObj.nextLine(); // Print and display System.out.println("Your Name IS : " + userName); }} Enter You Name Your Name IS : 0 Here In The Above Program, ‘java.util’ package is imported and run for a simple program. These are called as Inbuilt Packages. Now in order to create a package in java follow the certain steps as described below: First We Should Choose A Name For The Package We Are Going To Create And Include. The package command In The first line in the java program source code.Further inclusion of classes, interfaces, annotation types, etc that is required in the package can be made in the package. For example, the below single statement creates a package name called “FirstPackage”. First We Should Choose A Name For The Package We Are Going To Create And Include. The package command In The first line in the java program source code. Further inclusion of classes, interfaces, annotation types, etc that is required in the package can be made in the package. For example, the below single statement creates a package name called “FirstPackage”. Syntax: To declare the name of the package to be created. The package statement simply defines in which package the classes defined belong. package FirstPackage ; Implementation: To Create a Class Inside A Package First Declare The Package Name As The First Statement Of Our Program.Then We Can Include A Class As A Part Of The Package. First Declare The Package Name As The First Statement Of Our Program. Then We Can Include A Class As A Part Of The Package. Example 1: Java // Name of package to be createdpackage FirstPackage; // Class in which the above created package belong toclass Welcome { // main driver method public static void main(String[] args) { // Print statement for the successful // compilation and execution of the program System.out.println( "This Is The First Program Geeks For Geeks.."); }} So Inorder to generate the above-desired output first do use the commands as specified use the following specified commands Procedure: 1. To generate the output from the above program Command: javac Welcome.java 2. The Above Command Will Give Us Welcome.class File. Command: javac -d . Welcome.java 3. So This Command Will Create a New Folder Called FirstPackage. Command: java FirstPackage.Welcome Output: The Above Will Give The Final Output Of The Example Program This Is The Output Of The Above Program Example 2: Java // Name of package to be createdpackage data; // Class to which the above package belongspublic class Demo { // Member functions of the class- 'Demo' // Method 1 - To show() public void show() { // Print message System.out.println("Hi Everyone"); } // Method 2 - To show() public void view() { // Print message System.out.println("Hello"); }} Again, in order to generate the above-desired output first do use the commands as specified use the following specified commands Procedure: 1. To generate the output from the above program Command: javac Demo.java 2. This Command Will Give Us a Class File Command: javac -d . Demo.java 3. So This Command Will Create a New Folder Called data. Note: In data Demo.java & Demo.class File should be present Example 3: Data will be tried to be accessed now from another program Java // Name of the packageimport data.*; // Class to which the package belongsclass ncj { // main driver method public static void main(String arg[]) { // Creating an object of Demo class Demo d = new Demo(); // Calling the functions show() and view() // using the object of Demo class d.show(); d.view(); }} Again the following commands will be used in order to generate the output as first a file ill be created ‘ncj.java’ outside the data directory. Command: javac Demo.java The Above Command Will Give us a class file that is non-runnable so we do need a command further to make it an executable run file. Command: java ncj // To Run This File Output: Generated on the terminal after the above command Is executed Hi Everyone Hello arorakashish0911 addyjeridiq Java-Packages Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25250, "s": 25222, "text": "\n01 Nov, 2021" }, { "code": null, "e": 25796, "s": 25250, "text": "Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related classes where some classes are accessible are exposed and others are kept for internal purposes. We can reuse existing classes from the packages as many times as we need them in our program. Package names and directory structure are closely related" }, { "code": null, "e": 25843, "s": 25796, "text": "Ways: There are two types of packages in java:" }, { "code": null, "e": 26071, "s": 25843, "text": "User-defined Package (Create Your Own Package’s)Built-in packages are packages from the java application programming interface that are the packages from Java API for example such as swing, util, net, io, AWT, lang, javax, etc." }, { "code": null, "e": 26120, "s": 26071, "text": "User-defined Package (Create Your Own Package’s)" }, { "code": null, "e": 26300, "s": 26120, "text": "Built-in packages are packages from the java application programming interface that are the packages from Java API for example such as swing, util, net, io, AWT, lang, javax, etc." }, { "code": null, "e": 26494, "s": 26300, "text": "In this article, we will see How To Create A Package In Java?. A package is a group of similar types of Classes, Interfaces, and sub-packages. We use Packages in order to avoid name conflicts. " }, { "code": null, "e": 26522, "s": 26494, "text": "Syntax: To import a package" }, { "code": null, "e": 26545, "s": 26522, "text": "import package.name.*;" }, { "code": null, "e": 26574, "s": 26545, "text": "Example: To import a package" }, { "code": null, "e": 26579, "s": 26574, "text": "Java" }, { "code": "// Java Program to Import a package // Importing java utility packageimport java.util.*; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Scanner to take input from the user object Scanner myObj = new Scanner(System.in); String userName; // Display message // Enter Your Name And Press Enter System.out.println(\"Enter You Name\"); // Reading the integer age entered using // nextInt() method userName = myObj.nextLine(); // Print and display System.out.println(\"Your Name IS : \" + userName); }}", "e": 27209, "s": 26579, "text": null }, { "code": null, "e": 27241, "s": 27209, "text": "Enter You Name\nYour Name IS : 0" }, { "code": null, "e": 27369, "s": 27241, "text": "Here In The Above Program, ‘java.util’ package is imported and run for a simple program. These are called as Inbuilt Packages. " }, { "code": null, "e": 27456, "s": 27369, "text": "Now in order to create a package in java follow the certain steps as described below: " }, { "code": null, "e": 27818, "s": 27456, "text": "First We Should Choose A Name For The Package We Are Going To Create And Include. The package command In The first line in the java program source code.Further inclusion of classes, interfaces, annotation types, etc that is required in the package can be made in the package. For example, the below single statement creates a package name called “FirstPackage”." }, { "code": null, "e": 27971, "s": 27818, "text": "First We Should Choose A Name For The Package We Are Going To Create And Include. The package command In The first line in the java program source code." }, { "code": null, "e": 28181, "s": 27971, "text": "Further inclusion of classes, interfaces, annotation types, etc that is required in the package can be made in the package. For example, the below single statement creates a package name called “FirstPackage”." }, { "code": null, "e": 28321, "s": 28181, "text": "Syntax: To declare the name of the package to be created. The package statement simply defines in which package the classes defined belong." }, { "code": null, "e": 28344, "s": 28321, "text": "package FirstPackage ;" }, { "code": null, "e": 28396, "s": 28344, "text": "Implementation: To Create a Class Inside A Package " }, { "code": null, "e": 28519, "s": 28396, "text": "First Declare The Package Name As The First Statement Of Our Program.Then We Can Include A Class As A Part Of The Package." }, { "code": null, "e": 28589, "s": 28519, "text": "First Declare The Package Name As The First Statement Of Our Program." }, { "code": null, "e": 28643, "s": 28589, "text": "Then We Can Include A Class As A Part Of The Package." }, { "code": null, "e": 28655, "s": 28643, "text": "Example 1: " }, { "code": null, "e": 28660, "s": 28655, "text": "Java" }, { "code": "// Name of package to be createdpackage FirstPackage; // Class in which the above created package belong toclass Welcome { // main driver method public static void main(String[] args) { // Print statement for the successful // compilation and execution of the program System.out.println( \"This Is The First Program Geeks For Geeks..\"); }}", "e": 29043, "s": 28660, "text": null }, { "code": null, "e": 29167, "s": 29043, "text": "So Inorder to generate the above-desired output first do use the commands as specified use the following specified commands" }, { "code": null, "e": 29179, "s": 29167, "text": "Procedure: " }, { "code": null, "e": 29229, "s": 29179, "text": "1. To generate the output from the above program " }, { "code": null, "e": 29258, "s": 29229, "text": "Command: javac Welcome.java " }, { "code": null, "e": 29313, "s": 29258, "text": "2. The Above Command Will Give Us Welcome.class File. " }, { "code": null, "e": 29347, "s": 29313, "text": "Command: javac -d . Welcome.java " }, { "code": null, "e": 29414, "s": 29347, "text": "3. So This Command Will Create a New Folder Called FirstPackage. " }, { "code": null, "e": 29450, "s": 29414, "text": "Command: java FirstPackage.Welcome " }, { "code": null, "e": 29518, "s": 29450, "text": "Output: The Above Will Give The Final Output Of The Example Program" }, { "code": null, "e": 29558, "s": 29518, "text": "This Is The Output Of The Above Program" }, { "code": null, "e": 29570, "s": 29558, "text": "Example 2: " }, { "code": null, "e": 29575, "s": 29570, "text": "Java" }, { "code": "// Name of package to be createdpackage data; // Class to which the above package belongspublic class Demo { // Member functions of the class- 'Demo' // Method 1 - To show() public void show() { // Print message System.out.println(\"Hi Everyone\"); } // Method 2 - To show() public void view() { // Print message System.out.println(\"Hello\"); }}", "e": 29976, "s": 29575, "text": null }, { "code": null, "e": 30105, "s": 29976, "text": "Again, in order to generate the above-desired output first do use the commands as specified use the following specified commands" }, { "code": null, "e": 30117, "s": 30105, "text": "Procedure: " }, { "code": null, "e": 30167, "s": 30117, "text": "1. To generate the output from the above program " }, { "code": null, "e": 30193, "s": 30167, "text": "Command: javac Demo.java " }, { "code": null, "e": 30237, "s": 30193, "text": "2. This Command Will Give Us a Class File " }, { "code": null, "e": 30268, "s": 30237, "text": "Command: javac -d . Demo.java " }, { "code": null, "e": 30326, "s": 30268, "text": "3. So This Command Will Create a New Folder Called data. " }, { "code": null, "e": 30387, "s": 30326, "text": "Note: In data Demo.java & Demo.class File should be present " }, { "code": null, "e": 30458, "s": 30387, "text": "Example 3: Data will be tried to be accessed now from another program " }, { "code": null, "e": 30463, "s": 30458, "text": "Java" }, { "code": "// Name of the packageimport data.*; // Class to which the package belongsclass ncj { // main driver method public static void main(String arg[]) { // Creating an object of Demo class Demo d = new Demo(); // Calling the functions show() and view() // using the object of Demo class d.show(); d.view(); }}", "e": 30825, "s": 30463, "text": null }, { "code": null, "e": 30969, "s": 30825, "text": "Again the following commands will be used in order to generate the output as first a file ill be created ‘ncj.java’ outside the data directory." }, { "code": null, "e": 30995, "s": 30969, "text": "Command: javac Demo.java " }, { "code": null, "e": 31130, "s": 30995, "text": "The Above Command Will Give us a class file that is non-runnable so we do need a command further to make it an executable run file. " }, { "code": null, "e": 31170, "s": 31130, "text": "Command: java ncj \n// To Run This File " }, { "code": null, "e": 31241, "s": 31170, "text": "Output: Generated on the terminal after the above command Is executed " }, { "code": null, "e": 31260, "s": 31241, "text": "Hi Everyone\nHello " }, { "code": null, "e": 31277, "s": 31260, "text": "arorakashish0911" }, { "code": null, "e": 31289, "s": 31277, "text": "addyjeridiq" }, { "code": null, "e": 31303, "s": 31289, "text": "Java-Packages" }, { "code": null, "e": 31310, "s": 31303, "text": "Picked" }, { "code": null, "e": 31315, "s": 31310, "text": "Java" }, { "code": null, "e": 31329, "s": 31315, "text": "Java Programs" }, { "code": null, "e": 31334, "s": 31329, "text": "Java" }, { "code": null, "e": 31432, "s": 31334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31447, "s": 31432, "text": "Stream In Java" }, { "code": null, "e": 31468, "s": 31447, "text": "Constructors in Java" }, { "code": null, "e": 31487, "s": 31468, "text": "Exceptions in Java" }, { "code": null, "e": 31517, "s": 31487, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31563, "s": 31517, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31589, "s": 31563, "text": "Java Programming Examples" }, { "code": null, "e": 31623, "s": 31589, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 31670, "s": 31623, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 31702, "s": 31670, "text": "How to Iterate HashMap in Java?" } ]
Python - Write "GFG" using Turtle Graphics - GeeksforGeeks
03 Jun, 2020 IN this article we will learn how to write “GFG” using Turtle Graphics in Python. For that lets first know what is Turtle Graphics. backward(length): moves the pen in the backward direction by x unit. right(angle): rotate the pen in the clockwise direction by an angle x. left(angle): rotate the pen in the anticlockwise direction by an angle x. penup(): stop drawing of the turtle pen. pendown(): start drawing of the turtle pen. import the turtle modules.import turtle import turtle Get a screen to draw onws=turtle.Screen() ws=turtle.Screen() Define an instance for turtle. for printing G we have to make a semicircle and then complete it by rotating the turtle and moving it forward. Then for F move pen up using penup() , then goto() to desired coordinates, then pen it down for drawing using pendown() and draw F. for remaining G go to other coordinates and do same as done for 1st G. Below is the python implementation for the above approach: Python3 #python program for printing "GFG"#importing turtle modulesimport turtle #setting up workscreenws=turtle.Screen() #defining turtle instancet=turtle.Turtle() #turtle pen will be of "GREEN" colort.color("Green") #setting width of pent.width(3) #for printing letter "G"for x in range(180): t.backward(1) t.left(1)t.right(90)t.forward(50)t.right(90)t.forward(30)t.right(90)t.forward(50) #for printing letter "F"t.penup()t.goto(40,0)t.pendown()t.forward(110)t.goto(40,0)t.left(90)t.forward(50)t.penup()t.goto(40,-50)t.pendown()t.forward(40) #for printing letter "G"t.penup()t.goto(150,0)t.pendown()for x in range(180): t.backward(1) t.left(1)t.right(90)t.forward(50)t.right(90)t.forward(30)t.right(90)t.forward(50) Python-turtle Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25831, "s": 25803, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25963, "s": 25831, "text": "IN this article we will learn how to write “GFG” using Turtle Graphics in Python. For that lets first know what is Turtle Graphics." }, { "code": null, "e": 26032, "s": 25963, "text": "backward(length): moves the pen in the backward direction by x unit." }, { "code": null, "e": 26103, "s": 26032, "text": "right(angle): rotate the pen in the clockwise direction by an angle x." }, { "code": null, "e": 26177, "s": 26103, "text": "left(angle): rotate the pen in the anticlockwise direction by an angle x." }, { "code": null, "e": 26218, "s": 26177, "text": "penup(): stop drawing of the turtle pen." }, { "code": null, "e": 26262, "s": 26218, "text": "pendown(): start drawing of the turtle pen." }, { "code": null, "e": 26302, "s": 26262, "text": "import the turtle modules.import turtle" }, { "code": null, "e": 26316, "s": 26302, "text": "import turtle" }, { "code": null, "e": 26358, "s": 26316, "text": "Get a screen to draw onws=turtle.Screen()" }, { "code": null, "e": 26377, "s": 26358, "text": "ws=turtle.Screen()" }, { "code": null, "e": 26408, "s": 26377, "text": "Define an instance for turtle." }, { "code": null, "e": 26519, "s": 26408, "text": "for printing G we have to make a semicircle and then complete it by rotating the turtle and moving it forward." }, { "code": null, "e": 26652, "s": 26519, "text": "Then for F move pen up using penup() , then goto() to desired coordinates, then pen it down for drawing using pendown() and draw F." }, { "code": null, "e": 26723, "s": 26652, "text": "for remaining G go to other coordinates and do same as done for 1st G." }, { "code": null, "e": 26782, "s": 26723, "text": "Below is the python implementation for the above approach:" }, { "code": null, "e": 26790, "s": 26782, "text": "Python3" }, { "code": "#python program for printing \"GFG\"#importing turtle modulesimport turtle #setting up workscreenws=turtle.Screen() #defining turtle instancet=turtle.Turtle() #turtle pen will be of \"GREEN\" colort.color(\"Green\") #setting width of pent.width(3) #for printing letter \"G\"for x in range(180): t.backward(1) t.left(1)t.right(90)t.forward(50)t.right(90)t.forward(30)t.right(90)t.forward(50) #for printing letter \"F\"t.penup()t.goto(40,0)t.pendown()t.forward(110)t.goto(40,0)t.left(90)t.forward(50)t.penup()t.goto(40,-50)t.pendown()t.forward(40) #for printing letter \"G\"t.penup()t.goto(150,0)t.pendown()for x in range(180): t.backward(1) t.left(1)t.right(90)t.forward(50)t.right(90)t.forward(30)t.right(90)t.forward(50)", "e": 27525, "s": 26790, "text": null }, { "code": null, "e": 27539, "s": 27525, "text": "Python-turtle" }, { "code": null, "e": 27546, "s": 27539, "text": "Python" }, { "code": null, "e": 27562, "s": 27546, "text": "Python Programs" }, { "code": null, "e": 27660, "s": 27562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27678, "s": 27660, "text": "Python Dictionary" }, { "code": null, "e": 27713, "s": 27678, "text": "Read a file line by line in Python" }, { "code": null, "e": 27745, "s": 27713, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27767, "s": 27745, "text": "Enumerate() in Python" }, { "code": null, "e": 27809, "s": 27767, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27852, "s": 27809, "text": "Python program to convert a list to string" }, { "code": null, "e": 27874, "s": 27852, "text": "Defaultdict in Python" }, { "code": null, "e": 27913, "s": 27874, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27959, "s": 27913, "text": "Python | Split string into list of characters" } ]
Comparing Streams to Loops in Java - GeeksforGeeks
21 Feb, 2022 A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation performs a function. Ideally, a function’s output in a stream depends only on its input arguments. A stream holds no non-transient stage. Every stream works essentially the same which is: Starts with a source of data. Processes the data through a pipeline of intermediate operations. Finishes with a terminal operation. By default, each aggregate operation in a stream runs its function sequentially, i.e., one after another in the caller’s thread of control. Streams can be created from Collections, Lists, Sets, ints, longs, doubles, arrays, lines of a file. Stream operations are either intermediate or terminal. Intermediate operations such as filter, map, or sort return a stream, so we can chain multiple intermediate operations. Terminal operations such as forEach, collect, or reduce are either void or return a non-stream result. Streams bring functional programming in Java and are supported starting in Java 8. The Java 8 stream is an implementation of the PQSA1 Pipes and Filter pattern. Example: Java // Java Program to Compare Streams to Loops // Importing required librariesimport java.io.IOException;import java.lang.String;import java.nio.file.*;import java.util.*;import java.util.Arrays;import java.util.List;import java.util.stream.*; // Main class// JavaStreamsclass GFG { // Main driver method public static void main(String[] args) throws IOException { // 1. Integer Stream System.out.println("Integer Stream : "); IntStream.range(1, 10).forEach(System.out::print); // New line System.out.println(); // 2. Integer Stream with skip System.out.println("Integer Stream with skip : "); IntStream.range(1, 10).skip(5).forEach( x -> System.out.println(x)); // New line System.out.println(); // 3. Integer Stream with sum System.out.println("Integer Stream with sum : "); System.out.println(IntStream.range(1, 5).sum()); // New line System.out.println(); // 4. Stream.of, sorted and findFirst System.out.println( "Stream.of, sorted and findFirst : "); Stream.of("Java ", "Scala ", "Ruby ") .sorted() .findFirst() .ifPresent(System.out::println); // New line System.out.println(); // 5. Stream from Array, sort, filter and print String[] names = { "AI", "Matlab", "Scikit", "TensorFlow", "OpenCV", "DeepLearning", "NLP", "NeuralNetworks", "Regression" }; System.out.println( "Stream from Array, sort, filter and print : "); Arrays .stream(names) // same as Stream.of(names) .filter(x -> x.startsWith("S")) .sorted() .forEach(System.out::println); // New line System.out.println(); // 6. average of squares of an int array System.out.println( "Average of squares of an int array : "); Arrays.stream(new int[] { 2, 4, 6, 8, 10 }) .map(x -> x * x) .average() .ifPresent(System.out::println); // New line System.out.println(); // 7. Stream from List, filter and print // Display message only System.out.println( "Stream from List, filter and print : "); List<String> people = Arrays.asList( "AI", "Matlab", "Scikit", "TensorFlow", "OpenCV", "DeepLearning", "NLP", "NeuralNetworks"); people.stream() .map(String::toLowerCase) .filter(x -> x.startsWith("a")) .forEach(System.out::println); // New line System.out.println(); // 8. Reduction - sum // Display message only System.out.println("Reduction - sum : "); double total = Stream.of(7.3, 1.5, 4.8) .reduce(0.0, (Double a, Double b) -> a + b); // Print and display System.out.println("Total = " + total); System.out.println(); // 9. Reduction - summary statistics System.out.println( "Reduction - summary statistics : "); IntSummaryStatistics summary = IntStream.of(7, 2, 19, 88, 73, 4, 10) .summaryStatistics(); // Print and display System.out.println(summary); System.out.println(); }} Integer Stream : 123456789 Integer Stream with skip : 6 7 8 9 Integer Stream with sum : 10 Stream.of, sorted and findFirst : Java Stream from Array, sort, filter and print : Scikit Average of squares of an int array : 44.0 Stream from List, filter and print : ai Reduction - sum : Total = 13.600000000000001 Reduction - summary statistics : IntSummaryStatistics{count=7, sum=203, min=2, average=29.000000, max=88} Now, discussing loops in order to figure out in order to land onto conclusive differences. Looping is a feature in Java that facilitates the execution of a set of instructions until the controlling Boolean expression evaluates to false. Different types of loops are provided to fit any programming need. Each loop has its own purpose and a suitable use case to serve. Example: Java // Java Program to Comparing Streams to Loops // Importing utility packagesimport java.util.*; // Class 1// helper classclass ProgrammingLanguage { // Member variables of this class int rank; String name; int value; // Member method of this class public ProgrammingLanguage(int rank, String name, int value) { // this keyword is used to refer current object // itself this.rank = rank; this.name = name; this.value = value; }} // Class 2// JavaStreamExamplepublic class GFG { // MAin driver method public static void main(String[] args) { // Creating an object of List class // Declaring object of user defined type (above // class) List<ProgrammingLanguage> programmingLanguage = new ArrayList<ProgrammingLanguage>(); // Adding elements to the object of this class // Custom input entries programmingLanguage.add( new ProgrammingLanguage(1, "Java", 7000)); programmingLanguage.add( new ProgrammingLanguage(2, "Rust", 2000)); programmingLanguage.add( new ProgrammingLanguage(3, "Ruby", 1500)); programmingLanguage.add( new ProgrammingLanguage(4, "Scala", 2500)); programmingLanguage.add( new ProgrammingLanguage(5, "Groovy", 4000)); // Creating object of List class of integer type List<Integer> languageValueList = new ArrayList<Integer>(); // For each loops for iteration for (ProgrammingLanguage language : programmingLanguage) { // Filtering data of List if (language.value < 3000) { // Adding price to above elements languageValueList.add(language.value); } } // Print and display all elements inside the object System.out.println(languageValueList); }} [2000, 1500, 2500] By far we have understood both of the concepts and come across to know they don’t go hand in hand, one has advantage over other as per the usage where it is to be used. Hence, wrapping off the article by illustrating their advantages which are as follows: Advantages of Streams Streams are a more declarative style. Or a more expressive style. Streams have a strong affinity with functions. Java 8 introduces lambdas and functional interfaces, which opens a whole toolbox of powerful techniques. Streams provide the most convenient and natural way to apply functions to sequences of objects. Streams encourage less mutability. This is sort of related to the functional programming aspect i.e., the kind of programs we write using streams tend to be the kind of programs where we don’t modify objects. Streams encourage looser coupling. Our stream-handling code doesn’t need to know the source of the stream or its eventual terminating method. Streams can succinctly express quite sophisticated behavior. Advantages of Loops Performance: A for loop through an array is extremely lightweight both in terms of heap and CPU usage. If raw speed and memory thriftiness is a priority, using a stream is worse. Familiarity: The world is full of experienced procedural programmers, from many language backgrounds, for whom loops are familiar and streams are novel. In some environments, you want to write code that’s familiar to that kind of person. Cognitive overhead: Because of its declarative nature, and increased abstraction from what’s happening underneath, you may need to build a new mental model of how code relates to execution. Actually, you only need to do this when things go wrong, or if you need to deeply analyze performance or subtle bugs. When it “just works”, it just works. Debuggers are improving, but even now, when we are stepping through stream code in a debugger, it can be harder work than the equivalent loop, because a simple loop is very close to the variables and code locations that a traditional debugger works with. Conclusion: If you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead. AshokJaiswal sweetyty anikakapoor arorakashish0911 as5853535 java-stream Picked 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 Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26103, "s": 26075, "text": "\n21 Feb, 2022" }, { "code": null, "e": 26591, "s": 26103, "text": "A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation performs a function. Ideally, a function’s output in a stream depends only on its input arguments. A stream holds no non-transient stage. Every stream works essentially the same which is:" }, { "code": null, "e": 26621, "s": 26591, "text": "Starts with a source of data." }, { "code": null, "e": 26687, "s": 26621, "text": "Processes the data through a pipeline of intermediate operations." }, { "code": null, "e": 26723, "s": 26687, "text": "Finishes with a terminal operation." }, { "code": null, "e": 26965, "s": 26723, "text": "By default, each aggregate operation in a stream runs its function sequentially, i.e., one after another in the caller’s thread of control. Streams can be created from Collections, Lists, Sets, ints, longs, doubles, arrays, lines of a file. " }, { "code": null, "e": 27404, "s": 26965, "text": "Stream operations are either intermediate or terminal. Intermediate operations such as filter, map, or sort return a stream, so we can chain multiple intermediate operations. Terminal operations such as forEach, collect, or reduce are either void or return a non-stream result. Streams bring functional programming in Java and are supported starting in Java 8. The Java 8 stream is an implementation of the PQSA1 Pipes and Filter pattern." }, { "code": null, "e": 27413, "s": 27404, "text": "Example:" }, { "code": null, "e": 27418, "s": 27413, "text": "Java" }, { "code": "// Java Program to Compare Streams to Loops // Importing required librariesimport java.io.IOException;import java.lang.String;import java.nio.file.*;import java.util.*;import java.util.Arrays;import java.util.List;import java.util.stream.*; // Main class// JavaStreamsclass GFG { // Main driver method public static void main(String[] args) throws IOException { // 1. Integer Stream System.out.println(\"Integer Stream : \"); IntStream.range(1, 10).forEach(System.out::print); // New line System.out.println(); // 2. Integer Stream with skip System.out.println(\"Integer Stream with skip : \"); IntStream.range(1, 10).skip(5).forEach( x -> System.out.println(x)); // New line System.out.println(); // 3. Integer Stream with sum System.out.println(\"Integer Stream with sum : \"); System.out.println(IntStream.range(1, 5).sum()); // New line System.out.println(); // 4. Stream.of, sorted and findFirst System.out.println( \"Stream.of, sorted and findFirst : \"); Stream.of(\"Java \", \"Scala \", \"Ruby \") .sorted() .findFirst() .ifPresent(System.out::println); // New line System.out.println(); // 5. Stream from Array, sort, filter and print String[] names = { \"AI\", \"Matlab\", \"Scikit\", \"TensorFlow\", \"OpenCV\", \"DeepLearning\", \"NLP\", \"NeuralNetworks\", \"Regression\" }; System.out.println( \"Stream from Array, sort, filter and print : \"); Arrays .stream(names) // same as Stream.of(names) .filter(x -> x.startsWith(\"S\")) .sorted() .forEach(System.out::println); // New line System.out.println(); // 6. average of squares of an int array System.out.println( \"Average of squares of an int array : \"); Arrays.stream(new int[] { 2, 4, 6, 8, 10 }) .map(x -> x * x) .average() .ifPresent(System.out::println); // New line System.out.println(); // 7. Stream from List, filter and print // Display message only System.out.println( \"Stream from List, filter and print : \"); List<String> people = Arrays.asList( \"AI\", \"Matlab\", \"Scikit\", \"TensorFlow\", \"OpenCV\", \"DeepLearning\", \"NLP\", \"NeuralNetworks\"); people.stream() .map(String::toLowerCase) .filter(x -> x.startsWith(\"a\")) .forEach(System.out::println); // New line System.out.println(); // 8. Reduction - sum // Display message only System.out.println(\"Reduction - sum : \"); double total = Stream.of(7.3, 1.5, 4.8) .reduce(0.0, (Double a, Double b) -> a + b); // Print and display System.out.println(\"Total = \" + total); System.out.println(); // 9. Reduction - summary statistics System.out.println( \"Reduction - summary statistics : \"); IntSummaryStatistics summary = IntStream.of(7, 2, 19, 88, 73, 4, 10) .summaryStatistics(); // Print and display System.out.println(summary); System.out.println(); }}", "e": 30901, "s": 27418, "text": null }, { "code": null, "e": 31335, "s": 30904, "text": "Integer Stream : \n123456789\nInteger Stream with skip : \n6\n7\n8\n9\n\nInteger Stream with sum : \n10\n\nStream.of, sorted and findFirst : \nJava \n\nStream from Array, sort, filter and print : \nScikit\n\nAverage of squares of an int array : \n44.0\n\nStream from List, filter and print : \nai\n\nReduction - sum : \nTotal = 13.600000000000001\n\nReduction - summary statistics : \nIntSummaryStatistics{count=7, sum=203, min=2, average=29.000000, max=88}" }, { "code": null, "e": 31705, "s": 31337, "text": "Now, discussing loops in order to figure out in order to land onto conclusive differences. Looping is a feature in Java that facilitates the execution of a set of instructions until the controlling Boolean expression evaluates to false. Different types of loops are provided to fit any programming need. Each loop has its own purpose and a suitable use case to serve." }, { "code": null, "e": 31716, "s": 31707, "text": "Example:" }, { "code": null, "e": 31721, "s": 31716, "text": "Java" }, { "code": "// Java Program to Comparing Streams to Loops // Importing utility packagesimport java.util.*; // Class 1// helper classclass ProgrammingLanguage { // Member variables of this class int rank; String name; int value; // Member method of this class public ProgrammingLanguage(int rank, String name, int value) { // this keyword is used to refer current object // itself this.rank = rank; this.name = name; this.value = value; }} // Class 2// JavaStreamExamplepublic class GFG { // MAin driver method public static void main(String[] args) { // Creating an object of List class // Declaring object of user defined type (above // class) List<ProgrammingLanguage> programmingLanguage = new ArrayList<ProgrammingLanguage>(); // Adding elements to the object of this class // Custom input entries programmingLanguage.add( new ProgrammingLanguage(1, \"Java\", 7000)); programmingLanguage.add( new ProgrammingLanguage(2, \"Rust\", 2000)); programmingLanguage.add( new ProgrammingLanguage(3, \"Ruby\", 1500)); programmingLanguage.add( new ProgrammingLanguage(4, \"Scala\", 2500)); programmingLanguage.add( new ProgrammingLanguage(5, \"Groovy\", 4000)); // Creating object of List class of integer type List<Integer> languageValueList = new ArrayList<Integer>(); // For each loops for iteration for (ProgrammingLanguage language : programmingLanguage) { // Filtering data of List if (language.value < 3000) { // Adding price to above elements languageValueList.add(language.value); } } // Print and display all elements inside the object System.out.println(languageValueList); }}", "e": 33670, "s": 31721, "text": null }, { "code": null, "e": 33689, "s": 33670, "text": "[2000, 1500, 2500]" }, { "code": null, "e": 33947, "s": 33689, "text": "By far we have understood both of the concepts and come across to know they don’t go hand in hand, one has advantage over other as per the usage where it is to be used. Hence, wrapping off the article by illustrating their advantages which are as follows: " }, { "code": null, "e": 33970, "s": 33947, "text": "Advantages of Streams " }, { "code": null, "e": 34036, "s": 33970, "text": "Streams are a more declarative style. Or a more expressive style." }, { "code": null, "e": 34284, "s": 34036, "text": "Streams have a strong affinity with functions. Java 8 introduces lambdas and functional interfaces, which opens a whole toolbox of powerful techniques. Streams provide the most convenient and natural way to apply functions to sequences of objects." }, { "code": null, "e": 34493, "s": 34284, "text": "Streams encourage less mutability. This is sort of related to the functional programming aspect i.e., the kind of programs we write using streams tend to be the kind of programs where we don’t modify objects." }, { "code": null, "e": 34635, "s": 34493, "text": "Streams encourage looser coupling. Our stream-handling code doesn’t need to know the source of the stream or its eventual terminating method." }, { "code": null, "e": 34696, "s": 34635, "text": "Streams can succinctly express quite sophisticated behavior." }, { "code": null, "e": 34719, "s": 34698, "text": "Advantages of Loops " }, { "code": null, "e": 34898, "s": 34719, "text": "Performance: A for loop through an array is extremely lightweight both in terms of heap and CPU usage. If raw speed and memory thriftiness is a priority, using a stream is worse." }, { "code": null, "e": 35136, "s": 34898, "text": "Familiarity: The world is full of experienced procedural programmers, from many language backgrounds, for whom loops are familiar and streams are novel. In some environments, you want to write code that’s familiar to that kind of person." }, { "code": null, "e": 35481, "s": 35136, "text": "Cognitive overhead: Because of its declarative nature, and increased abstraction from what’s happening underneath, you may need to build a new mental model of how code relates to execution. Actually, you only need to do this when things go wrong, or if you need to deeply analyze performance or subtle bugs. When it “just works”, it just works." }, { "code": null, "e": 35736, "s": 35481, "text": "Debuggers are improving, but even now, when we are stepping through stream code in a debugger, it can be harder work than the equivalent loop, because a simple loop is very close to the variables and code locations that a traditional debugger works with." }, { "code": null, "e": 35751, "s": 35738, "text": "Conclusion: " }, { "code": null, "e": 36001, "s": 35751, "text": "If you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead." }, { "code": null, "e": 36014, "s": 36001, "text": "AshokJaiswal" }, { "code": null, "e": 36023, "s": 36014, "text": "sweetyty" }, { "code": null, "e": 36035, "s": 36023, "text": "anikakapoor" }, { "code": null, "e": 36052, "s": 36035, "text": "arorakashish0911" }, { "code": null, "e": 36062, "s": 36052, "text": "as5853535" }, { "code": null, "e": 36074, "s": 36062, "text": "java-stream" }, { "code": null, "e": 36081, "s": 36074, "text": "Picked" }, { "code": null, "e": 36100, "s": 36081, "text": "Difference Between" }, { "code": null, "e": 36105, "s": 36100, "text": "Java" }, { "code": null, "e": 36110, "s": 36105, "text": "Java" }, { "code": null, "e": 36208, "s": 36110, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36269, "s": 36208, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 36337, "s": 36269, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 36395, "s": 36337, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 36450, "s": 36395, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 36516, "s": 36450, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 36531, "s": 36516, "text": "Arrays in Java" }, { "code": null, "e": 36575, "s": 36531, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36597, "s": 36575, "text": "For-each loop in Java" }, { "code": null, "e": 36648, "s": 36597, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Aspect Modelling in Sentiment Analysis - GeeksforGeeks
30 May, 2021 Prerequisite: Sentiment Analysis Before getting into the specifics of Aspect Modelling, let us first briefly understand what Sentiment Analysis is with a real-life example. It is a technique to distinguish a person’s feeling towards something or someone based on a piece of text they have written about it. It could be positive, negative or neutral. Let us consider a real-life example. We see millions of tweets on Twitter on a daily basis. Here, we can build a sentiment analysis model to determine if their attitude towards a particular subject is happy, sad, angry or neutral. The current limitations of this technique are detecting sarcasm. Aspect modelling is an advanced text-analysis technique that refers to the process of breaking down the text input into aspect categories and its aspect terms and then identifying the sentiment behind each aspect in the whole text input. The two key terms in this model are: Sentiments: A positive or negative review about a particular aspect Aspects: the category, feature, or topic that is under observation. In the business world, there is always a major need to identify to observe the sentiment of the people towards a particular product or service to ensure their continuous interest in their business product. ABSA fulfils this purpose by identifying the sentiment behind each aspect category like food, location, ambience etc. This helps businesses keep track of the changing sentiment of the customer in each field of their business. The ABSA model includes the following steps in order to obtain the desired output. Step 1 - Consider the input text corpus and pre-process the dataset. Step 2 - Create Word Embeddings of the text input. (i.e. vectorize the text input and create tokens.) Step 3.a - Aspect Terms Extraction -> Aspect Categories Model Step 3.b - Sentiment Extraction -> Sentiment Model Step 4 - Combine 3.a and 3.b to create to get Aspect Based Sentiment.(OUTPUT) Aspect: It is defined as a concept on which an opinion or a sentiment is based. Let us take an example for better understanding. Suppose a company builds a web app that works slow but offers reliable results with high accuracy. Here, we break this text into two aspects. “Web app works slow” and “reliable results with high accuracy“. On observing the two aspect categories, you can easily conclude that they have different sentiment associated with them. (As shown in Fig 1) Fig 1 : Different Sentiment with different aspects The following code implementation performs the process of aspect extraction and associating it with a particular sentiment to make it model ready for training. Python3 # Importing the required librariesimport spacysp = spacy.load("en_core_web_sm")from textblob import TextBlob # Creating a list of positive and negative sentences.mixed_sen = [ 'This chocolate truffle cake is really tasty', 'This party is amazing!', 'My mom is the best!', 'App response is very slow!' 'The trip to India was very enjoyable'] # An empty list for obtaining the extracted aspects# from sentences. ext_aspects = [] # Performing Aspect Extractionfor sen in mixed_sen: important = sp(sentence) descriptive_item = '' target = '' for token in important: if token.dep_ == 'nsubj' and token.pos_ == 'NOUN': target = token.text if token.pos_ == 'ADJ': added_terms = '' for mini_token in token.children: if mini_token.pos_ != 'ADV': continue added_terms += mini_token.text + ' ' descriptive_item = added_terms + token.text ext_aspects.append({'aspect': target, 'description': descriptive_item}) print("ASPECT EXTRACTION\n")print(ext_aspects) for aspect in ext_aspects: aspect['sentiment'] = TextBlob(aspect['description']).sentiment print("\n")print("SENTIMENT ASSOCIATION\n")print(ext_aspects) OUTPUT OBTAINED Natural-language-processing Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning 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": 25589, "s": 25561, "text": "\n30 May, 2021" }, { "code": null, "e": 25623, "s": 25589, "text": "Prerequisite: Sentiment Analysis " }, { "code": null, "e": 25764, "s": 25623, "text": "Before getting into the specifics of Aspect Modelling, let us first briefly understand what Sentiment Analysis is with a real-life example. " }, { "code": null, "e": 25979, "s": 25764, "text": "It is a technique to distinguish a person’s feeling towards something or someone based on a piece of text they have written about it. It could be positive, negative or neutral. Let us consider a real-life example. " }, { "code": null, "e": 26239, "s": 25979, "text": "We see millions of tweets on Twitter on a daily basis. Here, we can build a sentiment analysis model to determine if their attitude towards a particular subject is happy, sad, angry or neutral. The current limitations of this technique are detecting sarcasm. " }, { "code": null, "e": 26514, "s": 26239, "text": "Aspect modelling is an advanced text-analysis technique that refers to the process of breaking down the text input into aspect categories and its aspect terms and then identifying the sentiment behind each aspect in the whole text input. The two key terms in this model are:" }, { "code": null, "e": 26582, "s": 26514, "text": "Sentiments: A positive or negative review about a particular aspect" }, { "code": null, "e": 26650, "s": 26582, "text": "Aspects: the category, feature, or topic that is under observation." }, { "code": null, "e": 26975, "s": 26650, "text": "In the business world, there is always a major need to identify to observe the sentiment of the people towards a particular product or service to ensure their continuous interest in their business product. ABSA fulfils this purpose by identifying the sentiment behind each aspect category like food, location, ambience etc. " }, { "code": null, "e": 27084, "s": 26975, "text": "This helps businesses keep track of the changing sentiment of the customer in each field of their business. " }, { "code": null, "e": 27168, "s": 27084, "text": "The ABSA model includes the following steps in order to obtain the desired output. " }, { "code": null, "e": 27571, "s": 27168, "text": "Step 1 - Consider the input text corpus and pre-process the dataset. \n \nStep 2 - Create Word Embeddings of the text input. (i.e. vectorize the text input \n and create tokens.)\n \nStep 3.a - Aspect Terms Extraction -> Aspect Categories Model \n \nStep 3.b - Sentiment Extraction -> Sentiment Model \n \nStep 4 - Combine 3.a and 3.b to create to get Aspect Based Sentiment.(OUTPUT)" }, { "code": null, "e": 27701, "s": 27571, "text": "Aspect: It is defined as a concept on which an opinion or a sentiment is based. Let us take an example for better understanding. " }, { "code": null, "e": 28048, "s": 27701, "text": "Suppose a company builds a web app that works slow but offers reliable results with high accuracy. Here, we break this text into two aspects. “Web app works slow” and “reliable results with high accuracy“. On observing the two aspect categories, you can easily conclude that they have different sentiment associated with them. (As shown in Fig 1)" }, { "code": null, "e": 28099, "s": 28048, "text": "Fig 1 : Different Sentiment with different aspects" }, { "code": null, "e": 28259, "s": 28099, "text": "The following code implementation performs the process of aspect extraction and associating it with a particular sentiment to make it model ready for training." }, { "code": null, "e": 28267, "s": 28259, "text": "Python3" }, { "code": "# Importing the required librariesimport spacysp = spacy.load(\"en_core_web_sm\")from textblob import TextBlob # Creating a list of positive and negative sentences.mixed_sen = [ 'This chocolate truffle cake is really tasty', 'This party is amazing!', 'My mom is the best!', 'App response is very slow!' 'The trip to India was very enjoyable'] # An empty list for obtaining the extracted aspects# from sentences. ext_aspects = [] # Performing Aspect Extractionfor sen in mixed_sen: important = sp(sentence) descriptive_item = '' target = '' for token in important: if token.dep_ == 'nsubj' and token.pos_ == 'NOUN': target = token.text if token.pos_ == 'ADJ': added_terms = '' for mini_token in token.children: if mini_token.pos_ != 'ADV': continue added_terms += mini_token.text + ' ' descriptive_item = added_terms + token.text ext_aspects.append({'aspect': target, 'description': descriptive_item}) print(\"ASPECT EXTRACTION\\n\")print(ext_aspects) for aspect in ext_aspects: aspect['sentiment'] = TextBlob(aspect['description']).sentiment print(\"\\n\")print(\"SENTIMENT ASSOCIATION\\n\")print(ext_aspects)", "e": 29437, "s": 28267, "text": null }, { "code": null, "e": 29453, "s": 29437, "text": "OUTPUT OBTAINED" }, { "code": null, "e": 29481, "s": 29453, "text": "Natural-language-processing" }, { "code": null, "e": 29498, "s": 29481, "text": "Machine Learning" }, { "code": null, "e": 29505, "s": 29498, "text": "Python" }, { "code": null, "e": 29522, "s": 29505, "text": "Machine Learning" }, { "code": null, "e": 29620, "s": 29522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29661, "s": 29620, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29694, "s": 29661, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29722, "s": 29694, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 29758, "s": 29722, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 29813, "s": 29758, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 29841, "s": 29813, "text": "Read JSON file using Python" }, { "code": null, "e": 29891, "s": 29841, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29913, "s": 29891, "text": "Python map() function" } ]
math.Pow() Function in Golang With Examples - GeeksforGeeks
13 Apr, 2020 Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find the base-a exponential of b(a**b)with the help of Pow() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access Pow() function. Syntax: func Pow(a, b float64) float64 If Pow(a, ±0), then this method will return 1 for any a. If Pow(1, b), then this method will return 1 for any b. If Pow(a, 1), then this method will return a for any a. If Pow(NaN, b), then this method will return NaN. If Pow(a, NaN), then this method will return NaN. If Pow(±0, b), then this method will return ± Inf for b an odd integer < 0. If Pow(±0, -Inf), then this method will return +Inf. If Pow(±0, +Inf), then this method will return +0. If Pow(±0, b), then this method will return +Inf for finite b < 0 and not an odd integer. If Pow(±0, b), then this method will return ± 0 for b an odd integer > 0. If Pow(±0, b), then this method will return +0 for finite b > 0 and not an odd integer. If Pow(+1, ±Inf), then this method will return 1. If Pow(a, +Inf), then this method will return +Inf for |a| > 1. If Pow(a, -Inf), then this method will return +0 for |a| > 1. If Pow(a, +Inf), then this method will return +0 for |a| < 1. If Pow(a, -Inf), then this method will return +Inf for |a| < 1. If Pow(+Inf, b), then this method will return +Inf for b > 0. If Pow(+Inf, b), then this method will return +0 for b < 0. If Pow(-Inf, b), then this method will return Pow(-0, -b). If Pow(a, b), then this method will return NaN for finite a < 0 and finite non-integer b. Example 1: // Golang program to illustrate// the use of math.Pow() function package main import ( "fmt" "math") // Main functionfunc main() { // Finding the base-a exponential of b // Using Pow() function res_1 := math.Pow(3, 5) res_2 := math.Pow(math.Inf(1), 3) res_3 := math.Pow(2, 0) res_4 := math.Pow(1, math.NaN()) res_5 := math.Pow(-0, math.Inf(-1)) // Displaying the result fmt.Printf("Result 1: %.1f", res_1) fmt.Printf("\nResult 2: %.1f", res_2) fmt.Printf("\nResult 3: %.1f", res_3) fmt.Printf("\nResult 4: %.1f", res_4) fmt.Printf("\nResult 5: %.1f", res_5)} Output: Result 1: 243.0 Result 2: +Inf Result 3: 1.0 Result 4: 1.0 Result 5: +Inf Example 2: // Golang program to illustrate// the use of math.Pow() function package main import ( "fmt" "math") // Main functionfunc main() { // Finding the base-a exponential of b // Using Pow() function nvalue_1 := math.Pow(3, 4) nvalue_2 := math.Pow(5, 6) // Sum of the given numbers res := nvalue_1 + nvalue_2 fmt.Printf("%.3f + %.3f = %.3f", nvalue_1, nvalue_2, res) } Output: 81.000 + 15625.000 = 15706.000 Golang-Math Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language Arrays in Go strings.Replace() Function in Golang With Examples How to Split a String in Golang? Slices in Golang Golang Maps Different Ways to Find the Type of Variable in Golang Inheritance in GoLang Interfaces in Golang How to Trim a String in Golang?
[ { "code": null, "e": 25665, "s": 25637, "text": "\n13 Apr, 2020" }, { "code": null, "e": 26042, "s": 25665, "text": "Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find the base-a exponential of b(a**b)with the help of Pow() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access Pow() function." }, { "code": null, "e": 26050, "s": 26042, "text": "Syntax:" }, { "code": null, "e": 26081, "s": 26050, "text": "func Pow(a, b float64) float64" }, { "code": null, "e": 26138, "s": 26081, "text": "If Pow(a, ±0), then this method will return 1 for any a." }, { "code": null, "e": 26194, "s": 26138, "text": "If Pow(1, b), then this method will return 1 for any b." }, { "code": null, "e": 26250, "s": 26194, "text": "If Pow(a, 1), then this method will return a for any a." }, { "code": null, "e": 26300, "s": 26250, "text": "If Pow(NaN, b), then this method will return NaN." }, { "code": null, "e": 26350, "s": 26300, "text": "If Pow(a, NaN), then this method will return NaN." }, { "code": null, "e": 26426, "s": 26350, "text": "If Pow(±0, b), then this method will return ± Inf for b an odd integer < 0." }, { "code": null, "e": 26479, "s": 26426, "text": "If Pow(±0, -Inf), then this method will return +Inf." }, { "code": null, "e": 26530, "s": 26479, "text": "If Pow(±0, +Inf), then this method will return +0." }, { "code": null, "e": 26620, "s": 26530, "text": "If Pow(±0, b), then this method will return +Inf for finite b < 0 and not an odd integer." }, { "code": null, "e": 26694, "s": 26620, "text": "If Pow(±0, b), then this method will return ± 0 for b an odd integer > 0." }, { "code": null, "e": 26782, "s": 26694, "text": "If Pow(±0, b), then this method will return +0 for finite b > 0 and not an odd integer." }, { "code": null, "e": 26832, "s": 26782, "text": "If Pow(+1, ±Inf), then this method will return 1." }, { "code": null, "e": 26896, "s": 26832, "text": "If Pow(a, +Inf), then this method will return +Inf for |a| > 1." }, { "code": null, "e": 26958, "s": 26896, "text": "If Pow(a, -Inf), then this method will return +0 for |a| > 1." }, { "code": null, "e": 27020, "s": 26958, "text": "If Pow(a, +Inf), then this method will return +0 for |a| < 1." }, { "code": null, "e": 27084, "s": 27020, "text": "If Pow(a, -Inf), then this method will return +Inf for |a| < 1." }, { "code": null, "e": 27146, "s": 27084, "text": "If Pow(+Inf, b), then this method will return +Inf for b > 0." }, { "code": null, "e": 27206, "s": 27146, "text": "If Pow(+Inf, b), then this method will return +0 for b < 0." }, { "code": null, "e": 27265, "s": 27206, "text": "If Pow(-Inf, b), then this method will return Pow(-0, -b)." }, { "code": null, "e": 27355, "s": 27265, "text": "If Pow(a, b), then this method will return NaN for finite a < 0 and finite non-integer b." }, { "code": null, "e": 27366, "s": 27355, "text": "Example 1:" }, { "code": "// Golang program to illustrate// the use of math.Pow() function package main import ( \"fmt\" \"math\") // Main functionfunc main() { // Finding the base-a exponential of b // Using Pow() function res_1 := math.Pow(3, 5) res_2 := math.Pow(math.Inf(1), 3) res_3 := math.Pow(2, 0) res_4 := math.Pow(1, math.NaN()) res_5 := math.Pow(-0, math.Inf(-1)) // Displaying the result fmt.Printf(\"Result 1: %.1f\", res_1) fmt.Printf(\"\\nResult 2: %.1f\", res_2) fmt.Printf(\"\\nResult 3: %.1f\", res_3) fmt.Printf(\"\\nResult 4: %.1f\", res_4) fmt.Printf(\"\\nResult 5: %.1f\", res_5)}", "e": 27977, "s": 27366, "text": null }, { "code": null, "e": 27985, "s": 27977, "text": "Output:" }, { "code": null, "e": 28060, "s": 27985, "text": "Result 1: 243.0\nResult 2: +Inf\nResult 3: 1.0\nResult 4: 1.0\nResult 5: +Inf\n" }, { "code": null, "e": 28071, "s": 28060, "text": "Example 2:" }, { "code": "// Golang program to illustrate// the use of math.Pow() function package main import ( \"fmt\" \"math\") // Main functionfunc main() { // Finding the base-a exponential of b // Using Pow() function nvalue_1 := math.Pow(3, 4) nvalue_2 := math.Pow(5, 6) // Sum of the given numbers res := nvalue_1 + nvalue_2 fmt.Printf(\"%.3f + %.3f = %.3f\", nvalue_1, nvalue_2, res) }", "e": 28481, "s": 28071, "text": null }, { "code": null, "e": 28489, "s": 28481, "text": "Output:" }, { "code": null, "e": 28520, "s": 28489, "text": "81.000 + 15625.000 = 15706.000" }, { "code": null, "e": 28532, "s": 28520, "text": "Golang-Math" }, { "code": null, "e": 28544, "s": 28532, "text": "Go Language" }, { "code": null, "e": 28642, "s": 28544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28688, "s": 28642, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28701, "s": 28688, "text": "Arrays in Go" }, { "code": null, "e": 28752, "s": 28701, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28785, "s": 28752, "text": "How to Split a String in Golang?" }, { "code": null, "e": 28802, "s": 28785, "text": "Slices in Golang" }, { "code": null, "e": 28814, "s": 28802, "text": "Golang Maps" }, { "code": null, "e": 28868, "s": 28814, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 28890, "s": 28868, "text": "Inheritance in GoLang" }, { "code": null, "e": 28911, "s": 28890, "text": "Interfaces in Golang" } ]
Angular PrimeNG ToggleButton Component - GeeksforGeeks
22 Aug, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the ToggleButton component in Angular PrimeNG. ToggleButton component is used to make a button that users can toggle by clicking on it. Properties: onLabel: It is used to set the label for the on-state. It is of string data type, the default value is null. offLabel: It is used to set the label for the off state. It is of string data type, the default value is null. onIcon: It is used to set the icon for the on-state. It is of string data type, the default value is null. offIcon: It is used to set the icon for the off state. It is of string data type, the default value is null. iconPos: It is used to set the position of the icon, valid values are “left” and “right”. It is of string data type, the default value is left. style: It is used to set the inline style of the element. It is of string data type, the default value is null. styleClass: It is used to set the style class of the element. It is of string data type, the default value is null. disabled: It specifies that the element should be disabled. It is of a boolean data type, the default value is false. tabindex: It is used to set the Index of the element in tabbing order. It is of number data type, the default value is null. inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null ariaLabel: It is used to define a string that labels the input element, It is of string data type, the default value is null. Event: onChange: it is a callback that is fired on state change. Styling: p-togglebutton: It is a styling Container element p-button-icon-left: It is a styling Icon element. p-button-icon-right: It is a styling Icon element. p-button-text: It is a styling Label element. Creating Angular Application & module installation: Step 1: Create an Angular application using the following command.ng new appname Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory.npm install primeng --save npm install primeicons --save Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following. Example 1: This is the basic example that shows how to use the ToggleButton component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG ToggleButton Component</h5><p-toggleButton [(ngModel)]="checked1" onIcon="pi pi-caret-left" offIcon="pi pi-caret-right" onLabel="ToggleButton Component" offLabel="Enabled Button"></p-toggleButton> <p-toggleButton [(ngModel)]="checked2" onIcon="pi pi-caret-left" offIcon="pi pi-caret-right" [disabled] onLabel="ToggleButton Component" offLabel="Disabled Button"></p-toggleButton> app.component.ts import { Component } from "@angular/core";import { SelectItem, PrimeNGConfig } from "primeng/api"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } checked1: boolean = false; checked2: boolean = false;} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component"; import { ToggleButtonModule } from "primeng/togglebutton"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ToggleButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use iconPos property in the toggleButton component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG ToggleButton Component</h5><p-toggleButton [(ngModel)]="checked1" onIcon="pi pi-caret-left" offIcon="pi pi-caret-right" onLabel="ToggleButton Component" offLabel="GeeksforGeeks" iconPos="right"></p-toggleButton> <p-toggleButton [(ngModel)]="checked2" onIcon="pi pi-caret-left" offIcon="pi pi-caret-right" onLabel="ToggleButton Component" offLabel="GeeksforGeeks"></p-toggleButton> app.component.ts import { Component } from "@angular/core";import { SelectItem, PrimeNGConfig } from "primeng/api"; @Component({ selector: "app-root", templateUrl: "./app.component.html",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } checked1: boolean = false; checked2: boolean = false;} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component"; import { ToggleButtonModule } from "primeng/togglebutton"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ToggleButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/togglebutton Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Messages Component Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26354, "s": 26326, "text": "\n22 Aug, 2021" }, { "code": null, "e": 26642, "s": 26354, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the ToggleButton component in Angular PrimeNG." }, { "code": null, "e": 26732, "s": 26642, "text": "ToggleButton component is used to make a button that users can toggle by clicking on it. " }, { "code": null, "e": 26744, "s": 26732, "text": "Properties:" }, { "code": null, "e": 26853, "s": 26744, "text": "onLabel: It is used to set the label for the on-state. It is of string data type, the default value is null." }, { "code": null, "e": 26964, "s": 26853, "text": "offLabel: It is used to set the label for the off state. It is of string data type, the default value is null." }, { "code": null, "e": 27071, "s": 26964, "text": "onIcon: It is used to set the icon for the on-state. It is of string data type, the default value is null." }, { "code": null, "e": 27180, "s": 27071, "text": "offIcon: It is used to set the icon for the off state. It is of string data type, the default value is null." }, { "code": null, "e": 27324, "s": 27180, "text": "iconPos: It is used to set the position of the icon, valid values are “left” and “right”. It is of string data type, the default value is left." }, { "code": null, "e": 27436, "s": 27324, "text": "style: It is used to set the inline style of the element. It is of string data type, the default value is null." }, { "code": null, "e": 27552, "s": 27436, "text": "styleClass: It is used to set the style class of the element. It is of string data type, the default value is null." }, { "code": null, "e": 27670, "s": 27552, "text": "disabled: It specifies that the element should be disabled. It is of a boolean data type, the default value is false." }, { "code": null, "e": 27795, "s": 27670, "text": "tabindex: It is used to set the Index of the element in tabbing order. It is of number data type, the default value is null." }, { "code": null, "e": 27914, "s": 27795, "text": "inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null" }, { "code": null, "e": 28040, "s": 27914, "text": "ariaLabel: It is used to define a string that labels the input element, It is of string data type, the default value is null." }, { "code": null, "e": 28047, "s": 28040, "text": "Event:" }, { "code": null, "e": 28105, "s": 28047, "text": "onChange: it is a callback that is fired on state change." }, { "code": null, "e": 28116, "s": 28107, "text": "Styling:" }, { "code": null, "e": 28166, "s": 28116, "text": "p-togglebutton: It is a styling Container element" }, { "code": null, "e": 28216, "s": 28166, "text": "p-button-icon-left: It is a styling Icon element." }, { "code": null, "e": 28267, "s": 28216, "text": "p-button-icon-right: It is a styling Icon element." }, { "code": null, "e": 28313, "s": 28267, "text": "p-button-text: It is a styling Label element." }, { "code": null, "e": 28365, "s": 28313, "text": "Creating Angular Application & module installation:" }, { "code": null, "e": 28446, "s": 28365, "text": "Step 1: Create an Angular application using the following command.ng new appname" }, { "code": null, "e": 28513, "s": 28446, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28528, "s": 28513, "text": "ng new appname" }, { "code": null, "e": 28635, "s": 28528, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname" }, { "code": null, "e": 28732, "s": 28635, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28743, "s": 28732, "text": "cd appname" }, { "code": null, "e": 28848, "s": 28743, "text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28897, "s": 28848, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28954, "s": 28897, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 29006, "s": 28954, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 29095, "s": 29008, "text": "Example 1: This is the basic example that shows how to use the ToggleButton component." }, { "code": null, "e": 29114, "s": 29095, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG ToggleButton Component</h5><p-toggleButton [(ngModel)]=\"checked1\" onIcon=\"pi pi-caret-left\" offIcon=\"pi pi-caret-right\" onLabel=\"ToggleButton Component\" offLabel=\"Enabled Button\"></p-toggleButton> <p-toggleButton [(ngModel)]=\"checked2\" onIcon=\"pi pi-caret-left\" offIcon=\"pi pi-caret-right\" [disabled] onLabel=\"ToggleButton Component\" offLabel=\"Disabled Button\"></p-toggleButton>", "e": 29539, "s": 29114, "text": null }, { "code": null, "e": 29556, "s": 29539, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { SelectItem, PrimeNGConfig } from \"primeng/api\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } checked1: boolean = false; checked2: boolean = false;}", "e": 29928, "s": 29556, "text": null }, { "code": null, "e": 29942, "s": 29928, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\"; import { ToggleButtonModule } from \"primeng/togglebutton\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ToggleButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 30479, "s": 29942, "text": null }, { "code": null, "e": 30487, "s": 30479, "text": "Output:" }, { "code": null, "e": 30588, "s": 30487, "text": "Example 2: In this example, we will know how to use iconPos property in the toggleButton component. " }, { "code": null, "e": 30607, "s": 30588, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG ToggleButton Component</h5><p-toggleButton [(ngModel)]=\"checked1\" onIcon=\"pi pi-caret-left\" offIcon=\"pi pi-caret-right\" onLabel=\"ToggleButton Component\" offLabel=\"GeeksforGeeks\" iconPos=\"right\"></p-toggleButton> <p-toggleButton [(ngModel)]=\"checked2\" onIcon=\"pi pi-caret-left\" offIcon=\"pi pi-caret-right\" onLabel=\"ToggleButton Component\" offLabel=\"GeeksforGeeks\"></p-toggleButton>", "e": 31034, "s": 30607, "text": null }, { "code": null, "e": 31051, "s": 31034, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { SelectItem, PrimeNGConfig } from \"primeng/api\"; @Component({ selector: \"app-root\", templateUrl: \"./app.component.html\",})export class AppComponent { constructor(private primengConfig: PrimeNGConfig) {} ngOnInit() { this.primengConfig.ripple = true; } checked1: boolean = false; checked2: boolean = false;}", "e": 31425, "s": 31051, "text": null }, { "code": null, "e": 31439, "s": 31425, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\"; import { ToggleButtonModule } from \"primeng/togglebutton\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ToggleButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31976, "s": 31439, "text": null }, { "code": null, "e": 31984, "s": 31976, "text": "Output:" }, { "code": null, "e": 32050, "s": 31984, "text": "Reference: https://primefaces.org/primeng/showcase/#/togglebutton" }, { "code": null, "e": 32066, "s": 32050, "text": "Angular-PrimeNG" }, { "code": null, "e": 32076, "s": 32066, "text": "AngularJS" }, { "code": null, "e": 32093, "s": 32076, "text": "Web Technologies" }, { "code": null, "e": 32191, "s": 32093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32226, "s": 32191, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32261, "s": 32226, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 32285, "s": 32261, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32338, "s": 32285, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32373, "s": 32338, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 32413, "s": 32373, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32446, "s": 32413, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32491, "s": 32446, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32534, "s": 32491, "text": "How to fetch data from an API in ReactJS ?" } ]
Find last index of a character in a string in C++
Suppose we have a string str. We have another character ch. Our task is to find the last index of ch in the string. Suppose the string is “Hello”, and character ch = ‘l’, then the last index will be 3. To solve this, we will traverse the list from right to left, if the character is not same as ‘l’, then decrease index, if it matches, then stop and return result. #include<iostream> using namespace std; int getLastIndex(string& str, char ch) { for (int i = str.length() - 1; i >= 0; i--) if (str[i] == ch) return i; return -1; } int main() { string str = "hello"; char ch = 'l'; int index = getLastIndex(str, ch); if (index == -1) cout << "Character not found"; else cout << "Last index is " << index; } Last index is 3
[ { "code": null, "e": 1264, "s": 1062, "text": "Suppose we have a string str. We have another character ch. Our task is to find the last index of ch in the string. Suppose the string is “Hello”, and character ch = ‘l’, then the last index will be 3." }, { "code": null, "e": 1427, "s": 1264, "text": "To solve this, we will traverse the list from right to left, if the character is not same as ‘l’, then decrease index, if it matches, then stop and return result." }, { "code": null, "e": 1816, "s": 1427, "text": "#include<iostream>\nusing namespace std;\nint getLastIndex(string& str, char ch) {\n for (int i = str.length() - 1; i >= 0; i--)\n if (str[i] == ch)\n return i;\n return -1;\n}\nint main() {\n string str = \"hello\";\n char ch = 'l';\n int index = getLastIndex(str, ch);\n if (index == -1)\n cout << \"Character not found\";\n else\n cout << \"Last index is \" << index;\n}" }, { "code": null, "e": 1832, "s": 1816, "text": "Last index is 3" } ]
How to Use Convolutional Neural Networks for Time Series Classification | by Margarita Granat | Towards Data Science
A large amount of data is stored in the form of time series: stock indices, climate measurements, medical tests, etc. Time series classification has a wide range of applications: from identification of stock market anomalies to automated detection of heart and brain diseases. There are many methods for time series classification. Most of them consist of two major stages: on the first stage you either use some algorithm for measuring the difference between time series that you want to classify (dynamic time warping is a well-known one) or you use whatever tools are at your disposal (simple statistics, advanced mathematical methods etc.) to represent your time series as feature vectors. In the second stage you use some algorithm to classify your data. It can be anything from k-nearest neighbors and SVMs to deep neural network models. But one thing unites these methods: they all require some kind of feature engineering as a separate stage before classification is performed. Fortunately, there are models that not only incorporate feature engineering in one framework, but also eliminate any need to do it manually: they are able to extract features and create informative representations of time series automatically. These models are recurrent and convolutional neural networks (CNNs). Research has shown that using CNNs for time series classification has several important advantages over other methods. They are highly noise-resistant models, and they are able to extract very informative, deep features, which are independent from time. In this article we will examine in detail how exactly the 1-D convolution works on time series. Then, I will give an overview of a more sophisticated model proposed by the researchers from Washington University in St. Louis. Finally, we will look at a simplified multi-scale CNN code example. Imagine a time series of length n and width k. The length is the number of timesteps, and the width is the number of variables in a multivariate time series. For example, for electroencephalography it is the number of channels (nodes on the head of a person), and for a weather time series it can be such variables as temperature, pressure, humidity etc. The convolution kernels always have the same width as the time series, while their length can be varied. This way, the kernel moves in one direction from the beginning of a time series towards its end, performing convolution. It does not move to the left or to the right as it does when the usual 2-D convolution is applied to images. The elements of the kernel get multiplied by the corresponding elements of the time series that they cover at a given point. Then the results of the multiplication are added together and a nonlinear activation function is applied to the value. The resulting value becomes an element of a new “filtered” univariate time series, and then the kernel moves forward along the time series to produce the next value. The number of new “filtered” time series is the same as the number of convolution kernels. Depending on the length of the kernel, different aspects, properties, “features” of the initial time series get captured in each of the new filtered series. The next step is to apply global max-pooling to each of the filtered time series vectors: the largest value is taken from each vector. A new vector is formed from these values, and this vector of maximums is the final feature vector that can be used as an input to a regular fully connected layer. This whole process is illustrated in the picture above. With this simple example in mind, let’s examine the model of a multi-scale convolutional neural network for time series classification [1]. The multi-scalability of this model consists in its architecture: in the first convolutional layer the convolution is performed on 3 parallel independent branches. Each branch extracts features of different nature from the data, operating at different time and frequency scales. The framework of this network consists of 3 consecutive stages: transformation, local convolution, and full convolution. On this stage different transformations are applied to the original time series on 3 separate branches. The first branch transformation is identity mapping, meaning that the original time series remains intact. The second branch transformation is smoothing the original time series with a moving average with various window sizes. This way, several new time series with different degrees of smoothness are created. The idea behind this is that each new time series consolidates information from different frequencies of the original data. Finally, the third branch transformation is down-sampling the original time series with various down-sampling coefficients. The smaller the coefficient, the more detailed the new time series is, and, therefore, it consolidates information about the time series features on a smaller time scale. Down-sampling with larger coefficients results in less detailed new time series which capture and emphasize those features of the original data that exhibit themselves on larger time scales. On this stage the 1-D convolution with different filter sizes that we discussed earlier is applied to the time series. Each convolutional layer is followed by a max-pooling layer. In the previous, simpler example global max pooling was used. Here, max pooling is not global, but still the pooling kernel size is extremely large, much larger than the sizes you are used to when working with image data. More specifically, the pooling kernel size is determined by the formula n/p, where n is the length of the time series, and p is a pooling factor, typically chosen between the values {2, 3, 5}. This stage is called local convolution because each branch is processed independently. On this stage all the outputs of local convolution stage from all 3 branches are concatenated. Then several more convolutional and max-pooling layers are added. After all the transformations and convolutions, you are left with a flat vector of deep, complex features that capture information about the original time series in a wide range of frequency and time scale domains. This vector is then used as an input to fully connected layers with Softmax function on the last layer. from keras.layers import Conv1D, Dense, Dropout, Input, Concatenate, GlobalMaxPooling1Dfrom keras.models import Model#this base model is one branch of the main model#it takes a time series as an input, performs 1-D convolution, and returns it as an output ready for concatenationdef get_base_model(input_len, fsize):#the input is a time series of length n and width 19input_seq = Input(shape=(input_len, 19))#choose the number of convolution filtersnb_filters = 10#1-D convolution and global max-poolingconvolved = Conv1D(nb_filters, fsize, padding="same", activation="tanh")(input_seq)processed = GlobalMaxPooling1D()(convolved)#dense layer with dropout regularizationcompressed = Dense(50, activation="tanh")(processed)compressed = Dropout(0.3)(compressed)model = Model(inputs=input_seq, outputs=compressed)return model#this is the main model#it takes the original time series and its down-sampled versions as an input, and returns the result of classification as an outputdef main_model(inputs_lens = [512, 1024, 3480], fsizes = [8,16,24]):#the inputs to the branches are the original time series, and its down-sampled versionsinput_smallseq = Input(shape=(inputs_lens[0], 19))input_medseq = Input(shape=(inputs_lens[1] , 19))input_origseq = Input(shape=(inputs_lens[2], 19))#the more down-sampled the time series, the shorter the corresponding filterbase_net_small = get_base_model(inputs_lens[0], fsizes[0])base_net_med = get_base_model(inputs_lens[1], fsizes[1])base_net_original = get_base_model(inputs_lens[2], fsizes[2])embedding_small = base_net_small(input_smallseq)embedding_med = base_net_med(input_medseq)embedding_original = base_net_original(input_origseq)#concatenate all the outputsmerged = Concatenate()([embedding_small, embedding_med, embedding_original])out = Dense(1, activation='sigmoid')(merged)model = Model(inputs=[input_smallseq, input_medseq, input_origseq], outputs=out)return model This model is a much simpler version of the multi-scale convolutional neural network. It takes the original time series and 2 down-sampled versions of it (medium and small length) as an input. The first branch of the model processes the original time series of length 3480 and of width 19. The corresponding convolution filter length is 24. The second branch processes the medium-length (1024 timesteps) down-sampled version of the time series, and the filter length used here is 16. The third branch processes the shortest version (512 timesteps) of the time series, with the filter length of 8. This way every branch extracts features on different time scales. After convolutional and global max-pooling layers, dropout regularization is added, and all the outputs are concatenated. The last fully connected layer returns the result of classification. In this article I tried to explain how deep convolutional neural networks can be used to classify time series. It is worth mentioning that the proposed method is not the only one that exists. There are ways of presenting time series in the form of images (for example, using their spectrograms), to which a regular 2-D convolution can be applied. Thank you very much for reading this article. I hope it was helpful to you, and I would really appreciate your feedback. References: [1] Z. Cui, W. Chen, Y. Chen, Multi-Scale Convolutional Neural Networks for Time Series Classification (2016), https://arxiv.org/abs/1603.06995. [2] Y. Kim, Convolutional Neural Networks for Sentence Classification (2014), https://arxiv.org/abs/1408.5882.
[ { "code": null, "e": 448, "s": 171, "text": "A large amount of data is stored in the form of time series: stock indices, climate measurements, medical tests, etc. Time series classification has a wide range of applications: from identification of stock market anomalies to automated detection of heart and brain diseases." }, { "code": null, "e": 1157, "s": 448, "text": "There are many methods for time series classification. Most of them consist of two major stages: on the first stage you either use some algorithm for measuring the difference between time series that you want to classify (dynamic time warping is a well-known one) or you use whatever tools are at your disposal (simple statistics, advanced mathematical methods etc.) to represent your time series as feature vectors. In the second stage you use some algorithm to classify your data. It can be anything from k-nearest neighbors and SVMs to deep neural network models. But one thing unites these methods: they all require some kind of feature engineering as a separate stage before classification is performed." }, { "code": null, "e": 1470, "s": 1157, "text": "Fortunately, there are models that not only incorporate feature engineering in one framework, but also eliminate any need to do it manually: they are able to extract features and create informative representations of time series automatically. These models are recurrent and convolutional neural networks (CNNs)." }, { "code": null, "e": 2017, "s": 1470, "text": "Research has shown that using CNNs for time series classification has several important advantages over other methods. They are highly noise-resistant models, and they are able to extract very informative, deep features, which are independent from time. In this article we will examine in detail how exactly the 1-D convolution works on time series. Then, I will give an overview of a more sophisticated model proposed by the researchers from Washington University in St. Louis. Finally, we will look at a simplified multi-scale CNN code example." }, { "code": null, "e": 2372, "s": 2017, "text": "Imagine a time series of length n and width k. The length is the number of timesteps, and the width is the number of variables in a multivariate time series. For example, for electroencephalography it is the number of channels (nodes on the head of a person), and for a weather time series it can be such variables as temperature, pressure, humidity etc." }, { "code": null, "e": 2707, "s": 2372, "text": "The convolution kernels always have the same width as the time series, while their length can be varied. This way, the kernel moves in one direction from the beginning of a time series towards its end, performing convolution. It does not move to the left or to the right as it does when the usual 2-D convolution is applied to images." }, { "code": null, "e": 3365, "s": 2707, "text": "The elements of the kernel get multiplied by the corresponding elements of the time series that they cover at a given point. Then the results of the multiplication are added together and a nonlinear activation function is applied to the value. The resulting value becomes an element of a new “filtered” univariate time series, and then the kernel moves forward along the time series to produce the next value. The number of new “filtered” time series is the same as the number of convolution kernels. Depending on the length of the kernel, different aspects, properties, “features” of the initial time series get captured in each of the new filtered series." }, { "code": null, "e": 3719, "s": 3365, "text": "The next step is to apply global max-pooling to each of the filtered time series vectors: the largest value is taken from each vector. A new vector is formed from these values, and this vector of maximums is the final feature vector that can be used as an input to a regular fully connected layer. This whole process is illustrated in the picture above." }, { "code": null, "e": 3859, "s": 3719, "text": "With this simple example in mind, let’s examine the model of a multi-scale convolutional neural network for time series classification [1]." }, { "code": null, "e": 4138, "s": 3859, "text": "The multi-scalability of this model consists in its architecture: in the first convolutional layer the convolution is performed on 3 parallel independent branches. Each branch extracts features of different nature from the data, operating at different time and frequency scales." }, { "code": null, "e": 4259, "s": 4138, "text": "The framework of this network consists of 3 consecutive stages: transformation, local convolution, and full convolution." }, { "code": null, "e": 4470, "s": 4259, "text": "On this stage different transformations are applied to the original time series on 3 separate branches. The first branch transformation is identity mapping, meaning that the original time series remains intact." }, { "code": null, "e": 4798, "s": 4470, "text": "The second branch transformation is smoothing the original time series with a moving average with various window sizes. This way, several new time series with different degrees of smoothness are created. The idea behind this is that each new time series consolidates information from different frequencies of the original data." }, { "code": null, "e": 5284, "s": 4798, "text": "Finally, the third branch transformation is down-sampling the original time series with various down-sampling coefficients. The smaller the coefficient, the more detailed the new time series is, and, therefore, it consolidates information about the time series features on a smaller time scale. Down-sampling with larger coefficients results in less detailed new time series which capture and emphasize those features of the original data that exhibit themselves on larger time scales." }, { "code": null, "e": 5966, "s": 5284, "text": "On this stage the 1-D convolution with different filter sizes that we discussed earlier is applied to the time series. Each convolutional layer is followed by a max-pooling layer. In the previous, simpler example global max pooling was used. Here, max pooling is not global, but still the pooling kernel size is extremely large, much larger than the sizes you are used to when working with image data. More specifically, the pooling kernel size is determined by the formula n/p, where n is the length of the time series, and p is a pooling factor, typically chosen between the values {2, 3, 5}. This stage is called local convolution because each branch is processed independently." }, { "code": null, "e": 6446, "s": 5966, "text": "On this stage all the outputs of local convolution stage from all 3 branches are concatenated. Then several more convolutional and max-pooling layers are added. After all the transformations and convolutions, you are left with a flat vector of deep, complex features that capture information about the original time series in a wide range of frequency and time scale domains. This vector is then used as an input to fully connected layers with Softmax function on the last layer." }, { "code": null, "e": 8359, "s": 6446, "text": "from keras.layers import Conv1D, Dense, Dropout, Input, Concatenate, GlobalMaxPooling1Dfrom keras.models import Model#this base model is one branch of the main model#it takes a time series as an input, performs 1-D convolution, and returns it as an output ready for concatenationdef get_base_model(input_len, fsize):#the input is a time series of length n and width 19input_seq = Input(shape=(input_len, 19))#choose the number of convolution filtersnb_filters = 10#1-D convolution and global max-poolingconvolved = Conv1D(nb_filters, fsize, padding=\"same\", activation=\"tanh\")(input_seq)processed = GlobalMaxPooling1D()(convolved)#dense layer with dropout regularizationcompressed = Dense(50, activation=\"tanh\")(processed)compressed = Dropout(0.3)(compressed)model = Model(inputs=input_seq, outputs=compressed)return model#this is the main model#it takes the original time series and its down-sampled versions as an input, and returns the result of classification as an outputdef main_model(inputs_lens = [512, 1024, 3480], fsizes = [8,16,24]):#the inputs to the branches are the original time series, and its down-sampled versionsinput_smallseq = Input(shape=(inputs_lens[0], 19))input_medseq = Input(shape=(inputs_lens[1] , 19))input_origseq = Input(shape=(inputs_lens[2], 19))#the more down-sampled the time series, the shorter the corresponding filterbase_net_small = get_base_model(inputs_lens[0], fsizes[0])base_net_med = get_base_model(inputs_lens[1], fsizes[1])base_net_original = get_base_model(inputs_lens[2], fsizes[2])embedding_small = base_net_small(input_smallseq)embedding_med = base_net_med(input_medseq)embedding_original = base_net_original(input_origseq)#concatenate all the outputsmerged = Concatenate()([embedding_small, embedding_med, embedding_original])out = Dense(1, activation='sigmoid')(merged)model = Model(inputs=[input_smallseq, input_medseq, input_origseq], outputs=out)return model" }, { "code": null, "e": 8445, "s": 8359, "text": "This model is a much simpler version of the multi-scale convolutional neural network." }, { "code": null, "e": 9022, "s": 8445, "text": "It takes the original time series and 2 down-sampled versions of it (medium and small length) as an input. The first branch of the model processes the original time series of length 3480 and of width 19. The corresponding convolution filter length is 24. The second branch processes the medium-length (1024 timesteps) down-sampled version of the time series, and the filter length used here is 16. The third branch processes the shortest version (512 timesteps) of the time series, with the filter length of 8. This way every branch extracts features on different time scales." }, { "code": null, "e": 9213, "s": 9022, "text": "After convolutional and global max-pooling layers, dropout regularization is added, and all the outputs are concatenated. The last fully connected layer returns the result of classification." }, { "code": null, "e": 9560, "s": 9213, "text": "In this article I tried to explain how deep convolutional neural networks can be used to classify time series. It is worth mentioning that the proposed method is not the only one that exists. There are ways of presenting time series in the form of images (for example, using their spectrograms), to which a regular 2-D convolution can be applied." }, { "code": null, "e": 9681, "s": 9560, "text": "Thank you very much for reading this article. I hope it was helpful to you, and I would really appreciate your feedback." }, { "code": null, "e": 9693, "s": 9681, "text": "References:" }, { "code": null, "e": 9838, "s": 9693, "text": "[1] Z. Cui, W. Chen, Y. Chen, Multi-Scale Convolutional Neural Networks for Time Series Classification (2016), https://arxiv.org/abs/1603.06995." } ]
Pareto Distributions and Monte Carlo Simulations | by Michael Grogan | Towards Data Science
Pareto Distributions are all around us. It has also been referred to as the 80/20 rule. As some examples: 20% of all websites get 80% of the traffic. The top 20% of earners globally make 80% of the income. You wear 20% of your clothes 80% of the time. Traditionally, we are thought that the assumed distribution for a statistical range is a normal distribution, i.e. one where the mean = median = mode. However, many of the phenomena we observe around us often more closely resemble a Pareto distribution. In this particular example, we can see a distribution that is heavily right-tailed, i.e. most of the observations with lower values (as defined by the x-axis) tend to the left of the graph, while a select few observations with higher values tend towards the right of the graph. Let’s take the example of web page views over time. Here is a line graph showing fluctuations over time for the term “earthquake” from January 2016 — August 2020 from Wikimedia Toolforge: We can see that there are “spikes” in page views at certain periods — possibly at a time when an earthquake is under way somewhere in the world. This is what we would expect — this is an example of a search term which sees higher page view interest at certain times. As a matter of fact, many webpages follow this pattern, where traffic more or less follows a stationary pattern — accompanied by sudden “spikes”. Let’s plot a histogram of this data. In the above instance, we see that the majority of page views for a given day are below 10,000, while there are a select few incidences where this is exceeded. The maximum number of page views in a given day over the selected time period was 31,520. This closely represents a Pareto Distribution. Attempting to forecast page views with traditional time series tools such as ARIMA is quite futile. This is because it is not possible to know in advance when a particular spike in traffic will occur — as it is heavily dependent on external circumstances and not related to past data. A more meaningful exercise would be to run simulations to forecast the range of traffic that one might expect to see given the assumption of a Pareto distribution. The Pareto Distribution is called in Python as follows: numpy.random.pareto(a, size=None) a represents the shape of the distribution, and size is set to 10,000, i.e. 10,000 random numbers from the distribution are generated for the Monte Carlo simulation. The mean and standard deviation for the original time series are calculated. mu=np.mean(value)sigma=np.std(value) The time series has a mean of 5224 and a standard deviation of 2057. Using these values, a Monte Carlo simulation can be generated using these parameters, along with the random sampling from an assumed Pareto distribution. t = np.random.pareto(a, 10000) * (mu+sigma)t As mentioned, the value of a is dependent on the shape of the distribution. Let’s set this to 3 in the first instance. Here are the recorded values for the distribution in percentile terms: We can see that the maximum value recorded when a = 3 is in excess of 350,000, which is far higher than the maximum recorded by the time series. What happens if we set a = 4? We now see that the maximum recorded value is now in excess of 60,000, which is still a lot higher than the maximum recorded by the time series. Let’s try a = 5. Maximum page views are just above 35,000, which is more in line with what we have seen in the original time series. However, consider that in this case — we are only looking at time series data from 2016 onwards. Many of the most serious earthquakes actually happened before 2016. For instance, let us suppose that an earthquake as serious as that of the 2004 Indian Ocean earthquake and tsunami were to happen today — we would reasonably expect that page view interest for the term “earthquake” would be much larger than that which we have observed since 2016. If we assume that the Pareto distribution has a = 3, then the model is indicating that page views for this term could spike to in excess of 350,000. In this regard, the Monte Carlo simulation is allowing us to examine scenarios that would be beyond the bounds of the time series data that has been recorded. Earthquakes (unfortunately) have been around for a lot longer than the internet has — and therefore we have no way of measuring what page views for this search term would have been like during times where the most powerful earthquakes were recorded. That said, conducting a Monte Carlo Simulation in conjunction with modelling on the closest theoretical distribution can allow for a strong scenario analysis of what the bounds of a time series could be under particular circumstances. In this article, you have seen: What is a Pareto Distribution How to generate such a distribution in Python How to combine a Pareto distribution with a Monte Carlo simulation Many thanks for your time. As always, very grateful for any feedback, thoughts, or indeed questions. Please feel free to leave them in the comments section. 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 in any way. Machine Learning Mastery: Monte Carlo Sampling for Probability Numpy v1.14 manual: numpy.random.pareto Stack Overflow: Matplotlib — Draw lines from x axis to points Towards Data Science - Monte Carlo Simulations in Python: Analysing Web Page Views Wikimedia Toolforge: Pageviews Analysis
[ { "code": null, "e": 277, "s": 171, "text": "Pareto Distributions are all around us. It has also been referred to as the 80/20 rule. As some examples:" }, { "code": null, "e": 321, "s": 277, "text": "20% of all websites get 80% of the traffic." }, { "code": null, "e": 377, "s": 321, "text": "The top 20% of earners globally make 80% of the income." }, { "code": null, "e": 423, "s": 377, "text": "You wear 20% of your clothes 80% of the time." }, { "code": null, "e": 574, "s": 423, "text": "Traditionally, we are thought that the assumed distribution for a statistical range is a normal distribution, i.e. one where the mean = median = mode." }, { "code": null, "e": 677, "s": 574, "text": "However, many of the phenomena we observe around us often more closely resemble a Pareto distribution." }, { "code": null, "e": 955, "s": 677, "text": "In this particular example, we can see a distribution that is heavily right-tailed, i.e. most of the observations with lower values (as defined by the x-axis) tend to the left of the graph, while a select few observations with higher values tend towards the right of the graph." }, { "code": null, "e": 1143, "s": 955, "text": "Let’s take the example of web page views over time. Here is a line graph showing fluctuations over time for the term “earthquake” from January 2016 — August 2020 from Wikimedia Toolforge:" }, { "code": null, "e": 1288, "s": 1143, "text": "We can see that there are “spikes” in page views at certain periods — possibly at a time when an earthquake is under way somewhere in the world." }, { "code": null, "e": 1556, "s": 1288, "text": "This is what we would expect — this is an example of a search term which sees higher page view interest at certain times. As a matter of fact, many webpages follow this pattern, where traffic more or less follows a stationary pattern — accompanied by sudden “spikes”." }, { "code": null, "e": 1593, "s": 1556, "text": "Let’s plot a histogram of this data." }, { "code": null, "e": 1753, "s": 1593, "text": "In the above instance, we see that the majority of page views for a given day are below 10,000, while there are a select few incidences where this is exceeded." }, { "code": null, "e": 1890, "s": 1753, "text": "The maximum number of page views in a given day over the selected time period was 31,520. This closely represents a Pareto Distribution." }, { "code": null, "e": 2175, "s": 1890, "text": "Attempting to forecast page views with traditional time series tools such as ARIMA is quite futile. This is because it is not possible to know in advance when a particular spike in traffic will occur — as it is heavily dependent on external circumstances and not related to past data." }, { "code": null, "e": 2339, "s": 2175, "text": "A more meaningful exercise would be to run simulations to forecast the range of traffic that one might expect to see given the assumption of a Pareto distribution." }, { "code": null, "e": 2395, "s": 2339, "text": "The Pareto Distribution is called in Python as follows:" }, { "code": null, "e": 2429, "s": 2395, "text": "numpy.random.pareto(a, size=None)" }, { "code": null, "e": 2595, "s": 2429, "text": "a represents the shape of the distribution, and size is set to 10,000, i.e. 10,000 random numbers from the distribution are generated for the Monte Carlo simulation." }, { "code": null, "e": 2672, "s": 2595, "text": "The mean and standard deviation for the original time series are calculated." }, { "code": null, "e": 2709, "s": 2672, "text": "mu=np.mean(value)sigma=np.std(value)" }, { "code": null, "e": 2778, "s": 2709, "text": "The time series has a mean of 5224 and a standard deviation of 2057." }, { "code": null, "e": 2932, "s": 2778, "text": "Using these values, a Monte Carlo simulation can be generated using these parameters, along with the random sampling from an assumed Pareto distribution." }, { "code": null, "e": 2977, "s": 2932, "text": "t = np.random.pareto(a, 10000) * (mu+sigma)t" }, { "code": null, "e": 3096, "s": 2977, "text": "As mentioned, the value of a is dependent on the shape of the distribution. Let’s set this to 3 in the first instance." }, { "code": null, "e": 3167, "s": 3096, "text": "Here are the recorded values for the distribution in percentile terms:" }, { "code": null, "e": 3312, "s": 3167, "text": "We can see that the maximum value recorded when a = 3 is in excess of 350,000, which is far higher than the maximum recorded by the time series." }, { "code": null, "e": 3342, "s": 3312, "text": "What happens if we set a = 4?" }, { "code": null, "e": 3487, "s": 3342, "text": "We now see that the maximum recorded value is now in excess of 60,000, which is still a lot higher than the maximum recorded by the time series." }, { "code": null, "e": 3504, "s": 3487, "text": "Let’s try a = 5." }, { "code": null, "e": 3620, "s": 3504, "text": "Maximum page views are just above 35,000, which is more in line with what we have seen in the original time series." }, { "code": null, "e": 3785, "s": 3620, "text": "However, consider that in this case — we are only looking at time series data from 2016 onwards. Many of the most serious earthquakes actually happened before 2016." }, { "code": null, "e": 4066, "s": 3785, "text": "For instance, let us suppose that an earthquake as serious as that of the 2004 Indian Ocean earthquake and tsunami were to happen today — we would reasonably expect that page view interest for the term “earthquake” would be much larger than that which we have observed since 2016." }, { "code": null, "e": 4215, "s": 4066, "text": "If we assume that the Pareto distribution has a = 3, then the model is indicating that page views for this term could spike to in excess of 350,000." }, { "code": null, "e": 4374, "s": 4215, "text": "In this regard, the Monte Carlo simulation is allowing us to examine scenarios that would be beyond the bounds of the time series data that has been recorded." }, { "code": null, "e": 4624, "s": 4374, "text": "Earthquakes (unfortunately) have been around for a lot longer than the internet has — and therefore we have no way of measuring what page views for this search term would have been like during times where the most powerful earthquakes were recorded." }, { "code": null, "e": 4859, "s": 4624, "text": "That said, conducting a Monte Carlo Simulation in conjunction with modelling on the closest theoretical distribution can allow for a strong scenario analysis of what the bounds of a time series could be under particular circumstances." }, { "code": null, "e": 4891, "s": 4859, "text": "In this article, you have seen:" }, { "code": null, "e": 4921, "s": 4891, "text": "What is a Pareto Distribution" }, { "code": null, "e": 4967, "s": 4921, "text": "How to generate such a distribution in Python" }, { "code": null, "e": 5034, "s": 4967, "text": "How to combine a Pareto distribution with a Monte Carlo simulation" }, { "code": null, "e": 5191, "s": 5034, "text": "Many thanks for your time. As always, very grateful for any feedback, thoughts, or indeed questions. Please feel free to leave them in the comments section." }, { "code": null, "e": 5419, "s": 5191, "text": "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 in any way." }, { "code": null, "e": 5482, "s": 5419, "text": "Machine Learning Mastery: Monte Carlo Sampling for Probability" }, { "code": null, "e": 5522, "s": 5482, "text": "Numpy v1.14 manual: numpy.random.pareto" }, { "code": null, "e": 5584, "s": 5522, "text": "Stack Overflow: Matplotlib — Draw lines from x axis to points" }, { "code": null, "e": 5667, "s": 5584, "text": "Towards Data Science - Monte Carlo Simulations in Python: Analysing Web Page Views" } ]
How do I see all foreign keys to a table column?
To see all the foreign keys to a table or column, the referenced_column_name command is used. First, two tables are created and then related with the help of the foreign key constraint. Creating the first table − mysql> CREATE table ForeignTable -> ( -> id int, -> name varchar(200), -> Fk_pk int -> ); Query OK, 0 rows affected (0.43 sec) After creating the first table successfully, the second table is created as follows − mysql> CREATE table primaryTable1 -> ( -> Fk_pk int, -> DeptName varchar(200), -> Primary key(Fk_pk) -> ); Query OK, 0 rows affected (0.48 sec) Now, both the tables are related with the help of the alter command and the foreign key constraint is also added. The syntax for this is as follows − alter table yourFirstTable add constraint anyConstraintName foreign key(column_name which is acts foreign key in second table) yourSecondTable(column_name which acts primary key in second table). The above syntax is applied to relate both the tables as follows − mysql> alter table ForeignTable add constraint constFKPK foreign key(Fk_pk) references primaryTable1(Fk_pk); Query OK, 0 rows affected (1.57 sec) Records: 0 Duplicates: 0 Warnings: 0 Now, the syntax to see all the foreign keys to a table is given as follows − For a table − SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = 'yourReferencedTableName'; Now the above syntax is used to create the query to view all the foreign keys. The query is given as follows − mysql> SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME -> FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE -> WHERE REFERENCED_TABLE_NAME = 'primarytable1'; The following is the output − +--------------+-------------+-----------------+-----------------------+------------------------+ | TABLE_NAME | COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME | +--------------+-------------+-----------------+-----------------------+------------------------+ | foreigntable | Fk_pk | constFKPK | primarytable1 | fk_pk | +--------------+-------------+-----------------+-----------------------+------------------------+ 1 row in set, 2 warnings (0.02 sec) In the sample output, the constraint_name is ‘constFKPK’ and table_name is ‘foreigntable’. For a column − SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'yourDatabaseName' AND REFERENCED_TABLE_NAME = 'yourreferencedtablename' AND REFERENCED_COLUMN_NAME = 'yourreferencedcolumnname'; The query to display all the foreign keys to a column is given using the above syntax. The query is as follows − mysql> SELECT -> TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME -> FROM -> INFORMATION_SCHEMA.KEY_COLUMN_USAGE -> WHERE -> REFERENCED_TABLE_SCHEMA = 'business' AND -> REFERENCED_TABLE_NAME = 'primarytable1' AND REFERENCED_COLUMN_NAME = 'fk_pk'; The output obtained is as follows: +--------------+-------------+-----------------+-----------------------+------------------------+ | TABLE_NAME | COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_TABLE_NAME |REFERENCED_COLUMN_NAME | +--------------+-------------+-----------------+-----------------------+------------------------+ | foreigntable | Fk_pk | constFKPK | primarytable1 | fk_pk | +--------------+-------------+-----------------+-----------------------+------------------------+ 1 row in set, 2 warnings (0.03 sec)
[ { "code": null, "e": 1156, "s": 1062, "text": "To see all the foreign keys to a table or column, the referenced_column_name command is\nused." }, { "code": null, "e": 1248, "s": 1156, "text": "First, two tables are created and then related with the help of the foreign key constraint." }, { "code": null, "e": 1275, "s": 1248, "text": "Creating the first table −" }, { "code": null, "e": 1402, "s": 1275, "text": "mysql> CREATE table ForeignTable\n-> (\n-> id int,\n-> name varchar(200),\n-> Fk_pk int\n-> );\nQuery OK, 0 rows affected (0.43 sec)" }, { "code": null, "e": 1488, "s": 1402, "text": "After creating the first table successfully, the second table is created as follows −" }, { "code": null, "e": 1632, "s": 1488, "text": "mysql> CREATE table primaryTable1\n-> (\n-> Fk_pk int,\n-> DeptName varchar(200),\n-> Primary key(Fk_pk)\n-> );\nQuery OK, 0 rows affected (0.48 sec)" }, { "code": null, "e": 1782, "s": 1632, "text": "Now, both the tables are related with the help of the alter command and the foreign key\nconstraint is also added. The syntax for this is as follows −" }, { "code": null, "e": 1978, "s": 1782, "text": "alter table yourFirstTable add constraint anyConstraintName foreign key(column_name which is\nacts foreign key in second table) yourSecondTable(column_name which acts primary key in\nsecond table)." }, { "code": null, "e": 2045, "s": 1978, "text": "The above syntax is applied to relate both the tables as follows −" }, { "code": null, "e": 2228, "s": 2045, "text": "mysql> alter table ForeignTable add constraint constFKPK foreign key(Fk_pk) references\nprimaryTable1(Fk_pk);\nQuery OK, 0 rows affected (1.57 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2305, "s": 2228, "text": "Now, the syntax to see all the foreign keys to a table is given as follows −" }, { "code": null, "e": 2319, "s": 2305, "text": "For a table −" }, { "code": null, "e": 2512, "s": 2319, "text": "SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME,\nREFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME\nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE REFERENCED_TABLE_NAME = 'yourReferencedTableName';" }, { "code": null, "e": 2623, "s": 2512, "text": "Now the above syntax is used to create the query to view all the foreign keys. The query is given as follows −" }, { "code": null, "e": 2818, "s": 2623, "text": "mysql> SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME,\nREFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME\n-> FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n-> WHERE REFERENCED_TABLE_NAME = 'primarytable1';" }, { "code": null, "e": 2848, "s": 2818, "text": "The following is the output −" }, { "code": null, "e": 3374, "s": 2848, "text": "+--------------+-------------+-----------------+-----------------------+------------------------+\n| TABLE_NAME | COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |\n+--------------+-------------+-----------------+-----------------------+------------------------+\n| foreigntable | Fk_pk | constFKPK | primarytable1 | fk_pk |\n+--------------+-------------+-----------------+-----------------------+------------------------+\n1 row in set, 2 warnings (0.02 sec)" }, { "code": null, "e": 3480, "s": 3374, "text": "In the sample output, the constraint_name is ‘constFKPK’ and table_name is ‘foreigntable’.\nFor a column −" }, { "code": null, "e": 3775, "s": 3480, "text": "SELECT\nTABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,\nREFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME\nFROM\nINFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE\nREFERENCED_TABLE_SCHEMA = 'yourDatabaseName' AND\nREFERENCED_TABLE_NAME = 'yourreferencedtablename' AND\nREFERENCED_COLUMN_NAME = 'yourreferencedcolumnname';" }, { "code": null, "e": 3888, "s": 3775, "text": "The query to display all the foreign keys to a column is given using the above syntax. The query is as\nfollows −" }, { "code": null, "e": 4171, "s": 3888, "text": "mysql> SELECT\n-> TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,\nREFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME\n-> FROM\n-> INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n-> WHERE\n-> REFERENCED_TABLE_SCHEMA = 'business' AND\n-> REFERENCED_TABLE_NAME = 'primarytable1' AND REFERENCED_COLUMN_NAME\n= 'fk_pk';" }, { "code": null, "e": 4206, "s": 4171, "text": "The output obtained is as follows:" }, { "code": null, "e": 4732, "s": 4206, "text": "+--------------+-------------+-----------------+-----------------------+------------------------+\n| TABLE_NAME | COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_TABLE_NAME |REFERENCED_COLUMN_NAME |\n+--------------+-------------+-----------------+-----------------------+------------------------+\n| foreigntable | Fk_pk | constFKPK | primarytable1 | fk_pk |\n+--------------+-------------+-----------------+-----------------------+------------------------+\n1 row in set, 2 warnings (0.03 sec)" } ]
acpi_available command in Linux with examples - GeeksforGeeks
04 Apr, 2019 acpi_available is a command in Linux which test whether ACPI (Advanced Configuration and Power Interface) subsystem is available or not. It has three return statuses: 0 : It means ACPI subsystem is available. 1 : It means ACPI subsystem is not available. 2 : It means some usage error has occured. Syntax: $ acpi_available Example 1: Here, echo $? is a command which is used to see the last return status. Example 2: Here, we create a false error and then displayed return status. Options: info acpi_available : It displays help information.Example: Example: linux-command Linux-misc-commands Picked Technical Scripter 2018 Linux-Unix Technical Scripter 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 ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++
[ { "code": null, "e": 23725, "s": 23697, "text": "\n04 Apr, 2019" }, { "code": null, "e": 23892, "s": 23725, "text": "acpi_available is a command in Linux which test whether ACPI (Advanced Configuration and Power Interface) subsystem is available or not. It has three return statuses:" }, { "code": null, "e": 23934, "s": 23892, "text": "0 : It means ACPI subsystem is available." }, { "code": null, "e": 23980, "s": 23934, "text": "1 : It means ACPI subsystem is not available." }, { "code": null, "e": 24023, "s": 23980, "text": "2 : It means some usage error has occured." }, { "code": null, "e": 24031, "s": 24023, "text": "Syntax:" }, { "code": null, "e": 24048, "s": 24031, "text": "$ acpi_available" }, { "code": null, "e": 24131, "s": 24048, "text": "Example 1: Here, echo $? is a command which is used to see the last return status." }, { "code": null, "e": 24206, "s": 24131, "text": "Example 2: Here, we create a false error and then displayed return status." }, { "code": null, "e": 24215, "s": 24206, "text": "Options:" }, { "code": null, "e": 24275, "s": 24215, "text": "info acpi_available : It displays help information.Example:" }, { "code": null, "e": 24284, "s": 24275, "text": "Example:" }, { "code": null, "e": 24298, "s": 24284, "text": "linux-command" }, { "code": null, "e": 24318, "s": 24298, "text": "Linux-misc-commands" }, { "code": null, "e": 24325, "s": 24318, "text": "Picked" }, { "code": null, "e": 24349, "s": 24325, "text": "Technical Scripter 2018" }, { "code": null, "e": 24360, "s": 24349, "text": "Linux-Unix" }, { "code": null, "e": 24379, "s": 24360, "text": "Technical Scripter" }, { "code": null, "e": 24477, "s": 24379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24486, "s": 24477, "text": "Comments" }, { "code": null, "e": 24499, "s": 24486, "text": "Old Comments" }, { "code": null, "e": 24537, "s": 24499, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 24572, "s": 24537, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 24607, "s": 24572, "text": "tar command in Linux with examples" }, { "code": null, "e": 24643, "s": 24607, "text": "curl command in Linux with Examples" }, { "code": null, "e": 24681, "s": 24643, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 24719, "s": 24681, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 24754, "s": 24719, "text": "Cat command in Linux with examples" }, { "code": null, "e": 24791, "s": 24754, "text": "touch command in Linux with Examples" }, { "code": null, "e": 24827, "s": 24791, "text": "echo command in Linux with Examples" } ]
Batch Script - DEL
This batch command deletes files and not directories. del [filename] The following example shows the different variants of the del command. @echo off Rem Deletes the file lists.txt in C:\ del C:\lists.txt Rem Deletes all files recursively in all nested directories del /s *.txt Rem Deletes all files recursively in all nested directories , but asks for the confirmation from the user first Del /p /s *.txt All actions are performed as per the remarks in the batch file. Print Add Notes Bookmark this page
[ { "code": null, "e": 2223, "s": 2169, "text": "This batch command deletes files and not directories." }, { "code": null, "e": 2239, "s": 2223, "text": "del [filename]\n" }, { "code": null, "e": 2310, "s": 2239, "text": "The following example shows the different variants of the del command." }, { "code": null, "e": 2582, "s": 2310, "text": "@echo off \nRem Deletes the file lists.txt in C:\\ \ndel C:\\lists.txt \nRem Deletes all files recursively in all nested directories\ndel /s *.txt \nRem Deletes all files recursively in all nested directories , but asks for the \nconfirmation from the user first \nDel /p /s *.txt" }, { "code": null, "e": 2646, "s": 2582, "text": "All actions are performed as per the remarks in the batch file." }, { "code": null, "e": 2653, "s": 2646, "text": " Print" }, { "code": null, "e": 2664, "s": 2653, "text": " Add Notes" } ]
Understanding Linear Regression. The Workhorse Of Data Science | by Tony Yiu | Towards Data Science
Despite the prevalence of more complicated and fancier models in recent years, linear regression remains hard to beat because of its versatility, robustness, and explainability. It’s a simple but powerful model that just gets the job done. And if you want to go into a quantitative field, you will need to understand how it works. Linear regression is basically line fitting. It asks the question — “What is the equation of the line that best fits my data?” Nice and simple. The equation of a line is: Y = b0 + b1*X Y, the target variable, is the thing we are trying to model. We want to understand (a.k.a. explain) its variance. In statistics, variance is a measure of uncertainty. It’s the tendency of a value to whip about its mean. The graphic to the left illustrates this. The green variable has a high variance and thus a large cone of uncertainty around its mean (the center of the cone). The red variable has a lower variance. Knowing nothing else about the variables, we would feel much more confident in our ability to not be too far off when guessing the value of the red variable. But in data science and statistics in general, we’re not worried about variance, we’re only worried about variance that cannot be explained. That is, if we can find some other variable (the feature variable, X), that explains much of the variance in Y, then we are good. With such a feature variable, if someone were to ask me for my prediction of Y, I just need to look up what X is equal to, and I can be reasonably certain of what Y will be. Much of Y’s variance has been explained by incorporating X. So why does line fitting help us explain the variance? Think about what the line’s equation represents. It defines the relationship between X and Y. By multiplying X by b1 and summing with b0 (b0 + b1*X), we get our prediction of Y based on a given value of X. Of course, this only works if X and Y are correlated (either positively or negatively). Correlation measures the tendency of two things to move together (or opposite of each other in the case of a negative correlation). For example, people’s height and weight are positively correlated. The taller you are, the more you tend to weigh. So line fitting allows us to infer the value of something we don’t know, Y, from the value of something that we do know, X, thanks to the correlation between X and Y. We are explaining the variance of Y using the X variables in our linear regression equation. By attributing (a.k.a. explaining) variance this way, we are in effect reducing it — explained variance is variance that we no longer have to worry about. The lynchpin assumption is that the X variables are readily measurable, understood, and not themselves a mystery. A common modeling mistake is to forecast something using variables that are themselves not observable in real-time. A model that forecasts the future using data from the future is no good. Let’s see how this process works. When we start out with just a Y variable, all we know about it is its distribution. In the figure below, all the variance (the green cone) is unexplained and our best guess of the future value of Y is its mean. Now let’s say we’ve found a feature variable, X, with a positive correlation to Y. The figure below shows how X helps to explain variance. We can segment the observations of Y into two sections based on their X values. For low values of X, Y has an expected value of Mean 1 and a variance approximated by the left red cone. For high values of X, Y has an expected value of Mean 2 and a variance approximated by the right red cone. Notice how by segmenting this way, the variance (the red cones) has been reduced relative to the original green cone. And our new prediction of Y, either Mean 1 or Mean 2 depending on what X is, is significantly more precise than our previous naive prediction (the mean of Y). But why stop at two segmentations? If we drew more blue dashed vertical lines, and broke the data into even more buckets, we could explain even more variance and generate even more precise predictions. And that’s what linear regression does. In effect, it draws tons and tons of vertical lines that break the data into numerous tiny segmentations. This maximizes both the variance explained and the precision around our prediction. Let’s quickly cover how linear regression finds the line of best fit. While there is an analytical solution, you can think of it as an optimization problem. The linear regression algorithm wants to: Find the values for b0 and b1that minimizes the sum of squared errors. Error is the distance between the data (black dots) and the blue line — in the picture below, the red arrows denote error. We square the error because it can be either positive or negative. Now that we know that error is the difference between the actual observations (Y, the black dots) and our prediction (the blue line), we can write out our optimization problem in more detail: Find the values for b0 and b1that minimizes the sum of squared errors.Where squared error for observation i= (Yi - (b0 + b1*Xi))^2And the sum of squared error is just the sum of (Yi - (b0 + b1*Xi))^2 for all observations. So to calculate the sum of squared errors, we take every vertical distance between a black dot and the blue line, square them, and sum them up. Finding the values of b0 and b1 that minimize this sum of squared errors gets us to the line of best fit. The parameters (b0, b1, etc.), known as betas, that fall out of a regression are important. In our earlier example, we had just a single feature variable. But say we had three feature variables: Y = b0 + b1*X1 + b2*X2 + b3*X3 b0 is the intercept between the Y axis and the blue line and tells us the expected value of Y when all our feature variables are 0. b1 tells us how, when holding X2 and X3 constant, changing X1 impacts Y. b2 tells us how, when holding X1 and X3 constant, changing X2 impacts Y. b3 tells us how, when holding X1 and X2 constant, changing X3 impacts Y. A key assumption for the interpretation of the betas is that you can hold the other feature variables constant. In some cases, it might be extremely hard to shift one feature without changing another. In this case, we would want to include these interaction effects (a topic for another post). Finally, we want to figure out how much of the original variance we were able to explain (since the goal is to explain, and therefore reduce variance). We can do that by calculating the R2: R^2 = 1 - (residual sum of squares / total sum of squares) The residual (a.k.a. error) sum of squares is proportional to the variance of our prediction errors (the vertical distances between the black dots and the blue line). Prediction error is the difference between the actual observation and our model’s prediction of it. It is a measure of unexplained variance. Total sum of squares is proportional to the total variance (of Y) that we are trying to explain — it’s actually the numerator of the formula for the variance of Y. The ratio of residual sum of squares to total sum of squares measures the proportion of variance left unexplained after running the linear regression. In other words, it’s the proportion of uncertainty that we could not make vanish with our linear regression. Since R2 is one minus that ratio, it can be thought of as the proportion of variance explained: R^2 = 1 - (residual sum of squares / total sum of squares)= 1 - proportion of variance unexplained= proportion of variance explainedSince: prop. of variance unexplained + prop of variance explained = 1 So if after running our regression, we see an R2 of 0.90, that means the X variables we included in our model helped explain 90% of the variance observed in Y. In other words, we successfully explained away much of uncertainty around the variable we are interested in. In future posts, we will do some examples as well as look at what happens when some of the assumptions that underpin linear regression are violated. Until then, cheers! If you liked this article and my writing in general, please consider supporting my writing by signing up for Medium via my referral link here. Thanks!
[ { "code": null, "e": 350, "s": 172, "text": "Despite the prevalence of more complicated and fancier models in recent years, linear regression remains hard to beat because of its versatility, robustness, and explainability." }, { "code": null, "e": 503, "s": 350, "text": "It’s a simple but powerful model that just gets the job done. And if you want to go into a quantitative field, you will need to understand how it works." }, { "code": null, "e": 647, "s": 503, "text": "Linear regression is basically line fitting. It asks the question — “What is the equation of the line that best fits my data?” Nice and simple." }, { "code": null, "e": 674, "s": 647, "text": "The equation of a line is:" }, { "code": null, "e": 688, "s": 674, "text": "Y = b0 + b1*X" }, { "code": null, "e": 908, "s": 688, "text": "Y, the target variable, is the thing we are trying to model. We want to understand (a.k.a. explain) its variance. In statistics, variance is a measure of uncertainty. It’s the tendency of a value to whip about its mean." }, { "code": null, "e": 1265, "s": 908, "text": "The graphic to the left illustrates this. The green variable has a high variance and thus a large cone of uncertainty around its mean (the center of the cone). The red variable has a lower variance. Knowing nothing else about the variables, we would feel much more confident in our ability to not be too far off when guessing the value of the red variable." }, { "code": null, "e": 1536, "s": 1265, "text": "But in data science and statistics in general, we’re not worried about variance, we’re only worried about variance that cannot be explained. That is, if we can find some other variable (the feature variable, X), that explains much of the variance in Y, then we are good." }, { "code": null, "e": 1770, "s": 1536, "text": "With such a feature variable, if someone were to ask me for my prediction of Y, I just need to look up what X is equal to, and I can be reasonably certain of what Y will be. Much of Y’s variance has been explained by incorporating X." }, { "code": null, "e": 2031, "s": 1770, "text": "So why does line fitting help us explain the variance? Think about what the line’s equation represents. It defines the relationship between X and Y. By multiplying X by b1 and summing with b0 (b0 + b1*X), we get our prediction of Y based on a given value of X." }, { "code": null, "e": 2366, "s": 2031, "text": "Of course, this only works if X and Y are correlated (either positively or negatively). Correlation measures the tendency of two things to move together (or opposite of each other in the case of a negative correlation). For example, people’s height and weight are positively correlated. The taller you are, the more you tend to weigh." }, { "code": null, "e": 2533, "s": 2366, "text": "So line fitting allows us to infer the value of something we don’t know, Y, from the value of something that we do know, X, thanks to the correlation between X and Y." }, { "code": null, "e": 2781, "s": 2533, "text": "We are explaining the variance of Y using the X variables in our linear regression equation. By attributing (a.k.a. explaining) variance this way, we are in effect reducing it — explained variance is variance that we no longer have to worry about." }, { "code": null, "e": 3084, "s": 2781, "text": "The lynchpin assumption is that the X variables are readily measurable, understood, and not themselves a mystery. A common modeling mistake is to forecast something using variables that are themselves not observable in real-time. A model that forecasts the future using data from the future is no good." }, { "code": null, "e": 3329, "s": 3084, "text": "Let’s see how this process works. When we start out with just a Y variable, all we know about it is its distribution. In the figure below, all the variance (the green cone) is unexplained and our best guess of the future value of Y is its mean." }, { "code": null, "e": 3760, "s": 3329, "text": "Now let’s say we’ve found a feature variable, X, with a positive correlation to Y. The figure below shows how X helps to explain variance. We can segment the observations of Y into two sections based on their X values. For low values of X, Y has an expected value of Mean 1 and a variance approximated by the left red cone. For high values of X, Y has an expected value of Mean 2 and a variance approximated by the right red cone." }, { "code": null, "e": 4037, "s": 3760, "text": "Notice how by segmenting this way, the variance (the red cones) has been reduced relative to the original green cone. And our new prediction of Y, either Mean 1 or Mean 2 depending on what X is, is significantly more precise than our previous naive prediction (the mean of Y)." }, { "code": null, "e": 4239, "s": 4037, "text": "But why stop at two segmentations? If we drew more blue dashed vertical lines, and broke the data into even more buckets, we could explain even more variance and generate even more precise predictions." }, { "code": null, "e": 4469, "s": 4239, "text": "And that’s what linear regression does. In effect, it draws tons and tons of vertical lines that break the data into numerous tiny segmentations. This maximizes both the variance explained and the precision around our prediction." }, { "code": null, "e": 4668, "s": 4469, "text": "Let’s quickly cover how linear regression finds the line of best fit. While there is an analytical solution, you can think of it as an optimization problem. The linear regression algorithm wants to:" }, { "code": null, "e": 4739, "s": 4668, "text": "Find the values for b0 and b1that minimizes the sum of squared errors." }, { "code": null, "e": 4929, "s": 4739, "text": "Error is the distance between the data (black dots) and the blue line — in the picture below, the red arrows denote error. We square the error because it can be either positive or negative." }, { "code": null, "e": 5121, "s": 4929, "text": "Now that we know that error is the difference between the actual observations (Y, the black dots) and our prediction (the blue line), we can write out our optimization problem in more detail:" }, { "code": null, "e": 5343, "s": 5121, "text": "Find the values for b0 and b1that minimizes the sum of squared errors.Where squared error for observation i= (Yi - (b0 + b1*Xi))^2And the sum of squared error is just the sum of (Yi - (b0 + b1*Xi))^2 for all observations." }, { "code": null, "e": 5593, "s": 5343, "text": "So to calculate the sum of squared errors, we take every vertical distance between a black dot and the blue line, square them, and sum them up. Finding the values of b0 and b1 that minimize this sum of squared errors gets us to the line of best fit." }, { "code": null, "e": 5788, "s": 5593, "text": "The parameters (b0, b1, etc.), known as betas, that fall out of a regression are important. In our earlier example, we had just a single feature variable. But say we had three feature variables:" }, { "code": null, "e": 5819, "s": 5788, "text": "Y = b0 + b1*X1 + b2*X2 + b3*X3" }, { "code": null, "e": 5951, "s": 5819, "text": "b0 is the intercept between the Y axis and the blue line and tells us the expected value of Y when all our feature variables are 0." }, { "code": null, "e": 6024, "s": 5951, "text": "b1 tells us how, when holding X2 and X3 constant, changing X1 impacts Y." }, { "code": null, "e": 6097, "s": 6024, "text": "b2 tells us how, when holding X1 and X3 constant, changing X2 impacts Y." }, { "code": null, "e": 6170, "s": 6097, "text": "b3 tells us how, when holding X1 and X2 constant, changing X3 impacts Y." }, { "code": null, "e": 6464, "s": 6170, "text": "A key assumption for the interpretation of the betas is that you can hold the other feature variables constant. In some cases, it might be extremely hard to shift one feature without changing another. In this case, we would want to include these interaction effects (a topic for another post)." }, { "code": null, "e": 6616, "s": 6464, "text": "Finally, we want to figure out how much of the original variance we were able to explain (since the goal is to explain, and therefore reduce variance)." }, { "code": null, "e": 6654, "s": 6616, "text": "We can do that by calculating the R2:" }, { "code": null, "e": 6713, "s": 6654, "text": "R^2 = 1 - (residual sum of squares / total sum of squares)" }, { "code": null, "e": 7021, "s": 6713, "text": "The residual (a.k.a. error) sum of squares is proportional to the variance of our prediction errors (the vertical distances between the black dots and the blue line). Prediction error is the difference between the actual observation and our model’s prediction of it. It is a measure of unexplained variance." }, { "code": null, "e": 7185, "s": 7021, "text": "Total sum of squares is proportional to the total variance (of Y) that we are trying to explain — it’s actually the numerator of the formula for the variance of Y." }, { "code": null, "e": 7445, "s": 7185, "text": "The ratio of residual sum of squares to total sum of squares measures the proportion of variance left unexplained after running the linear regression. In other words, it’s the proportion of uncertainty that we could not make vanish with our linear regression." }, { "code": null, "e": 7541, "s": 7445, "text": "Since R2 is one minus that ratio, it can be thought of as the proportion of variance explained:" }, { "code": null, "e": 7743, "s": 7541, "text": "R^2 = 1 - (residual sum of squares / total sum of squares)= 1 - proportion of variance unexplained= proportion of variance explainedSince: prop. of variance unexplained + prop of variance explained = 1" }, { "code": null, "e": 8012, "s": 7743, "text": "So if after running our regression, we see an R2 of 0.90, that means the X variables we included in our model helped explain 90% of the variance observed in Y. In other words, we successfully explained away much of uncertainty around the variable we are interested in." }, { "code": null, "e": 8181, "s": 8012, "text": "In future posts, we will do some examples as well as look at what happens when some of the assumptions that underpin linear regression are violated. Until then, cheers!" } ]
Advanced Streamlit Caching. Caching = Better User Experience | by Rahul Agarwal | Towards Data Science
It is straightforward now how to create a web app using Streamlit, but there are a lot of things that it doesn’t allow you to do yet. One of the major issues I faced recently was around caching when I was trying to use a News API to create an analytical news dashboard in Streamlit. The problem was that I was hitting the News API regularly and was reaching the free API limits. Also, running the news API every time the user refreshed the app was getting pretty slow. A solution to that would have been caching the API data. But when I used @st.cache decorator, the page never refreshed as the parameters to the API call remained the same. And that is where I came to understand the limitations of Streamlit when it comes to caching. So, in a nutshell, What I wanted was a way not to hit the API every time the page refreshes. At the same time, since I was getting the News data, I also wanted to hit the API at every 5-minute interval. And, here is the hacky way I accomplished that. Update: In the new release notes for 0.57.0 which just came out yesterday, streamlit has made updates to st.cache. One notable change to this release is the “ability to set expiration options for cached functions by setting the max_entries and ttl arguments”. From the documentation: max_entries (int or None) — The maximum number of entries to keep in the cache, or None for an unbounded cache. (When a new entry is added to a full cache, the oldest cached entry will be removed.) The default is None. ttl (float or None) — The maximum number of seconds to keep an entry in the cache, or None if cache entries should not expire. The default is None. Two use cases where this might help would be: If you’re serving your app and don’t want the cache to grow forever. If you have a cached function that reads live data from a URL and should clear every few hours to fetch the latest data So now what you need to do is just: @st.cache(ttl=60*5,max_entries=20)def hit_news_api(country, n): # hit_api It is really unbelievable how fast things change. Before I begin, Here is a tutorial for streamlit if you are not able to follow this post. towardsdatascience.com When we mark a function with Streamlit’s cache decorator @st.cache, whenever the function is called streamlit checks the input parameters that you called the function with. What happens in the backend is when a function is decorated with @st.cache streamlit keeps all the states of a function in the memory. For example, if we have a simple streamlit app like below: import streamlit as stimport timedef expensive_computation(a, b): time.sleep(2) # 👈 This makes the function take 2s to run return a * ba = 2b = 21res = expensive_computation(a, b)st.write("Result:", res) When we refresh the app, we will notice that expensive_computation(a, b) is re-executed every time the app runs. This isn’t a great experience for the user. Now if we add the @st.cache decorator: import streamlit as stimport [email protected] # 👈 Added thisdef expensive_computation(a, b): time.sleep(2) # This makes the function take 2s to run return a * ba = 2b = 21res = expensive_computation(a, b)st.write("Result:", res) Since the results are now cached for the parameters a and b the expensive_computation doesn’t run again every time the user refreshes the page. And that results in a far better user experience. So what if I wanted to execute a function if the page refreshes after a set time period? i.e., it has been some time since the cached function was last run, and the results need to be updated. To understand this, let us create a basic example. In this example, our function takes a parameter n and a parameter country and returns the top n news item from that country. In this minimal example, it is akin to returning a list of n random numbers. We want to keep showing this list to our users till the next 5 minutes. If the user refreshes the page after 5 minutes, we want the list to be refreshed. This is quite similar to hitting a news API. So our basic app code looks like: import streamlit as stimport randomdef hit_news_api(country, n): st.write("Cache Miss for n:",n) return [random.randint(0,1000) for i in range(n)]results = hit_news_api("USA", 5)st.write(results) And the app looks like: Now every time, I refresh the page, the function hit_news_api gets called again, and that means we will hit our API limits as our number of users increase. So how do we solve this problem? We can use caching. Right. So let us see what happens if we cache the hit_news_api function. import streamlit as stimport [email protected] hit_news_api(country, n): st.write("Cache Miss for n:",n) return [random.randint(0,1000) for i in range(n)]results = hit_news_api("USA", 5)st.write(results) The problem now is that our dashboard never calls the news API after hitting it once if the API parameters remain the same. And we see static results for an eternity for the same set of params. What should we do? We can use this hack — Pass a time-dependent dummy parameter to the hit_news_api function call that changes value every five minutes/ten minutes. The code to do this is: Here the truncate_time function helps us to truncate the current datetime to the nearest lowest divisor for that minute. For Example, given dt_time=’2020–03–27 02:32:19.684443' and period = 5 the function returns ‘2020–03–27 02:30:00.0’. See how we call the hit_news_api function now with the truncated time. Now, whenever the hit_news_api function is called from the time between dt_time=’2020–03–27 02:30:00.0' and dt_time=’2020–03–27 02:34:59.99999' the parameters to the function call remains the same, and hence we don’t hit the API again and again. Exactly what we wanted! This is all well and good, but can you spot a problem with this approach? The cache size is going to grow over time. And that means we need to clear the cache at fixed intervals manually. How do we automate the cache clearing process? It is a pretty simple hack. We can use this below code at the top of our code to clear the whole cache at a period of 1 day. from streamlit import cachingfrom datetime import datedef cache_clear_dt(dummy): clear_dt = date.today() return clear_dtif cache_clear_dt("dummy")<date.today(): caching.clear_cache() This is how the whole app looks with all the above functions. Streamlit has democratized the whole process to create apps, and I couldn’t recommend it more. Yet, there are some things for which we need to go about in a roundabout way. And there are still a lot of things that I will love to have in this awesome platform. I have been in talks with the Streamlit team over the new functionality that they are going to introduce, and I will try to keep you updated on the same. You can find the full code for the final app here at my Github repo. If you want to learn about the best strategies for creating Visualizations, I would like to call out an excellent course about Data Visualization and applied plotting from the University of Michigan, which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 455, "s": 172, "text": "It is straightforward now how to create a web app using Streamlit, but there are a lot of things that it doesn’t allow you to do yet. One of the major issues I faced recently was around caching when I was trying to use a News API to create an analytical news dashboard in Streamlit." }, { "code": null, "e": 641, "s": 455, "text": "The problem was that I was hitting the News API regularly and was reaching the free API limits. Also, running the news API every time the user refreshed the app was getting pretty slow." }, { "code": null, "e": 813, "s": 641, "text": "A solution to that would have been caching the API data. But when I used @st.cache decorator, the page never refreshed as the parameters to the API call remained the same." }, { "code": null, "e": 907, "s": 813, "text": "And that is where I came to understand the limitations of Streamlit when it comes to caching." }, { "code": null, "e": 1110, "s": 907, "text": "So, in a nutshell, What I wanted was a way not to hit the API every time the page refreshes. At the same time, since I was getting the News data, I also wanted to hit the API at every 5-minute interval." }, { "code": null, "e": 1158, "s": 1110, "text": "And, here is the hacky way I accomplished that." }, { "code": null, "e": 1166, "s": 1158, "text": "Update:" }, { "code": null, "e": 1442, "s": 1166, "text": "In the new release notes for 0.57.0 which just came out yesterday, streamlit has made updates to st.cache. One notable change to this release is the “ability to set expiration options for cached functions by setting the max_entries and ttl arguments”. From the documentation:" }, { "code": null, "e": 1661, "s": 1442, "text": "max_entries (int or None) — The maximum number of entries to keep in the cache, or None for an unbounded cache. (When a new entry is added to a full cache, the oldest cached entry will be removed.) The default is None." }, { "code": null, "e": 1809, "s": 1661, "text": "ttl (float or None) — The maximum number of seconds to keep an entry in the cache, or None if cache entries should not expire. The default is None." }, { "code": null, "e": 1855, "s": 1809, "text": "Two use cases where this might help would be:" }, { "code": null, "e": 1924, "s": 1855, "text": "If you’re serving your app and don’t want the cache to grow forever." }, { "code": null, "e": 2044, "s": 1924, "text": "If you have a cached function that reads live data from a URL and should clear every few hours to fetch the latest data" }, { "code": null, "e": 2080, "s": 2044, "text": "So now what you need to do is just:" }, { "code": null, "e": 2157, "s": 2080, "text": "@st.cache(ttl=60*5,max_entries=20)def hit_news_api(country, n): # hit_api" }, { "code": null, "e": 2207, "s": 2157, "text": "It is really unbelievable how fast things change." }, { "code": null, "e": 2297, "s": 2207, "text": "Before I begin, Here is a tutorial for streamlit if you are not able to follow this post." }, { "code": null, "e": 2320, "s": 2297, "text": "towardsdatascience.com" }, { "code": null, "e": 2628, "s": 2320, "text": "When we mark a function with Streamlit’s cache decorator @st.cache, whenever the function is called streamlit checks the input parameters that you called the function with. What happens in the backend is when a function is decorated with @st.cache streamlit keeps all the states of a function in the memory." }, { "code": null, "e": 2687, "s": 2628, "text": "For example, if we have a simple streamlit app like below:" }, { "code": null, "e": 2898, "s": 2687, "text": "import streamlit as stimport timedef expensive_computation(a, b): time.sleep(2) # 👈 This makes the function take 2s to run return a * ba = 2b = 21res = expensive_computation(a, b)st.write(\"Result:\", res)" }, { "code": null, "e": 3055, "s": 2898, "text": "When we refresh the app, we will notice that expensive_computation(a, b) is re-executed every time the app runs. This isn’t a great experience for the user." }, { "code": null, "e": 3094, "s": 3055, "text": "Now if we add the @st.cache decorator:" }, { "code": null, "e": 3328, "s": 3094, "text": "import streamlit as stimport [email protected] # 👈 Added thisdef expensive_computation(a, b): time.sleep(2) # This makes the function take 2s to run return a * ba = 2b = 21res = expensive_computation(a, b)st.write(\"Result:\", res)" }, { "code": null, "e": 3522, "s": 3328, "text": "Since the results are now cached for the parameters a and b the expensive_computation doesn’t run again every time the user refreshes the page. And that results in a far better user experience." }, { "code": null, "e": 3715, "s": 3522, "text": "So what if I wanted to execute a function if the page refreshes after a set time period? i.e., it has been some time since the cached function was last run, and the results need to be updated." }, { "code": null, "e": 3891, "s": 3715, "text": "To understand this, let us create a basic example. In this example, our function takes a parameter n and a parameter country and returns the top n news item from that country." }, { "code": null, "e": 4167, "s": 3891, "text": "In this minimal example, it is akin to returning a list of n random numbers. We want to keep showing this list to our users till the next 5 minutes. If the user refreshes the page after 5 minutes, we want the list to be refreshed. This is quite similar to hitting a news API." }, { "code": null, "e": 4201, "s": 4167, "text": "So our basic app code looks like:" }, { "code": null, "e": 4397, "s": 4201, "text": "import streamlit as stimport randomdef hit_news_api(country, n): st.write(\"Cache Miss for n:\",n) return [random.randint(0,1000) for i in range(n)]results = hit_news_api(\"USA\", 5)st.write(results)" }, { "code": null, "e": 4421, "s": 4397, "text": "And the app looks like:" }, { "code": null, "e": 4610, "s": 4421, "text": "Now every time, I refresh the page, the function hit_news_api gets called again, and that means we will hit our API limits as our number of users increase. So how do we solve this problem?" }, { "code": null, "e": 4703, "s": 4610, "text": "We can use caching. Right. So let us see what happens if we cache the hit_news_api function." }, { "code": null, "e": 4908, "s": 4703, "text": "import streamlit as stimport [email protected] hit_news_api(country, n): st.write(\"Cache Miss for n:\",n) return [random.randint(0,1000) for i in range(n)]results = hit_news_api(\"USA\", 5)st.write(results)" }, { "code": null, "e": 5121, "s": 4908, "text": "The problem now is that our dashboard never calls the news API after hitting it once if the API parameters remain the same. And we see static results for an eternity for the same set of params. What should we do?" }, { "code": null, "e": 5291, "s": 5121, "text": "We can use this hack — Pass a time-dependent dummy parameter to the hit_news_api function call that changes value every five minutes/ten minutes. The code to do this is:" }, { "code": null, "e": 5529, "s": 5291, "text": "Here the truncate_time function helps us to truncate the current datetime to the nearest lowest divisor for that minute. For Example, given dt_time=’2020–03–27 02:32:19.684443' and period = 5 the function returns ‘2020–03–27 02:30:00.0’." }, { "code": null, "e": 5870, "s": 5529, "text": "See how we call the hit_news_api function now with the truncated time. Now, whenever the hit_news_api function is called from the time between dt_time=’2020–03–27 02:30:00.0' and dt_time=’2020–03–27 02:34:59.99999' the parameters to the function call remains the same, and hence we don’t hit the API again and again. Exactly what we wanted!" }, { "code": null, "e": 6105, "s": 5870, "text": "This is all well and good, but can you spot a problem with this approach? The cache size is going to grow over time. And that means we need to clear the cache at fixed intervals manually. How do we automate the cache clearing process?" }, { "code": null, "e": 6230, "s": 6105, "text": "It is a pretty simple hack. We can use this below code at the top of our code to clear the whole cache at a period of 1 day." }, { "code": null, "e": 6419, "s": 6230, "text": "from streamlit import cachingfrom datetime import datedef cache_clear_dt(dummy): clear_dt = date.today() return clear_dtif cache_clear_dt(\"dummy\")<date.today(): caching.clear_cache()" }, { "code": null, "e": 6481, "s": 6419, "text": "This is how the whole app looks with all the above functions." }, { "code": null, "e": 6576, "s": 6481, "text": "Streamlit has democratized the whole process to create apps, and I couldn’t recommend it more." }, { "code": null, "e": 6895, "s": 6576, "text": "Yet, there are some things for which we need to go about in a roundabout way. And there are still a lot of things that I will love to have in this awesome platform. I have been in talks with the Streamlit team over the new functionality that they are going to introduce, and I will try to keep you updated on the same." }, { "code": null, "e": 6964, "s": 6895, "text": "You can find the full code for the final app here at my Github repo." }, { "code": null, "e": 7265, "s": 6964, "text": "If you want to learn about the best strategies for creating Visualizations, I would like to call out an excellent course about Data Visualization and applied plotting from the University of Michigan, which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out." }, { "code": null, "e": 7529, "s": 7265, "text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
Grunt - Sample File
In this chapter, let us create a simple Grunt file using the following plugins − grunt-contrib-uglify grunt-contrib-concat grunt-contrib-jshint grunt-contrib-watch Install all the above plugins and follow the steps given below to create a simple Gruntfile.js − Step 1 − You need to create a wrapper function, which encapsulates the configurations for your Grunt. module.exports = function(grunt) {}; Step 2 − Initialize your configuration object as shown below − grunt.initConfig({}); Step 3 − Next, read the project settings from the package.json file into the pkg property. It enables us to refer to the properties values within yourpackage.json file. pkg: grunt.file.readJSON('package.json') Step 4 − Next, you can define configurations for tasks. Let us create our first task concat to concatenate all the files that are present in the src/ folder and store the concatenated .js file under the dist/ folder. concat: { options: { // define a string to insert between files in the concatenated output separator: ';' }, dist: { // files needs to be concatenated src: ['src/**/*.js'], // location of the concatenated output JS file dest: 'dist/<%= pkg.name %>.js' } } Step 5 − Now, let us create another task called uglify to minify our JavaScript. uglify: { options: { // banner will be inserted at the top of the output which displays the date and time banner: '/*! <%= pkg.name %> <%= grunt.template.today() %> */\n' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } } The above task creates a file within the dist/ folder which contains the minified .js files. The <%= concat.dist.dest %> will instruct uglify to minify the file that concat task generates. Step 6 − Let us configure JSHint plugin by creating jshint task. jshint: { // define the files to lint files: ['Gruntfile.js', 'src/**/*.js'], // configure JSHint options: { // more options here if you want to override JSHint defaults globals: { jQuery: true, } } } The above jshint task accepts an array of files and then an object of options. The above task will look for any coding violation in Gruntfile.js and src/**/*.js files. Step 7 − Next, we have the watch task which looks for changes in any of the specified files and runs the tasks you specify. watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] } Step 8 − Next, we have to load Grunt plugins which have all been installed via _npm. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); Step 9 − Finally, we have to define the default task. grunt.registerTask('default', ['jshint', 'concat', 'uglify']); The default task can be run by just typing the grunt command on command line. Here is your complete Gruntfile.js − module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist: { src: ['src/**/*.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today() %> */\n' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { // define the files to lint files: ['Gruntfile.js', 'src/**/*.js'], // configure JSHint options: { // more options here if you want to override JSHint defaults globals: { jQuery: true, } } }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['jshint', 'concat', 'uglify']); }; Print Add Notes Bookmark this page
[ { "code": null, "e": 1796, "s": 1715, "text": "In this chapter, let us create a simple Grunt file using the following plugins −" }, { "code": null, "e": 1817, "s": 1796, "text": "grunt-contrib-uglify" }, { "code": null, "e": 1838, "s": 1817, "text": "grunt-contrib-concat" }, { "code": null, "e": 1859, "s": 1838, "text": "grunt-contrib-jshint" }, { "code": null, "e": 1879, "s": 1859, "text": "grunt-contrib-watch" }, { "code": null, "e": 1976, "s": 1879, "text": "Install all the above plugins and follow the steps given below to create a simple Gruntfile.js −" }, { "code": null, "e": 2078, "s": 1976, "text": "Step 1 − You need to create a wrapper function, which encapsulates the configurations for your Grunt." }, { "code": null, "e": 2115, "s": 2078, "text": "module.exports = function(grunt) {};" }, { "code": null, "e": 2178, "s": 2115, "text": "Step 2 − Initialize your configuration object as shown below −" }, { "code": null, "e": 2200, "s": 2178, "text": "grunt.initConfig({});" }, { "code": null, "e": 2369, "s": 2200, "text": "Step 3 − Next, read the project settings from the package.json file into the pkg property. It enables us to refer to the properties values within yourpackage.json file." }, { "code": null, "e": 2410, "s": 2369, "text": "pkg: grunt.file.readJSON('package.json')" }, { "code": null, "e": 2627, "s": 2410, "text": "Step 4 − Next, you can define configurations for tasks. Let us create our first task concat to concatenate all the files that are present in the src/ folder and store the concatenated .js file under the dist/ folder." }, { "code": null, "e": 2931, "s": 2627, "text": "concat: {\n options: {\n // define a string to insert between files in the concatenated output\n separator: ';'\n },\n dist: {\n // files needs to be concatenated\n src: ['src/**/*.js'],\n // location of the concatenated output JS file\n dest: 'dist/<%= pkg.name %>.js'\n }\n}" }, { "code": null, "e": 3012, "s": 2931, "text": "Step 5 − Now, let us create another task called uglify to minify our JavaScript." }, { "code": null, "e": 3313, "s": 3012, "text": "uglify: {\n options: {\n // banner will be inserted at the top of the output which displays the date and time\n banner: '/*! <%= pkg.name %> <%= grunt.template.today() %> */\\n'\n },\n dist: {\n files: {\n 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']\n }\n }\n}" }, { "code": null, "e": 3502, "s": 3313, "text": "The above task creates a file within the dist/ folder which contains the minified .js files. The <%= concat.dist.dest %> will instruct uglify to minify the file that concat task generates." }, { "code": null, "e": 3567, "s": 3502, "text": "Step 6 − Let us configure JSHint plugin by creating jshint task." }, { "code": null, "e": 3810, "s": 3567, "text": "jshint: {\n // define the files to lint\n files: ['Gruntfile.js', 'src/**/*.js'],\n // configure JSHint\n options: {\n // more options here if you want to override JSHint defaults\n globals: {\n jQuery: true,\n }\n }\n}" }, { "code": null, "e": 3978, "s": 3810, "text": "The above jshint task accepts an array of files and then an object of options. The above task will look for any coding violation in Gruntfile.js and src/**/*.js files." }, { "code": null, "e": 4102, "s": 3978, "text": "Step 7 − Next, we have the watch task which looks for changes in any of the specified files and runs the tasks you specify." }, { "code": null, "e": 4169, "s": 4102, "text": "watch: {\n files: ['<%= jshint.files %>'],\n tasks: ['jshint']\n}" }, { "code": null, "e": 4254, "s": 4169, "text": "Step 8 − Next, we have to load Grunt plugins which have all been installed via _npm." }, { "code": null, "e": 4432, "s": 4254, "text": "grunt.loadNpmTasks('grunt-contrib-uglify');\n\ngrunt.loadNpmTasks('grunt-contrib-jshint');\n\ngrunt.loadNpmTasks('grunt-contrib-watch');\n\ngrunt.loadNpmTasks('grunt-contrib-concat');" }, { "code": null, "e": 4486, "s": 4432, "text": "Step 9 − Finally, we have to define the default task." }, { "code": null, "e": 4549, "s": 4486, "text": "grunt.registerTask('default', ['jshint', 'concat', 'uglify']);" }, { "code": null, "e": 4627, "s": 4549, "text": "The default task can be run by just typing the grunt command on command line." }, { "code": null, "e": 4664, "s": 4627, "text": "Here is your complete Gruntfile.js −" }, { "code": null, "e": 5898, "s": 4664, "text": "module.exports = function(grunt) {\n\n grunt.initConfig({\n pkg: grunt.file.readJSON('package.json'),\n concat: {\n options: {\n separator: ';'\n },\n dist: {\n src: ['src/**/*.js'],\n dest: 'dist/<%= pkg.name %>.js'\n }\n },\n uglify: {\n options: {\n banner: '/*! <%= pkg.name %> <%= grunt.template.today() %> */\\n'\n },\n dist: {\n files: {\n 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']\n }\n }\n },\n jshint: {\n // define the files to lint\n files: ['Gruntfile.js', 'src/**/*.js'],\n // configure JSHint\n options: {\n // more options here if you want to override JSHint defaults\n globals: {\n jQuery: true,\n }\n }\n },\n watch: {\n files: ['<%= jshint.files %>'],\n tasks: ['jshint']\n }\n });\n\n grunt.loadNpmTasks('grunt-contrib-uglify');\n grunt.loadNpmTasks('grunt-contrib-jshint');\n grunt.loadNpmTasks('grunt-contrib-watch');\n grunt.loadNpmTasks('grunt-contrib-concat');\n\n grunt.registerTask('default', ['jshint', 'concat', 'uglify']);\n\n};" }, { "code": null, "e": 5905, "s": 5898, "text": " Print" }, { "code": null, "e": 5916, "s": 5905, "text": " Add Notes" } ]
Teradata - User Management
This chapter discussed the various strategies of user management in Teradata. A user is created using CREATE USER command. In Teradata, a user is also similar to a database. They both can be assigned space and contain database objects except that the user is assigned a password. Following is the syntax for CREATE USER. CREATE USER username AS [PERMANENT|PERM] = n BYTES PASSWORD = password TEMPORARY = n BYTES SPOOL = n BYTES; While creating a user, the values for user name, Permanent space and Password is mandatory. Other fields are optional. Following is an example to create the user TD01. CREATE USER TD01 AS PERMANENT = 1000000 BYTES PASSWORD = ABC$124 TEMPORARY = 1000000 BYTES SPOOL = 1000000 BYTES; While creating a new user, the user may be assigned to an account. ACCOUNT option in CREATE USER is used to assign the account. A user may be assigned to multiple accounts. Following is the syntax for CREATE USER with account option. CREATE USER username PERM = n BYTES PASSWORD = password ACCOUNT = accountid The following example creates the user TD02 and assigns the account as IT and Admin. CREATE USER TD02 AS PERMANENT = 1000000 BYTES PASSWORD = abc$123 TEMPORARY = 1000000 BYTES SPOOL = 1000000 BYTES ACCOUNT = (‘IT’,’Admin’); The user can specify the account id while logging into Teradata system or after being logged into the system using SET SESSION command. .LOGON username, passowrd,accountid OR SET SESSION ACCOUNT = accountid GRANT command is used to assign one or more privileges on the database objects to the user or database. Following is the syntax of the GRANT command. GRANT privileges ON objectname TO username; Privileges can be INSERT, SELECT, UPDATE, REFERENCES. Following is an example of GRANT statement. GRANT SELECT,INSERT,UPDATE ON Employee TO TD01; REVOKE command removes the privileges from the users or databases. The REVOKE command can only remove explicit privileges. Following is the basic syntax for REVOKE command. REVOKE [ALL|privileges] ON objectname FROM username; Following is an example of REVOKE command. REVOKE INSERT,SELECT ON Employee FROM TD01; Print Add Notes Bookmark this page
[ { "code": null, "e": 2708, "s": 2630, "text": "This chapter discussed the various strategies of user management in Teradata." }, { "code": null, "e": 2910, "s": 2708, "text": "A user is created using CREATE USER command. In Teradata, a user is also similar to a database. They both can be assigned space and contain database objects except that the user is assigned a password." }, { "code": null, "e": 2951, "s": 2910, "text": "Following is the syntax for CREATE USER." }, { "code": null, "e": 3066, "s": 2951, "text": "CREATE USER username \nAS \n[PERMANENT|PERM] = n BYTES \nPASSWORD = password \nTEMPORARY = n BYTES \nSPOOL = n BYTES;\n" }, { "code": null, "e": 3185, "s": 3066, "text": "While creating a user, the values for user name, Permanent space and Password is mandatory. Other fields are optional." }, { "code": null, "e": 3234, "s": 3185, "text": "Following is an example to create the user TD01." }, { "code": null, "e": 3354, "s": 3234, "text": "CREATE USER TD01 \nAS \nPERMANENT = 1000000 BYTES \nPASSWORD = ABC$124 \nTEMPORARY = 1000000 BYTES \nSPOOL = 1000000 BYTES;" }, { "code": null, "e": 3527, "s": 3354, "text": "While creating a new user, the user may be assigned to an account. ACCOUNT option in CREATE USER is used to assign the account. A user may be assigned to multiple accounts." }, { "code": null, "e": 3588, "s": 3527, "text": "Following is the syntax for CREATE USER with account option." }, { "code": null, "e": 3668, "s": 3588, "text": "CREATE USER username \nPERM = n BYTES \nPASSWORD = password \nACCOUNT = accountid\n" }, { "code": null, "e": 3753, "s": 3668, "text": "The following example creates the user TD02 and assigns the account as IT and Admin." }, { "code": null, "e": 3899, "s": 3753, "text": "CREATE USER TD02 \nAS \nPERMANENT = 1000000 BYTES \nPASSWORD = abc$123 \nTEMPORARY = 1000000 BYTES \nSPOOL = 1000000 BYTES \nACCOUNT = (‘IT’,’Admin’);" }, { "code": null, "e": 4035, "s": 3899, "text": "The user can specify the account id while logging into Teradata system or after being logged into the system using SET SESSION command." }, { "code": null, "e": 4110, "s": 4035, "text": ".LOGON username, passowrd,accountid \nOR \nSET SESSION ACCOUNT = accountid \n" }, { "code": null, "e": 4214, "s": 4110, "text": "GRANT command is used to assign one or more privileges on the database objects to the user or database." }, { "code": null, "e": 4260, "s": 4214, "text": "Following is the syntax of the GRANT command." }, { "code": null, "e": 4305, "s": 4260, "text": "GRANT privileges ON objectname TO username;\n" }, { "code": null, "e": 4359, "s": 4305, "text": "Privileges can be INSERT, SELECT, UPDATE, REFERENCES." }, { "code": null, "e": 4403, "s": 4359, "text": "Following is an example of GRANT statement." }, { "code": null, "e": 4451, "s": 4403, "text": "GRANT SELECT,INSERT,UPDATE ON Employee TO TD01;" }, { "code": null, "e": 4574, "s": 4451, "text": "REVOKE command removes the privileges from the users or databases. The REVOKE command can only remove explicit privileges." }, { "code": null, "e": 4624, "s": 4574, "text": "Following is the basic syntax for REVOKE command." }, { "code": null, "e": 4678, "s": 4624, "text": "REVOKE [ALL|privileges] ON objectname FROM username;\n" }, { "code": null, "e": 4721, "s": 4678, "text": "Following is an example of REVOKE command." }, { "code": null, "e": 4765, "s": 4721, "text": "REVOKE INSERT,SELECT ON Employee FROM TD01;" }, { "code": null, "e": 4772, "s": 4765, "text": " Print" }, { "code": null, "e": 4783, "s": 4772, "text": " Add Notes" } ]
Finding the nth element of the lucas number sequence in JavaScript
Lucas numbers are numbers in a sequence defined like this − L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) We are required to write a JavaScript function that takes in a number n and return the nth lucas number. Following is the code − Live Demo const num = 21; const lucas = (num = 1) => { if (num === 0) return 2; if (num === 1) return 1; return lucas(num - 1) + lucas(num - 2); }; console.log(lucas(num)); Following is the console output − 24476
[ { "code": null, "e": 1122, "s": 1062, "text": "Lucas numbers are numbers in a sequence defined like this −" }, { "code": null, "e": 1163, "s": 1122, "text": "L(0) = 2\nL(1) = 1\nL(n) = L(n-1) + L(n-2)" }, { "code": null, "e": 1268, "s": 1163, "text": "We are required to write a JavaScript function that takes in a number n and return the nth lucas number." }, { "code": null, "e": 1292, "s": 1268, "text": "Following is the code −" }, { "code": null, "e": 1303, "s": 1292, "text": " Live Demo" }, { "code": null, "e": 1493, "s": 1303, "text": "const num = 21;\nconst lucas = (num = 1) => {\n if (num === 0)\n return 2;\n if (num === 1)\n return 1;\n return lucas(num - 1) +\n lucas(num - 2);\n};\nconsole.log(lucas(num));" }, { "code": null, "e": 1527, "s": 1493, "text": "Following is the console output −" }, { "code": null, "e": 1533, "s": 1527, "text": "24476" } ]
What are Chrome Flags or Experiments? - GeeksforGeeks
31 Mar, 2021 Chrome Flags also called Experiments are the experimental features that are provided by the Chrome browser but are not a part of the default chrome experience. Anyone can use them by following some simple steps and transform their chrome browsing experience. Some flags eventually become a part of the default public release once they are tried and tested completely. For example, the Tab Groups feature was first introduced as a Chrome flag before it was rolled out as a default feature. Chrome flags Warning Flags are experimental features and are not always stable. Using them might make the browser act weird or crash as they haven’t been tested extensively. Flags are not tested thoroughly for security as well. So you might want to use a different browser or turn them off when doing online banking or other sensitive activities. To enable a flag, the browser needs to be relaunched. Once the browser is relaunched, all the windows and tabs will reopen while the incognito windows will be lost. Proceed with Caution WARNING: EXPERIMENTAL FEATURES AHEAD! By enabling these features, you could lose browser data or compromise your security or privacy. Enabled features apply to all users of this browser. Chrome flags can be accessed on this URL on any chrome browser be it Windows, Chromebook, MacOS, iPhones, or Android. chrome://flags/ This will take you to the home page of Chrome Experiments where all the chrome flags are available along with their status (Default/Enabled/Disabled). Let us consider the chrome flag Enable Tab Search. There are two ways to access it: Search with the name in the search box, or Search for a flag Go to the flag tag. For e.g. chrome://flags/#enable-tab-search URL for a flag Then just enable it and relaunch the browser. Enable a flag You can now see the Search Tabs icon on the right side of the title bar. With just a few clicks you can enable a very useful feature. Individual flags can be reset similarly by changing their state to Default or Disabled. The Reset all button will bring everything back to the default state. In either case, chrome needs to be relaunched to apply the changes. Here is a link to a list of some chrome flags mentioned on the Google Chrome Github page. How To TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Align Text in HTML? How to Install FFmpeg on Windows? Java Tutorial How to Install Jupyter Notebook on MacOS? How to Install Python Pandas on MacOS? Running Python script on GPU. Setting up the environment in Java How to Run a Python Script using Docker? How to Force Dark Mode on Web Contents in Chrome 'dd' command in Linux
[ { "code": null, "e": 25037, "s": 25006, "text": " \n31 Mar, 2021\n" }, { "code": null, "e": 25526, "s": 25037, "text": "Chrome Flags also called Experiments are the experimental features that are provided by the Chrome browser but are not a part of the default chrome experience. Anyone can use them by following some simple steps and transform their chrome browsing experience. Some flags eventually become a part of the default public release once they are tried and tested completely. For example, the Tab Groups feature was first introduced as a Chrome flag before it was rolled out as a default feature." }, { "code": null, "e": 25547, "s": 25526, "text": "Chrome flags Warning" }, { "code": null, "e": 25700, "s": 25547, "text": "Flags are experimental features and are not always stable. Using them might make the browser act weird or crash as they haven’t been tested extensively." }, { "code": null, "e": 25873, "s": 25700, "text": "Flags are not tested thoroughly for security as well. So you might want to use a different browser or turn them off when doing online banking or other sensitive activities." }, { "code": null, "e": 26038, "s": 25873, "text": "To enable a flag, the browser needs to be relaunched. Once the browser is relaunched, all the windows and tabs will reopen while the incognito windows will be lost." }, { "code": null, "e": 26060, "s": 26038, "text": "Proceed with Caution " }, { "code": null, "e": 26249, "s": 26060, "text": "WARNING: EXPERIMENTAL FEATURES AHEAD! \nBy enabling these features, you could lose browser data or compromise your security or privacy. \nEnabled features apply to all users of this browser." }, { "code": null, "e": 26367, "s": 26249, "text": "Chrome flags can be accessed on this URL on any chrome browser be it Windows, Chromebook, MacOS, iPhones, or Android." }, { "code": null, "e": 26383, "s": 26367, "text": "chrome://flags/" }, { "code": null, "e": 26534, "s": 26383, "text": "This will take you to the home page of Chrome Experiments where all the chrome flags are available along with their status (Default/Enabled/Disabled)." }, { "code": null, "e": 26586, "s": 26534, "text": "Let us consider the chrome flag Enable Tab Search. " }, { "code": null, "e": 26619, "s": 26586, "text": "There are two ways to access it:" }, { "code": null, "e": 26663, "s": 26619, "text": "Search with the name in the search box, or " }, { "code": null, "e": 26681, "s": 26663, "text": "Search for a flag" }, { "code": null, "e": 26745, "s": 26681, "text": "Go to the flag tag. For e.g. chrome://flags/#enable-tab-search " }, { "code": null, "e": 26760, "s": 26745, "text": "URL for a flag" }, { "code": null, "e": 26807, "s": 26760, "text": "Then just enable it and relaunch the browser. " }, { "code": null, "e": 26821, "s": 26807, "text": "Enable a flag" }, { "code": null, "e": 26955, "s": 26821, "text": "You can now see the Search Tabs icon on the right side of the title bar. With just a few clicks you can enable a very useful feature." }, { "code": null, "e": 27181, "s": 26955, "text": "Individual flags can be reset similarly by changing their state to Default or Disabled. The Reset all button will bring everything back to the default state. In either case, chrome needs to be relaunched to apply the changes." }, { "code": null, "e": 27271, "s": 27181, "text": "Here is a link to a list of some chrome flags mentioned on the Google Chrome Github page." }, { "code": null, "e": 27280, "s": 27271, "text": "\nHow To\n" }, { "code": null, "e": 27291, "s": 27280, "text": "\nTechTips\n" }, { "code": null, "e": 27496, "s": 27291, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27523, "s": 27496, "text": "How to Align Text in HTML?" }, { "code": null, "e": 27557, "s": 27523, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27571, "s": 27557, "text": "Java Tutorial" }, { "code": null, "e": 27613, "s": 27571, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27652, "s": 27613, "text": "How to Install Python Pandas on MacOS?" }, { "code": null, "e": 27682, "s": 27652, "text": "Running Python script on GPU." }, { "code": null, "e": 27717, "s": 27682, "text": "Setting up the environment in Java" }, { "code": null, "e": 27758, "s": 27717, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 27807, "s": 27758, "text": "How to Force Dark Mode on Web Contents in Chrome" } ]
Radix sort in Javascript?
The radix sort algorithm distributes integers into buckets based on a number's significant digit or value (the radix). The radix is based on the number system of the values of the arrays. Let us look at how it can be implemented − function radixSort(arr) { // Find the max number and multiply it by 10 to get a number // with no. of digits of max + 1 const maxNum = Math.max(...arr) * 10; let divisor = 10; while (divisor < maxNum) { // Create bucket arrays for each of 0-9 let buckets = [...Array(10)].map(() => []); // For each number, get the current significant digit and put it in the respective bucket for (let num of arr) { buckets[Math.floor((num % divisor) / (divisor / 10))].push(num); } // Reconstruct the array by concatinating all sub arrays arr = [].concat.apply([], buckets); // Move to the next significant digit divisor *= 10; } return arr; } console.log(radixSort([5,3,88,235,65,23,4632,234])) [ 3, 5, 23, 65, 88, 234, 235, 4632 ]
[ { "code": null, "e": 1293, "s": 1062, "text": "The radix sort algorithm distributes integers into buckets based on a number's significant digit or value (the radix). The radix is based on the number system of the values of the arrays. Let us look at how it can be implemented −" }, { "code": null, "e": 2058, "s": 1293, "text": "function radixSort(arr) {\n // Find the max number and multiply it by 10 to get a number\n // with no. of digits of max + 1\n const maxNum = Math.max(...arr) * 10;\n let divisor = 10;\n while (divisor < maxNum) {\n // Create bucket arrays for each of 0-9\n let buckets = [...Array(10)].map(() => []);\n // For each number, get the current significant digit and put it in the respective bucket\n for (let num of arr) {\n buckets[Math.floor((num % divisor) / (divisor / 10))].push(num);\n }\n // Reconstruct the array by concatinating all sub arrays\n arr = [].concat.apply([], buckets);\n // Move to the next significant digit\n divisor *= 10;\n }\n return arr;\n}\nconsole.log(radixSort([5,3,88,235,65,23,4632,234]))" }, { "code": null, "e": 2095, "s": 2058, "text": "[ 3, 5, 23, 65, 88, 234, 235, 4632 ]" } ]
Testing Broken Authentication
When authentication functions related to the application are not implemented correctly, it allows hackers to compromise passwords or session ID's or to exploit other implementation flaws using other users credentials. Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram. An e-commerce application supports URL rewriting, putting session IDs in the URL − http://example.com/sale/saleitems/jsessionid=2P0OC2JSNDLPSKHCJUN2JV/?item=laptop An authenticated user of the site forwards the URL to their friends to know about the discounted sales. He e-mails the above link without knowing that the user is also giving away the session IDs. When his friends use the link, they use his session and credit card. Step 1 − Login to Webgoat and navigate to 'Session Management Flaws' Section. Let us bypass the authetication by spoofing the cookie. Below is the snapshot of the scenario. Step 2 − When we login using the credentials webgoat/webgoat, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432ubphcfx upon successful authentication. Step 3 − When we login using the credentials aspect/aspect, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432udfqtb upon successful authentication. Step 4 − Now we need to analyze the AuthCookie Patterns. The first half '65432' is common for both authentications. Hence we are now interested in analyzing the last part of the authcookie values such as - ubphcfx for webgoat user and udfqtb for aspect user respectively. Step 5 − If we take a deep look at the AuthCookie values, the last part is having the same length as that of user name. Hence it is evident that the username is used with some encryption method. Upon trial and errors/brute force mechanisms, we find that after reversing the user name, webgoat; we end up with taogbew and then the before alphabet character is what being used as AuthCookie. i.e ubphcfx. Step 6 − If we pass this cookie value and let us see what happens. Upon authenticating as user webgoat, change the AuthCookie value to mock the user Alice by finding the AuthCookie for the same by performing step#4 and step#5. Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard. Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard. Developers should ensure that they avoid XSS flaws that can be used to steal session IDs. Developers should ensure that they avoid XSS flaws that can be used to steal session IDs. 36 Lectures 5 hours Sharad Kumar 26 Lectures 2.5 hours Harshit Srivastava 47 Lectures 2 hours Dhabaleshwar Das 14 Lectures 1.5 hours Harshit Srivastava 38 Lectures 3 hours Harshit Srivastava 32 Lectures 3 hours Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2658, "s": 2440, "text": "When authentication functions related to the application are not implemented correctly, it allows hackers to compromise passwords or session ID's or to exploit other implementation flaws using other users credentials." }, { "code": null, "e": 2810, "s": 2658, "text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram." }, { "code": null, "e": 2976, "s": 2810, "text": "An e-commerce application supports URL rewriting, putting session IDs in the URL −\n\nhttp://example.com/sale/saleitems/jsessionid=2P0OC2JSNDLPSKHCJUN2JV/?item=laptop\n" }, { "code": null, "e": 3242, "s": 2976, "text": "An authenticated user of the site forwards the URL to their friends to know about the discounted sales. He e-mails the above link without knowing that the user is also giving away the session IDs. When his friends use the link, they use his session and credit card." }, { "code": null, "e": 3415, "s": 3242, "text": "Step 1 − Login to Webgoat and navigate to 'Session Management Flaws' Section. Let us bypass the authetication by spoofing the cookie. Below is the snapshot of the scenario." }, { "code": null, "e": 3626, "s": 3415, "text": "Step 2 − When we login using the credentials webgoat/webgoat, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432ubphcfx upon successful authentication." }, { "code": null, "e": 3834, "s": 3626, "text": "Step 3 − When we login using the credentials aspect/aspect, we find from Burp Suite that the JSESSION ID is C8F3177CCAFF380441ABF71090748F2E while the AuthCookie = 65432udfqtb upon successful authentication." }, { "code": null, "e": 4106, "s": 3834, "text": "Step 4 − Now we need to analyze the AuthCookie Patterns. The first half '65432' is common for both authentications. Hence we are now interested in analyzing the last part of the authcookie values such as - ubphcfx for webgoat user and udfqtb for aspect user respectively." }, { "code": null, "e": 4509, "s": 4106, "text": "Step 5 − If we take a deep look at the AuthCookie values, the last part is having the same length as that of user name. Hence it is evident that the username is used with some encryption method. Upon trial and errors/brute force mechanisms, we find that after reversing the user name, webgoat; we end up with taogbew and then the before alphabet character is what being used as AuthCookie. i.e ubphcfx." }, { "code": null, "e": 4736, "s": 4509, "text": "Step 6 − If we pass this cookie value and let us see what happens. Upon authenticating as user webgoat, change the AuthCookie value to mock the user Alice by finding the AuthCookie for the same by performing step#4 and step#5." }, { "code": null, "e": 4941, "s": 4736, "text": "Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard." }, { "code": null, "e": 5146, "s": 4941, "text": "Develop a strong authentication and session management controls such that it meets all the authentication and session management requirements defined in OWASP's Application Security Verification Standard." }, { "code": null, "e": 5236, "s": 5146, "text": "Developers should ensure that they avoid XSS flaws that can be used to steal session IDs." }, { "code": null, "e": 5326, "s": 5236, "text": "Developers should ensure that they avoid XSS flaws that can be used to steal session IDs." }, { "code": null, "e": 5359, "s": 5326, "text": "\n 36 Lectures \n 5 hours \n" }, { "code": null, "e": 5373, "s": 5359, "text": " Sharad Kumar" }, { "code": null, "e": 5408, "s": 5373, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5428, "s": 5408, "text": " Harshit Srivastava" }, { "code": null, "e": 5461, "s": 5428, "text": "\n 47 Lectures \n 2 hours \n" }, { "code": null, "e": 5479, "s": 5461, "text": " Dhabaleshwar Das" }, { "code": null, "e": 5514, "s": 5479, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5534, "s": 5514, "text": " Harshit Srivastava" }, { "code": null, "e": 5567, "s": 5534, "text": "\n 38 Lectures \n 3 hours \n" }, { "code": null, "e": 5587, "s": 5567, "text": " Harshit Srivastava" }, { "code": null, "e": 5620, "s": 5587, "text": "\n 32 Lectures \n 3 hours \n" }, { "code": null, "e": 5640, "s": 5620, "text": " Harshit Srivastava" }, { "code": null, "e": 5647, "s": 5640, "text": " Print" }, { "code": null, "e": 5658, "s": 5647, "text": " Add Notes" } ]
Decoding Ethereum smart contract data | by Yifei Huang | Towards Data Science
In the last two posts of this series, I described what crypto data is and why it is a unique and compelling opportunity. I strongly encourage reading these before continuing if you have not already, as they provide important context for understanding this post. In this post, we will get our hands dirty and discuss the technical details of decoding Ethereum smart contract data into human readable formats. This is a necessary first step towards a deeper understanding of the underlying user activity. We will focus on Ethereum as the primary example, but many of the concepts we discuss here will apply more broadly to all EVM compatible chains and smart contracts e.g. Polygon, BSC, Optimism, etc. As we have discussed in previous posts, a smart contract transaction is analogous to a backend API call in a smart contract powered web3 application. The details of each smart contract transaction and resulting application state changes are recorded in data elements known as transactions, calls, and logs. The transaction data element represents the function call initiated by a user (or EOA to be more precise), the call data elements represent additional function calls initiated within the transaction by the smart contract, and the log data elements represent events that have occurred during the transaction execution. With these data elements, one can very granularly describe the state changes that occurred in the applications and on the blockchain as a result of the transaction. And when analyzed in the aggregate, the collection of all transactions, traces, and logs for a given decentralized web3 application can provide holistic and insightful views of the user bases and their activities in the product. However, doing so is made challenging by the fact that much of the salient details are recorded as hexadecimal encoded strings. See for example, this transaction to swap a pair of tokens using Uniswap on the Ethereum network (This particular record can be obtained by querying the transactions table in Google’s Public Dataset on Ethereum, and also viewable on Etherscan): hash: 0x87a3bc85da972583e22da329aa109ea0db57c54a2eee359b2ed12597f5cb1a64nonce: 449transaction_index: 37from_address: 0x3c02cebb49f6e8f1fc96158099ffa064bbfee38bto_address: 0x7a250d5630b4cf539739df2c5dacb4c659f2488dvalue: 0E-9gas: 228630gas_price: 91754307665input: 0x38ed1739000000000000000000000000000000000000000000000000000000009502f900000000000000000000000000000000000000000000a07e38bf71936cbe39594100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000003c02cebb49f6e8f1fc96158099ffa064bbfee38b00000000000000000000000000000000000000000000000000000000616e11230000000000000000000000000000000000000000000000000000000000000003000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000528b3e98c63ce21c6f680b713918e0f89dfae555receipt_cumulative_gas_used: 2119514receipt_gas_used: 192609receipt_contract_address: Nonereceipt_root: Nonereceipt_status: 1block_timestamp: 2021–10–19 00:00:18block_number: 13444845block_hash: 0xe9ea4fc0ef9a13b1e403e68e3ff94bc94e472132528fe8f07ade422b84a43afcmax_fee_per_gas: Nonemax_priority_fee_per_gas: Nonetransaction_type: Nonereceipt_effective_gas_price: 91754307665 As you might have noticed if you looked at the transaction on Etherscan, it already decodes this raw record and provides great context to help you understand the transaction details. While this is extremely helpful, it is not designed to answer questions that require transformation and aggregation of the data, e.g. how much total value was traded by all Uniswap users, or what is the 3 month retentions of Uniswap users. To answer these questions, we would need to be able to gather all the records, decode them, and work with the relevant details in batch. We will go through how to do that in the rest of this post. If we examine the raw data record, we can see that the transaction was initiated by the EOA, 0x3c02cebb49f6e8f1fc96158099ffa064bbfee38b, to the smart contract address associated with Uniswap v2 router, 0x7a250d5630b4cf539739df2c5dacb4c659f2488d. However, the relevant request details are encoded as a long hexadecimal string in theinput field. Before we get into how to extract human readable data frominput, it will be instructive to talk through its structure. The leading 0x is an indicator that this string is hexadecimal, so it is not relevant to the actual information content. After that, every 2 hex characters represent a byte. The first four bytes, in this case 38ed1739, is the hashed signature of the function being called. The rest of the bytes are hashes of the arguments being passed to the function. This means that the length of the input string can vary depending on the specific function invoked and parameters required. In order to decode this hexadecimal string, we need to reference something called the application binary interface or ABI. This is a json object that contains all the function and event interface definitions (i.e. names and types) for the given smart contract. The ABI functions as a look up for matching the hashed signatures in the transaction data against the human readable interface definition. An example ABI looks something like this ABIs can generally be found on block explorers like Etherscan, alongside the contract source code. Here is the link of the ABI for the Uniswap v2 Router contract. Once we have the ABI handy, we can write to decode the transaction: A few things to note in the example code: This code is designed to be used for batch processing of a large number of transactions. It assumes that the data is already present in local storage (and not fetch live from the blockchain), and is well suited to a distributed processing framework like PySpark.@lru_cache(maxsize=None) — We cache the contract object creation to reduce overhead from repeating the same computation across a large number of transactions. This assumes that the decoding is targeted at a smallish number (on the order of thousands) of distinct smart contracts.It leverages the open-sourced web3 package method decode_function_input for extraction of data based on the templates provided in the ABI. This method, however, returns data that is often not serializable (e.g. byte arrays) and sometimes missing human-readable keys. Therefore, it is very helpful (maybe even necessary) to perform post-extraction processing using the utility method convert_to_hex to convert the data into serializable json objects and attach the human understandable keys where missing. This makes it easier to persist and re-use the decoded data.The same code can be used for decoding trace data elements as well. This is because they are simply internal transactions initiated by a smart contract. This code is designed to be used for batch processing of a large number of transactions. It assumes that the data is already present in local storage (and not fetch live from the blockchain), and is well suited to a distributed processing framework like PySpark. @lru_cache(maxsize=None) — We cache the contract object creation to reduce overhead from repeating the same computation across a large number of transactions. This assumes that the decoding is targeted at a smallish number (on the order of thousands) of distinct smart contracts. It leverages the open-sourced web3 package method decode_function_input for extraction of data based on the templates provided in the ABI. This method, however, returns data that is often not serializable (e.g. byte arrays) and sometimes missing human-readable keys. Therefore, it is very helpful (maybe even necessary) to perform post-extraction processing using the utility method convert_to_hex to convert the data into serializable json objects and attach the human understandable keys where missing. This makes it easier to persist and re-use the decoded data. The same code can be used for decoding trace data elements as well. This is because they are simply internal transactions initiated by a smart contract. Using the code above yields this decoded input data function called: swapExactTokensForTokensarguments: { "amountIn": 2500000000, "amountOutMin": 194024196127819599854524737, "path": [ "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "0x528B3e98c63cE21C6f680b713918E0F89DfaE555" ], "to": "0x3c02cebB49F6e8f1FC96158099fFA064bBfeE38B", "deadline": 1634603299} From this we can much more easily understand that The call is to a method namedswapExactTokensForTokens, and the user is putting in 2,500,000,000 units of the starting token, and expecting to get back at least 194,024,196,127,819,599,854,524,737 units of the target token. These numbers may seem astronomical, but keep in mind that token units are typically denoted in the 1/10^n, where n is something like 18. n is sometimes referred to as the decimal value of the token.The path array describes the tokens being exchanged in this transaction. Each array element is an address of a token contract. The first one is USDC (a stable coin pegged to the dollar), the second one is Wrapped Eth (Ethereum with an ERC20 interface), and the third one is DXO (a deep.space in-game currency).Putting 1 and 2 together, we can deduce that the user request is to swap 2,500 USDC (USDC has a decimal value of 6) for ~194 million DXO (DXO has a decimal value of 18). Since this particular pairwise swap is not directly available, the transaction will be mediated through the intermediary token of WETH. The call is to a method namedswapExactTokensForTokens, and the user is putting in 2,500,000,000 units of the starting token, and expecting to get back at least 194,024,196,127,819,599,854,524,737 units of the target token. These numbers may seem astronomical, but keep in mind that token units are typically denoted in the 1/10^n, where n is something like 18. n is sometimes referred to as the decimal value of the token. The path array describes the tokens being exchanged in this transaction. Each array element is an address of a token contract. The first one is USDC (a stable coin pegged to the dollar), the second one is Wrapped Eth (Ethereum with an ERC20 interface), and the third one is DXO (a deep.space in-game currency). Putting 1 and 2 together, we can deduce that the user request is to swap 2,500 USDC (USDC has a decimal value of 6) for ~194 million DXO (DXO has a decimal value of 18). Since this particular pairwise swap is not directly available, the transaction will be mediated through the intermediary token of WETH. This transaction also emitted 7 events in the process of execution, which can be obtained by querying the logs table in Google’s Public Dataset on Ethereum, and also viewed on Etherscan. The two most salient records that correspond to the swaps requested by the users are: log_index: 47transaction_hash: 0x87a3bc85da972583e22da329aa109ea0db57c54a2eee359b2ed12597f5cb1a64transaction_index: 37address: 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dcdata: 0x000000000000000000000000000000000000000000000000000000009502f90000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000093f8f932b016b1ctopics: ['0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822','0x0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d','0x000000000000000000000000242301fa62f0de9e3842a5fb4c0cdca67e3a2fab']block_timestamp: 2021-10-19 00:00:18block_number: 13444845block_hash: 0xe9ea4fc0ef9a13b1e403e68e3ff94bc94e472132528fe8f07ade422b84a43afc and log_index: 50transaction_hash: 0x87a3bc85da972583e22da329aa109ea0db57c54a2eee359b2ed12597f5cb1a64transaction_index: 37address: 0x242301fa62f0de9e3842a5fb4c0cdca67e3a2fabdata: 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000093f8f932b016b1c000000000000000000000000000000000000000000a137bb41b9113069a51e190000000000000000000000000000000000000000000000000000000000000000topics: ['0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822', '0x0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d', '0x0000000000000000000000003c02cebb49f6e8f1fc96158099ffa064bbfee38b']block_timestamp: 2021-10-19 00:00:18block_number: 13444845block_hash: 0xe9ea4fc0ef9a13b1e403e68e3ff94bc94e472132528fe8f07ade422b84a43afc Again, the relevant details are encoded into hexadecimal string in the topics and data fields. As in the case with transaction input, it is instructive to go through the structure of these data fields. topics is an array where the first element represents the hashed signature of the event interface definition. Any additional elements in the topics array are typically blockchain addresses that are involved in the event, and may or may not exist depending on the specific context. data represents the event parameter values and can vary in length depending on the event definition. As was the case with transactions, we need to reference the contract ABI, in order to translate this into human readable form. The astute reader will notice that the contract addresses in the logs above, 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc and 0x242301fa62f0de9e3842a5fb4c0cdca67e3a2fab are different from the Router v2 contract, 0x7a250d5630b4cf539739df2c5dacb4c659f2488d, which the user EOA initially called. These two addresses correspond to Uniswap v2 pair contracts for the USDC-WETH and DXO-WETH token pairs. These contracts are responsible for holding the liquidity for their respective trading pair and actually making the swap. The Router contract, which the user interacted with initially, functions as a coordinator and initiates internal transactions (traces) to the appropriate pair contracts. Therefore, in order to decode these events, we also need the pair contract ABI. Example code to decode logs is as follows: Similar to the code for transaction decoding, the example code is optimized for batch decoding use cases, and is meant to be used in conjunction with something like PySpark to process a large number of log events. Running the above yields: event emitted: Swaparguments: { "sender": "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", "to": "0x242301FA62f0De9e3842A5Fb4c0CdCa67e3A2Fab", "amount0In": 2500000000, "amount1In": 0, "amount0Out": 0, "amount1Out": 666409132118600476} and event emitted: Swaparguments: { "sender": "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D", "to": "0x3c02cebB49F6e8f1FC96158099fFA064bBfeE38B", "amount0In": 0, "amount1In": 666409132118600476, "amount0Out": 194900241391490294085918233, "amount1Out": 0} We can that these two are indeed swap events that followed the path in the initial request — USDC > WETH > DXO. We can see that the router contract (ending 488D) is the sender in both events, acting as the coordinator. The USDC-WETH pair contract (ending c9dc) swaps 2,500,000,000 units of USDC for 666,409,132,118,600,476 units of WETH, and then transfers the resulting WETH to the DXO-WETH pair contract (ending 2Fab). The DXO-WETH contract then swaps the 666,409,132,118,600,476 units of WETH for 194,900,241,391,490,294,085,918,233 units of DXO and sends it back to the user (EOA ending E38B) as initially requested. As this example hopefully illustrates, the process of decoding is relatively straightforward once you have the tools, but knowing what to decode and how to interpret the resulting data is not. Depending on the specific question you are trying to answer, some functions and events are more relevant than others. For the purpose of analyzing economic activity and user behavior in web3 applications, it will be important to develop an understanding of how the specific smart contracts work, and to identify the key functions and events involved in the metric of interest. This is best done through a combination of actually using the product, examining the data exhaust on Block explorers like Etherscan, and reading the smart contract source code. This is a crucial requisite for developing the right decoding and analysis strategy. I hope this was a useful discussion and I have helped you gain a better sense for how to work with crypto data. In my next post, I will show an example deep dive analysis on Opensea, the largest NFT marketplace. Be sure to hit the email icon to subscribe if you would like to be notified when that posts. Thank you for reading and feel free to reach out if you have questions or comments. Twitter | Linkedin
[ { "code": null, "e": 873, "s": 172, "text": "In the last two posts of this series, I described what crypto data is and why it is a unique and compelling opportunity. I strongly encourage reading these before continuing if you have not already, as they provide important context for understanding this post. In this post, we will get our hands dirty and discuss the technical details of decoding Ethereum smart contract data into human readable formats. This is a necessary first step towards a deeper understanding of the underlying user activity. We will focus on Ethereum as the primary example, but many of the concepts we discuss here will apply more broadly to all EVM compatible chains and smart contracts e.g. Polygon, BSC, Optimism, etc." }, { "code": null, "e": 1498, "s": 873, "text": "As we have discussed in previous posts, a smart contract transaction is analogous to a backend API call in a smart contract powered web3 application. The details of each smart contract transaction and resulting application state changes are recorded in data elements known as transactions, calls, and logs. The transaction data element represents the function call initiated by a user (or EOA to be more precise), the call data elements represent additional function calls initiated within the transaction by the smart contract, and the log data elements represent events that have occurred during the transaction execution." }, { "code": null, "e": 2265, "s": 1498, "text": "With these data elements, one can very granularly describe the state changes that occurred in the applications and on the blockchain as a result of the transaction. And when analyzed in the aggregate, the collection of all transactions, traces, and logs for a given decentralized web3 application can provide holistic and insightful views of the user bases and their activities in the product. However, doing so is made challenging by the fact that much of the salient details are recorded as hexadecimal encoded strings. See for example, this transaction to swap a pair of tokens using Uniswap on the Ethereum network (This particular record can be obtained by querying the transactions table in Google’s Public Dataset on Ethereum, and also viewable on Etherscan):" }, { "code": null, "e": 3490, "s": 2265, "text": "hash: 0x87a3bc85da972583e22da329aa109ea0db57c54a2eee359b2ed12597f5cb1a64nonce: 449transaction_index: 37from_address: 0x3c02cebb49f6e8f1fc96158099ffa064bbfee38bto_address: 0x7a250d5630b4cf539739df2c5dacb4c659f2488dvalue: 0E-9gas: 228630gas_price: 91754307665input: 0x38ed1739000000000000000000000000000000000000000000000000000000009502f900000000000000000000000000000000000000000000a07e38bf71936cbe39594100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000003c02cebb49f6e8f1fc96158099ffa064bbfee38b00000000000000000000000000000000000000000000000000000000616e11230000000000000000000000000000000000000000000000000000000000000003000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000528b3e98c63ce21c6f680b713918e0f89dfae555receipt_cumulative_gas_used: 2119514receipt_gas_used: 192609receipt_contract_address: Nonereceipt_root: Nonereceipt_status: 1block_timestamp: 2021–10–19 00:00:18block_number: 13444845block_hash: 0xe9ea4fc0ef9a13b1e403e68e3ff94bc94e472132528fe8f07ade422b84a43afcmax_fee_per_gas: Nonemax_priority_fee_per_gas: Nonetransaction_type: Nonereceipt_effective_gas_price: 91754307665" }, { "code": null, "e": 4110, "s": 3490, "text": "As you might have noticed if you looked at the transaction on Etherscan, it already decodes this raw record and provides great context to help you understand the transaction details. While this is extremely helpful, it is not designed to answer questions that require transformation and aggregation of the data, e.g. how much total value was traded by all Uniswap users, or what is the 3 month retentions of Uniswap users. To answer these questions, we would need to be able to gather all the records, decode them, and work with the relevant details in batch. We will go through how to do that in the rest of this post." }, { "code": null, "e": 4454, "s": 4110, "text": "If we examine the raw data record, we can see that the transaction was initiated by the EOA, 0x3c02cebb49f6e8f1fc96158099ffa064bbfee38b, to the smart contract address associated with Uniswap v2 router, 0x7a250d5630b4cf539739df2c5dacb4c659f2488d. However, the relevant request details are encoded as a long hexadecimal string in theinput field." }, { "code": null, "e": 5050, "s": 4454, "text": "Before we get into how to extract human readable data frominput, it will be instructive to talk through its structure. The leading 0x is an indicator that this string is hexadecimal, so it is not relevant to the actual information content. After that, every 2 hex characters represent a byte. The first four bytes, in this case 38ed1739, is the hashed signature of the function being called. The rest of the bytes are hashes of the arguments being passed to the function. This means that the length of the input string can vary depending on the specific function invoked and parameters required." }, { "code": null, "e": 5491, "s": 5050, "text": "In order to decode this hexadecimal string, we need to reference something called the application binary interface or ABI. This is a json object that contains all the function and event interface definitions (i.e. names and types) for the given smart contract. The ABI functions as a look up for matching the hashed signatures in the transaction data against the human readable interface definition. An example ABI looks something like this" }, { "code": null, "e": 5654, "s": 5491, "text": "ABIs can generally be found on block explorers like Etherscan, alongside the contract source code. Here is the link of the ABI for the Uniswap v2 Router contract." }, { "code": null, "e": 5722, "s": 5654, "text": "Once we have the ABI handy, we can write to decode the transaction:" }, { "code": null, "e": 5764, "s": 5722, "text": "A few things to note in the example code:" }, { "code": null, "e": 7023, "s": 5764, "text": "This code is designed to be used for batch processing of a large number of transactions. It assumes that the data is already present in local storage (and not fetch live from the blockchain), and is well suited to a distributed processing framework like PySpark.@lru_cache(maxsize=None) — We cache the contract object creation to reduce overhead from repeating the same computation across a large number of transactions. This assumes that the decoding is targeted at a smallish number (on the order of thousands) of distinct smart contracts.It leverages the open-sourced web3 package method decode_function_input for extraction of data based on the templates provided in the ABI. This method, however, returns data that is often not serializable (e.g. byte arrays) and sometimes missing human-readable keys. Therefore, it is very helpful (maybe even necessary) to perform post-extraction processing using the utility method convert_to_hex to convert the data into serializable json objects and attach the human understandable keys where missing. This makes it easier to persist and re-use the decoded data.The same code can be used for decoding trace data elements as well. This is because they are simply internal transactions initiated by a smart contract." }, { "code": null, "e": 7286, "s": 7023, "text": "This code is designed to be used for batch processing of a large number of transactions. It assumes that the data is already present in local storage (and not fetch live from the blockchain), and is well suited to a distributed processing framework like PySpark." }, { "code": null, "e": 7566, "s": 7286, "text": "@lru_cache(maxsize=None) — We cache the contract object creation to reduce overhead from repeating the same computation across a large number of transactions. This assumes that the decoding is targeted at a smallish number (on the order of thousands) of distinct smart contracts." }, { "code": null, "e": 8132, "s": 7566, "text": "It leverages the open-sourced web3 package method decode_function_input for extraction of data based on the templates provided in the ABI. This method, however, returns data that is often not serializable (e.g. byte arrays) and sometimes missing human-readable keys. Therefore, it is very helpful (maybe even necessary) to perform post-extraction processing using the utility method convert_to_hex to convert the data into serializable json objects and attach the human understandable keys where missing. This makes it easier to persist and re-use the decoded data." }, { "code": null, "e": 8285, "s": 8132, "text": "The same code can be used for decoding trace data elements as well. This is because they are simply internal transactions initiated by a smart contract." }, { "code": null, "e": 8337, "s": 8285, "text": "Using the code above yields this decoded input data" }, { "code": null, "e": 8703, "s": 8337, "text": "function called: swapExactTokensForTokensarguments: { \"amountIn\": 2500000000, \"amountOutMin\": 194024196127819599854524737, \"path\": [ \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\", \"0x528B3e98c63cE21C6f680b713918E0F89DfaE555\" ], \"to\": \"0x3c02cebB49F6e8f1FC96158099fFA064bBfeE38B\", \"deadline\": 1634603299}" }, { "code": null, "e": 8753, "s": 8703, "text": "From this we can much more easily understand that" }, { "code": null, "e": 9791, "s": 8753, "text": "The call is to a method namedswapExactTokensForTokens, and the user is putting in 2,500,000,000 units of the starting token, and expecting to get back at least 194,024,196,127,819,599,854,524,737 units of the target token. These numbers may seem astronomical, but keep in mind that token units are typically denoted in the 1/10^n, where n is something like 18. n is sometimes referred to as the decimal value of the token.The path array describes the tokens being exchanged in this transaction. Each array element is an address of a token contract. The first one is USDC (a stable coin pegged to the dollar), the second one is Wrapped Eth (Ethereum with an ERC20 interface), and the third one is DXO (a deep.space in-game currency).Putting 1 and 2 together, we can deduce that the user request is to swap 2,500 USDC (USDC has a decimal value of 6) for ~194 million DXO (DXO has a decimal value of 18). Since this particular pairwise swap is not directly available, the transaction will be mediated through the intermediary token of WETH." }, { "code": null, "e": 10214, "s": 9791, "text": "The call is to a method namedswapExactTokensForTokens, and the user is putting in 2,500,000,000 units of the starting token, and expecting to get back at least 194,024,196,127,819,599,854,524,737 units of the target token. These numbers may seem astronomical, but keep in mind that token units are typically denoted in the 1/10^n, where n is something like 18. n is sometimes referred to as the decimal value of the token." }, { "code": null, "e": 10525, "s": 10214, "text": "The path array describes the tokens being exchanged in this transaction. Each array element is an address of a token contract. The first one is USDC (a stable coin pegged to the dollar), the second one is Wrapped Eth (Ethereum with an ERC20 interface), and the third one is DXO (a deep.space in-game currency)." }, { "code": null, "e": 10831, "s": 10525, "text": "Putting 1 and 2 together, we can deduce that the user request is to swap 2,500 USDC (USDC has a decimal value of 6) for ~194 million DXO (DXO has a decimal value of 18). Since this particular pairwise swap is not directly available, the transaction will be mediated through the intermediary token of WETH." }, { "code": null, "e": 11104, "s": 10831, "text": "This transaction also emitted 7 events in the process of execution, which can be obtained by querying the logs table in Google’s Public Dataset on Ethereum, and also viewed on Etherscan. The two most salient records that correspond to the swaps requested by the users are:" }, { "code": null, "e": 11890, "s": 11104, "text": "log_index: 47transaction_hash: 0x87a3bc85da972583e22da329aa109ea0db57c54a2eee359b2ed12597f5cb1a64transaction_index: 37address: 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dcdata: 0x000000000000000000000000000000000000000000000000000000009502f90000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000093f8f932b016b1ctopics: ['0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822','0x0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d','0x000000000000000000000000242301fa62f0de9e3842a5fb4c0cdca67e3a2fab']block_timestamp: 2021-10-19 00:00:18block_number: 13444845block_hash: 0xe9ea4fc0ef9a13b1e403e68e3ff94bc94e472132528fe8f07ade422b84a43afc" }, { "code": null, "e": 11894, "s": 11890, "text": "and" }, { "code": null, "e": 12682, "s": 11894, "text": "log_index: 50transaction_hash: 0x87a3bc85da972583e22da329aa109ea0db57c54a2eee359b2ed12597f5cb1a64transaction_index: 37address: 0x242301fa62f0de9e3842a5fb4c0cdca67e3a2fabdata: 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000093f8f932b016b1c000000000000000000000000000000000000000000a137bb41b9113069a51e190000000000000000000000000000000000000000000000000000000000000000topics: ['0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822', '0x0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d', '0x0000000000000000000000003c02cebb49f6e8f1fc96158099ffa064bbfee38b']block_timestamp: 2021-10-19 00:00:18block_number: 13444845block_hash: 0xe9ea4fc0ef9a13b1e403e68e3ff94bc94e472132528fe8f07ade422b84a43afc" }, { "code": null, "e": 13393, "s": 12682, "text": "Again, the relevant details are encoded into hexadecimal string in the topics and data fields. As in the case with transaction input, it is instructive to go through the structure of these data fields. topics is an array where the first element represents the hashed signature of the event interface definition. Any additional elements in the topics array are typically blockchain addresses that are involved in the event, and may or may not exist depending on the specific context. data represents the event parameter values and can vary in length depending on the event definition. As was the case with transactions, we need to reference the contract ABI, in order to translate this into human readable form." }, { "code": null, "e": 14203, "s": 13393, "text": "The astute reader will notice that the contract addresses in the logs above, 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc and 0x242301fa62f0de9e3842a5fb4c0cdca67e3a2fab are different from the Router v2 contract, 0x7a250d5630b4cf539739df2c5dacb4c659f2488d, which the user EOA initially called. These two addresses correspond to Uniswap v2 pair contracts for the USDC-WETH and DXO-WETH token pairs. These contracts are responsible for holding the liquidity for their respective trading pair and actually making the swap. The Router contract, which the user interacted with initially, functions as a coordinator and initiates internal transactions (traces) to the appropriate pair contracts. Therefore, in order to decode these events, we also need the pair contract ABI. Example code to decode logs is as follows:" }, { "code": null, "e": 14443, "s": 14203, "text": "Similar to the code for transaction decoding, the example code is optimized for batch decoding use cases, and is meant to be used in conjunction with something like PySpark to process a large number of log events. Running the above yields:" }, { "code": null, "e": 14683, "s": 14443, "text": "event emitted: Swaparguments: { \"sender\": \"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\", \"to\": \"0x242301FA62f0De9e3842A5Fb4c0CdCa67e3A2Fab\", \"amount0In\": 2500000000, \"amount1In\": 0, \"amount0Out\": 0, \"amount1Out\": 666409132118600476}" }, { "code": null, "e": 14687, "s": 14683, "text": "and" }, { "code": null, "e": 14944, "s": 14687, "text": "event emitted: Swaparguments: { \"sender\": \"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\", \"to\": \"0x3c02cebB49F6e8f1FC96158099fFA064bBfeE38B\", \"amount0In\": 0, \"amount1In\": 666409132118600476, \"amount0Out\": 194900241391490294085918233, \"amount1Out\": 0}" }, { "code": null, "e": 15565, "s": 14944, "text": "We can that these two are indeed swap events that followed the path in the initial request — USDC > WETH > DXO. We can see that the router contract (ending 488D) is the sender in both events, acting as the coordinator. The USDC-WETH pair contract (ending c9dc) swaps 2,500,000,000 units of USDC for 666,409,132,118,600,476 units of WETH, and then transfers the resulting WETH to the DXO-WETH pair contract (ending 2Fab). The DXO-WETH contract then swaps the 666,409,132,118,600,476 units of WETH for 194,900,241,391,490,294,085,918,233 units of DXO and sends it back to the user (EOA ending E38B) as initially requested." }, { "code": null, "e": 16397, "s": 15565, "text": "As this example hopefully illustrates, the process of decoding is relatively straightforward once you have the tools, but knowing what to decode and how to interpret the resulting data is not. Depending on the specific question you are trying to answer, some functions and events are more relevant than others. For the purpose of analyzing economic activity and user behavior in web3 applications, it will be important to develop an understanding of how the specific smart contracts work, and to identify the key functions and events involved in the metric of interest. This is best done through a combination of actually using the product, examining the data exhaust on Block explorers like Etherscan, and reading the smart contract source code. This is a crucial requisite for developing the right decoding and analysis strategy." }, { "code": null, "e": 16702, "s": 16397, "text": "I hope this was a useful discussion and I have helped you gain a better sense for how to work with crypto data. In my next post, I will show an example deep dive analysis on Opensea, the largest NFT marketplace. Be sure to hit the email icon to subscribe if you would like to be notified when that posts." } ]
Exploratory Data Analysis in Julia - GeeksforGeeks
12 Oct, 2020 Exploratory Data Analysis (EDA) is used for achieving a better understanding of data in terms of its main features, the significance of various variables, and the inter-variable relationships. The First step is to explore the dataset. Methods to explore the given dataset in Julia: Using data tables and applying statisticsUsing Visual Plotting techniques on the data Using data tables and applying statistics Using Visual Plotting techniques on the data Step 1: Install DataFrames Package For using data tables in Julia, a data structure called Dataframe is used. DataFrame can handle multiple operations without compromising on Speed and Scalability. Dataframes package can be installed using the following command: using Pkg Pkg.add(“DataFrames”) Step 2: Download the Dataset For data analysis, we have used the Iris dataset. It is easily available online. Step 3: Import Necessary Packages and the Dataset Let’s first import our DataFrames Package, CSV Package, and load the Iris.csv file of the data set: Julia # Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”) Output: Step 4: Quick Data Exploration Preliminary exploration can be performed on the dataset such as identifying the shape of the dataset using the size function, list of columns using the names function, first n rows using the head function. Example: Julia # Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”); # Shape of Datasetsize(Iris) # List of columnsnames(Iris) # First 10 rowshead(Iris, 10) Output: Dataframe_name[:column_name] is a basic indexing technique to access a particular column of the data frame. Example: Julia # Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”); # Access particular column of datasetIris[: SepalLength] Output: Describe function is used to present the mean, median, minimum, maximum, quartiles, etc of the dataset. Example: Julia # Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”); # Using describe function # to get statistics of a datasetdescribe(Iris) # Using describe function to get# statistics of a particular column in a datasetdescribe(Iris, :all, cols=:SepalLength) Output: Visual Exploration in Julia can be achieved with the help of various plotting libraries such as Plots, StatPlots, and Pyplot. Plots: It is a high-level plotting package that interfaces other plotting packages called ‘back-ends‘. They behave like the graphics engines that generate the graphics. It has a simple and consistent interface. StatPlots: It is a supporting package used with Plots package consisting of statistical recipes for various concepts and types. PyPlot: It is used to work with mathplotlib library of Python in Julia. The above-mentioned libraries can be installed using the following commands: Pkg.add(“Plots”) Pkg.add(“StatPlots”) Pkg.add(“PyPlot”) The distribution of variables in Julia can be performed using various plots such as histogram, boxplot, scatterplot, etc. Let’s start by plotting the histogram of SepalLength: Example: Julia # Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read("Iris.csv"); # Using Plots Package using Plots # Plot HistogramPlots.histogram(Iris[:SepalLength], bins = 50, xlabel = "SepalLength", labels = "Length in cm") Output: Next, we look at box plots to understand the distributions. Box plot for SepalLength can be plotted by: Example: Julia # Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read("Iris.csv"); # Using Plots,StatPlots Package using Plots, StatPlots # Plot BoxplotPlots.boxplot(Iris[:SepalLength], xlabel = "SepalLength") Output: Next, we look at Scatter plot to understand the distributions. Scatter plot for SepalLength can be plotted by: Example: Julia # Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read("Iris.csv"); # Using Plots package using Plots # Plot Scatterplotplot(Iris[:SepalLength], seriestype = :scatter, title = "Sepal Length") Output: Julia Data-science Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Get array dimensions and size of a dimension in Julia - size() Method Exception handling in Julia Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Get number of elements of array in Julia - length() Method Join an array of strings into a single string in Julia - join() Method Working with Excel Files in Julia File Handling in Julia Getting last element of an array in Julia - last() Method
[ { "code": null, "e": 25814, "s": 25786, "text": "\n12 Oct, 2020" }, { "code": null, "e": 26051, "s": 25814, "text": "Exploratory Data Analysis (EDA) is used for achieving a better understanding of data in terms of its main features, the significance of various variables, and the inter-variable relationships. The First step is to explore the dataset. " }, { "code": null, "e": 26098, "s": 26051, "text": "Methods to explore the given dataset in Julia:" }, { "code": null, "e": 26184, "s": 26098, "text": "Using data tables and applying statisticsUsing Visual Plotting techniques on the data" }, { "code": null, "e": 26226, "s": 26184, "text": "Using data tables and applying statistics" }, { "code": null, "e": 26271, "s": 26226, "text": "Using Visual Plotting techniques on the data" }, { "code": null, "e": 26308, "s": 26271, "text": "Step 1: Install DataFrames Package " }, { "code": null, "e": 26471, "s": 26308, "text": "For using data tables in Julia, a data structure called Dataframe is used. DataFrame can handle multiple operations without compromising on Speed and Scalability." }, { "code": null, "e": 26536, "s": 26471, "text": "Dataframes package can be installed using the following command:" }, { "code": null, "e": 26569, "s": 26536, "text": "using Pkg\nPkg.add(“DataFrames”)\n" }, { "code": null, "e": 26600, "s": 26569, "text": "Step 2: Download the Dataset " }, { "code": null, "e": 26681, "s": 26600, "text": "For data analysis, we have used the Iris dataset. It is easily available online." }, { "code": null, "e": 26731, "s": 26681, "text": "Step 3: Import Necessary Packages and the Dataset" }, { "code": null, "e": 26831, "s": 26731, "text": "Let’s first import our DataFrames Package, CSV Package, and load the Iris.csv file of the data set:" }, { "code": null, "e": 26837, "s": 26831, "text": "Julia" }, { "code": "# Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”)", "e": 26969, "s": 26837, "text": null }, { "code": null, "e": 26977, "s": 26969, "text": "Output:" }, { "code": null, "e": 27008, "s": 26977, "text": "Step 4: Quick Data Exploration" }, { "code": null, "e": 27216, "s": 27008, "text": "Preliminary exploration can be performed on the dataset such as identifying the shape of the dataset using the size function, list of columns using the names function, first n rows using the head function. " }, { "code": null, "e": 27225, "s": 27216, "text": "Example:" }, { "code": null, "e": 27231, "s": 27225, "text": "Julia" }, { "code": "# Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”); # Shape of Datasetsize(Iris) # List of columnsnames(Iris) # First 10 rowshead(Iris, 10)", "e": 27456, "s": 27231, "text": null }, { "code": null, "e": 27464, "s": 27456, "text": "Output:" }, { "code": null, "e": 27574, "s": 27464, "text": "Dataframe_name[:column_name] is a basic indexing technique to access a particular column of the data frame. " }, { "code": null, "e": 27583, "s": 27574, "text": "Example:" }, { "code": null, "e": 27589, "s": 27583, "text": "Julia" }, { "code": "# Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”); # Access particular column of datasetIris[: SepalLength]", "e": 27780, "s": 27589, "text": null }, { "code": null, "e": 27788, "s": 27780, "text": "Output:" }, { "code": null, "e": 27892, "s": 27788, "text": "Describe function is used to present the mean, median, minimum, maximum, quartiles, etc of the dataset." }, { "code": null, "e": 27901, "s": 27892, "text": "Example:" }, { "code": null, "e": 27907, "s": 27901, "text": "Julia" }, { "code": "# Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(“Iris.csv”); # Using describe function # to get statistics of a datasetdescribe(Iris) # Using describe function to get# statistics of a particular column in a datasetdescribe(Iris, :all, cols=:SepalLength)", "e": 28235, "s": 27907, "text": null }, { "code": null, "e": 28243, "s": 28235, "text": "Output:" }, { "code": null, "e": 28369, "s": 28243, "text": "Visual Exploration in Julia can be achieved with the help of various plotting libraries such as Plots, StatPlots, and Pyplot." }, { "code": null, "e": 28580, "s": 28369, "text": "Plots: It is a high-level plotting package that interfaces other plotting packages called ‘back-ends‘. They behave like the graphics engines that generate the graphics. It has a simple and consistent interface." }, { "code": null, "e": 28708, "s": 28580, "text": "StatPlots: It is a supporting package used with Plots package consisting of statistical recipes for various concepts and types." }, { "code": null, "e": 28780, "s": 28708, "text": "PyPlot: It is used to work with mathplotlib library of Python in Julia." }, { "code": null, "e": 28857, "s": 28780, "text": "The above-mentioned libraries can be installed using the following commands:" }, { "code": null, "e": 28918, "s": 28857, "text": "Pkg.add(“Plots”) \nPkg.add(“StatPlots”) \nPkg.add(“PyPlot”)\n" }, { "code": null, "e": 29042, "s": 28918, "text": "The distribution of variables in Julia can be performed using various plots such as histogram, boxplot, scatterplot, etc. " }, { "code": null, "e": 29096, "s": 29042, "text": "Let’s start by plotting the histogram of SepalLength:" }, { "code": null, "e": 29105, "s": 29096, "text": "Example:" }, { "code": null, "e": 29111, "s": 29105, "text": "Julia" }, { "code": "# Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(\"Iris.csv\"); # Using Plots Package using Plots # Plot HistogramPlots.histogram(Iris[:SepalLength], bins = 50, xlabel = \"SepalLength\", labels = \"Length in cm\")", "e": 29439, "s": 29111, "text": null }, { "code": null, "e": 29447, "s": 29439, "text": "Output:" }, { "code": null, "e": 29551, "s": 29447, "text": "Next, we look at box plots to understand the distributions. Box plot for SepalLength can be plotted by:" }, { "code": null, "e": 29560, "s": 29551, "text": "Example:" }, { "code": null, "e": 29566, "s": 29560, "text": "Julia" }, { "code": "# Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(\"Iris.csv\"); # Using Plots,StatPlots Package using Plots, StatPlots # Plot BoxplotPlots.boxplot(Iris[:SepalLength], xlabel = \"SepalLength\")", "e": 29844, "s": 29566, "text": null }, { "code": null, "e": 29852, "s": 29844, "text": "Output:" }, { "code": null, "e": 29963, "s": 29852, "text": "Next, we look at Scatter plot to understand the distributions. Scatter plot for SepalLength can be plotted by:" }, { "code": null, "e": 29972, "s": 29963, "text": "Example:" }, { "code": null, "e": 29978, "s": 29972, "text": "Julia" }, { "code": "# Using the DataFrames Packageusing DataFrames # Using the CSV packageusing CSV # Reading the CSV fileIris = CSV.read(\"Iris.csv\"); # Using Plots package using Plots # Plot Scatterplotplot(Iris[:SepalLength], seriestype = :scatter, title = \"Sepal Length\")", "e": 30248, "s": 29978, "text": null }, { "code": null, "e": 30256, "s": 30248, "text": "Output:" }, { "code": null, "e": 30275, "s": 30256, "text": "Julia Data-science" }, { "code": null, "e": 30281, "s": 30275, "text": "Julia" }, { "code": null, "e": 30379, "s": 30281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30452, "s": 30379, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 30522, "s": 30452, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 30550, "s": 30522, "text": "Exception handling in Julia" }, { "code": null, "e": 30598, "s": 30550, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 30668, "s": 30598, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 30727, "s": 30668, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 30798, "s": 30727, "text": "Join an array of strings into a single string in Julia - join() Method" }, { "code": null, "e": 30832, "s": 30798, "text": "Working with Excel Files in Julia" }, { "code": null, "e": 30855, "s": 30832, "text": "File Handling in Julia" } ]
Functors and their use in Python - GeeksforGeeks
22 Nov, 2020 Let’s understand Functors First:Functors are objects the that can be treated as though they are a function. When to use functors? Functors are used when you want to hide/abstract the real implementation. Let’s say you want to call the different functions depending on the input but you don’t want the user code to make explicit calls to those different functions. This is the ideal situation where functors can help. In this scenario, we can go for a functor which internally calls the most suitable function depending on the input Now if later, none of functions to be called increases, then it would be just a simple change in the backend code without disturbing any of the user code. Thus functors help in creating maintainable, decoupled and extendable codes. Let’s understand it by a simple design problem example. The problem is to design class/method which will call different sorting method based on the input type. If the input is of type int then Mergesort function should be called and if the input is of type float then Heapsort otherwise just call quicksort function # Python code to illustrate program # without functors class GodClass(object): def DoSomething(self,x): x_first=x[0] if type(x_first) is int : return self.__MergeSort(x) if type(x_first) is float : return self.__HeapSort(x) else : return self.__QuickSort(x) def __MergeSort(self,a): #" Dummy MergeSort " print ("Data is Merge sorted") return a def __HeapSort(self,b): # " Dummy HeapSort " print( "Data is Heap sorted") return b def __QuickSort(self,c): # "Dummy QuickSort" print ("Data is Quick sorted") return c # Here the user code need to know about the conditions for calling different strategy # and making it tightly coupled code. godObject=GodClass() print (godObject.DoSomething([1,2,3])) Output: Data is Merge sorted [1, 2, 3] There are some evident design gaps in this code1. Inner Implementation should be hidden from the user code i.e abstraction should be maintained2. Every class should handle single responsibility/functionality.2. The code is tightly coupled. Let’s solve the same problem using functors in python # Python code to illustrate program # using functors class Functor(object): def __init__(self, n=10): self.n = n # This construct allows objects to be called as functions in python def __call__(self, x) : x_first = x[0] if type(x_first) is int: return self. __MergeSort(x) if type(x_first) is float: return self. __HeapSort(x) else : return self.__QuickSort(x) def __MergeSort(self,a): #" Dummy MergeSort " print ("Data is Merge sorted") return a def __HeapSort(self,b): # " Dummy HeapSort " print ("Data is Heap sorted") return b def __QuickSort(self,c): # "Dummy QuickSort" print ("Data is Quick sorted") return c # Now let's code the class which will call the above functions. # Without the functor this class should know which specific function to be called # based on the type of input ### USER CODE class Caller(object): def __init__(self): self.sort=Functor() def Dosomething(self,x): # Here it simply calls the function and doesn't need to care about # which sorting is used. It only knows that sorted output will be the # result of this call return self.sort(x) Call=Caller() # Here passing different input print(Call.Dosomething([5,4,6])) # Mergesort print(Call.Dosomething([2.23,3.45,5.65])) # heapsort print(Call.Dosomething(['a','s','b','q'])) # quick sort # creating word vocab Output: Data is Merge sorted [5, 4, 6] Data is Heap sorted [2.23, 3.45, 5.65] Data is Quick sorted ['a', 's', 'b', 'q'] The above design makes it easy to change the underneath strategy or implementation without disturbing any user code. Usercode can reliably use the above functor without knowing what is going underneath the hood,making the code decoupled, easily extendable and maintainable. Now, along with the functions in the python, you have also understood the strategy pattern in Python which calls for the separation between the Class calling the specific function and Class where strategies are listed or chosen. References:https://www.daniweb.com/programming/software-development/threads/485098/functors-in-python This article is contributed by Ankit Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 25517, "s": 25489, "text": "\n22 Nov, 2020" }, { "code": null, "e": 25625, "s": 25517, "text": "Let’s understand Functors First:Functors are objects the that can be treated as though they are a function." }, { "code": null, "e": 25647, "s": 25625, "text": "When to use functors?" }, { "code": null, "e": 25934, "s": 25647, "text": "Functors are used when you want to hide/abstract the real implementation. Let’s say you want to call the different functions depending on the input but you don’t want the user code to make explicit calls to those different functions. This is the ideal situation where functors can help." }, { "code": null, "e": 26049, "s": 25934, "text": "In this scenario, we can go for a functor which internally calls the most suitable function depending on the input" }, { "code": null, "e": 26281, "s": 26049, "text": "Now if later, none of functions to be called increases, then it would be just a simple change in the backend code without disturbing any of the user code. Thus functors help in creating maintainable, decoupled and extendable codes." }, { "code": null, "e": 26597, "s": 26281, "text": "Let’s understand it by a simple design problem example. The problem is to design class/method which will call different sorting method based on the input type. If the input is of type int then Mergesort function should be called and if the input is of type float then Heapsort otherwise just call quicksort function" }, { "code": "# Python code to illustrate program # without functors class GodClass(object): def DoSomething(self,x): x_first=x[0] if type(x_first) is int : return self.__MergeSort(x) if type(x_first) is float : return self.__HeapSort(x) else : return self.__QuickSort(x) def __MergeSort(self,a): #\" Dummy MergeSort \" print (\"Data is Merge sorted\") return a def __HeapSort(self,b): # \" Dummy HeapSort \" print( \"Data is Heap sorted\") return b def __QuickSort(self,c): # \"Dummy QuickSort\" print (\"Data is Quick sorted\") return c # Here the user code need to know about the conditions for calling different strategy # and making it tightly coupled code. godObject=GodClass() print (godObject.DoSomething([1,2,3])) ", "e": 27501, "s": 26597, "text": null }, { "code": null, "e": 27509, "s": 27501, "text": "Output:" }, { "code": null, "e": 27541, "s": 27509, "text": "Data is Merge sorted\n[1, 2, 3]\n" }, { "code": null, "e": 27781, "s": 27541, "text": "There are some evident design gaps in this code1. Inner Implementation should be hidden from the user code i.e abstraction should be maintained2. Every class should handle single responsibility/functionality.2. The code is tightly coupled." }, { "code": null, "e": 27835, "s": 27781, "text": "Let’s solve the same problem using functors in python" }, { "code": "# Python code to illustrate program # using functors class Functor(object): def __init__(self, n=10): self.n = n # This construct allows objects to be called as functions in python def __call__(self, x) : x_first = x[0] if type(x_first) is int: return self. __MergeSort(x) if type(x_first) is float: return self. __HeapSort(x) else : return self.__QuickSort(x) def __MergeSort(self,a): #\" Dummy MergeSort \" print (\"Data is Merge sorted\") return a def __HeapSort(self,b): # \" Dummy HeapSort \" print (\"Data is Heap sorted\") return b def __QuickSort(self,c): # \"Dummy QuickSort\" print (\"Data is Quick sorted\") return c # Now let's code the class which will call the above functions. # Without the functor this class should know which specific function to be called # based on the type of input ### USER CODE class Caller(object): def __init__(self): self.sort=Functor() def Dosomething(self,x): # Here it simply calls the function and doesn't need to care about # which sorting is used. It only knows that sorted output will be the # result of this call return self.sort(x) Call=Caller() # Here passing different input print(Call.Dosomething([5,4,6])) # Mergesort print(Call.Dosomething([2.23,3.45,5.65])) # heapsort print(Call.Dosomething(['a','s','b','q'])) # quick sort # creating word vocab ", "e": 29355, "s": 27835, "text": null }, { "code": null, "e": 29363, "s": 29355, "text": "Output:" }, { "code": null, "e": 29478, "s": 29363, "text": "\nData is Merge sorted\n[5, 4, 6]\nData is Heap sorted\n[2.23, 3.45, 5.65]\nData is Quick sorted\n['a', 's', 'b', 'q']\n\n" }, { "code": null, "e": 29752, "s": 29478, "text": "The above design makes it easy to change the underneath strategy or implementation without disturbing any user code. Usercode can reliably use the above functor without knowing what is going underneath the hood,making the code decoupled, easily extendable and maintainable." }, { "code": null, "e": 29981, "s": 29752, "text": "Now, along with the functions in the python, you have also understood the strategy pattern in Python which calls for the separation between the Class calling the specific function and Class where strategies are listed or chosen." }, { "code": null, "e": 30083, "s": 29981, "text": "References:https://www.daniweb.com/programming/software-development/threads/485098/functors-in-python" }, { "code": null, "e": 30382, "s": 30083, "text": "This article is contributed by Ankit Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30507, "s": 30382, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30514, "s": 30507, "text": "Python" }, { "code": null, "e": 30612, "s": 30514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30630, "s": 30612, "text": "Python Dictionary" }, { "code": null, "e": 30665, "s": 30630, "text": "Read a file line by line in Python" }, { "code": null, "e": 30697, "s": 30665, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30719, "s": 30697, "text": "Enumerate() in Python" }, { "code": null, "e": 30761, "s": 30719, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30791, "s": 30761, "text": "Iterate over a list in Python" }, { "code": null, "e": 30817, "s": 30791, "text": "Python String | replace()" }, { "code": null, "e": 30861, "s": 30817, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30898, "s": 30861, "text": "Create a Pandas DataFrame from Lists" } ]
How to convert list of dictionaries into Pyspark DataFrame ? - GeeksforGeeks
30 May, 2021 In this article, we are going to discuss the creation of the Pyspark dataframe from the list of dictionaries. We are going to create a dataframe in PySpark using a list of dictionaries with the help createDataFrame() method. The data attribute takes the list of dictionaries and columns attribute takes the list of names. dataframe = spark.createDataFrame(data, columns) Example 1: Python3 # importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of dictionaries of students datadata = [{"Student ID": 1, "Student name": "sravan"}, {"Student ID": 2, "Student name": "Jyothika"}, {"Student ID": 3, "Student name": "deepika"}, {"Student ID": 4, "Student name": "harsha"}] # creating a dataframedataframe = spark.createDataFrame(data) # display dataframedataframe.show() Output: Example 2: Python3 # importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of dictionaries of crop datadata = [{"Crop ID": 1, "name": "rose", "State": "AP"}, {"Crop ID": 2, "name": "lilly", "State": "TS"}, {"Crop ID": 3, "name": "lotus", "State": "Maharashtra"}, {"Crop ID": 4, "name": "jasmine", "State": "AP"}] # creating a dataframedataframe = spark.createDataFrame(data) # display dataframedataframe.show() Output: Example 3: Python3 # importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of dictionaries of crop datadata = [{"Crop ID": 1, "name": "rose", "State": "AP"}, {"Crop ID": 2, "name": "lilly", "State": "TS"}, {"Crop ID": 3, "name": "lotus", "State": "Maharashtra"}, {"Crop ID": 4, "name": "jasmine", "State": "AP"}] # creating a dataframedataframe = spark.createDataFrame(data) # display dataframe countdataframe.count() Output: 4 Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n30 May, 2021" }, { "code": null, "e": 25647, "s": 25537, "text": "In this article, we are going to discuss the creation of the Pyspark dataframe from the list of dictionaries." }, { "code": null, "e": 25859, "s": 25647, "text": "We are going to create a dataframe in PySpark using a list of dictionaries with the help createDataFrame() method. The data attribute takes the list of dictionaries and columns attribute takes the list of names." }, { "code": null, "e": 25908, "s": 25859, "text": "dataframe = spark.createDataFrame(data, columns)" }, { "code": null, "e": 25919, "s": 25908, "text": "Example 1:" }, { "code": null, "e": 25927, "s": 25919, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of dictionaries of students datadata = [{\"Student ID\": 1, \"Student name\": \"sravan\"}, {\"Student ID\": 2, \"Student name\": \"Jyothika\"}, {\"Student ID\": 3, \"Student name\": \"deepika\"}, {\"Student ID\": 4, \"Student name\": \"harsha\"}] # creating a dataframedataframe = spark.createDataFrame(data) # display dataframedataframe.show()", "e": 26510, "s": 25927, "text": null }, { "code": null, "e": 26518, "s": 26510, "text": "Output:" }, { "code": null, "e": 26529, "s": 26518, "text": "Example 2:" }, { "code": null, "e": 26537, "s": 26529, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of dictionaries of crop datadata = [{\"Crop ID\": 1, \"name\": \"rose\", \"State\": \"AP\"}, {\"Crop ID\": 2, \"name\": \"lilly\", \"State\": \"TS\"}, {\"Crop ID\": 3, \"name\": \"lotus\", \"State\": \"Maharashtra\"}, {\"Crop ID\": 4, \"name\": \"jasmine\", \"State\": \"AP\"}] # creating a dataframedataframe = spark.createDataFrame(data) # display dataframedataframe.show()", "e": 27137, "s": 26537, "text": null }, { "code": null, "e": 27145, "s": 27137, "text": "Output:" }, { "code": null, "e": 27156, "s": 27145, "text": "Example 3:" }, { "code": null, "e": 27164, "s": 27156, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of dictionaries of crop datadata = [{\"Crop ID\": 1, \"name\": \"rose\", \"State\": \"AP\"}, {\"Crop ID\": 2, \"name\": \"lilly\", \"State\": \"TS\"}, {\"Crop ID\": 3, \"name\": \"lotus\", \"State\": \"Maharashtra\"}, {\"Crop ID\": 4, \"name\": \"jasmine\", \"State\": \"AP\"}] # creating a dataframedataframe = spark.createDataFrame(data) # display dataframe countdataframe.count()", "e": 27771, "s": 27164, "text": null }, { "code": null, "e": 27779, "s": 27771, "text": "Output:" }, { "code": null, "e": 27781, "s": 27779, "text": "4" }, { "code": null, "e": 27788, "s": 27781, "text": "Picked" }, { "code": null, "e": 27803, "s": 27788, "text": "Python-Pyspark" }, { "code": null, "e": 27810, "s": 27803, "text": "Python" }, { "code": null, "e": 27908, "s": 27810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27940, "s": 27908, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27982, "s": 27940, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28024, "s": 27982, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28080, "s": 28024, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28107, "s": 28080, "text": "Python Classes and Objects" }, { "code": null, "e": 28146, "s": 28107, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28177, "s": 28146, "text": "Python | os.path.join() method" }, { "code": null, "e": 28199, "s": 28177, "text": "Defaultdict in Python" }, { "code": null, "e": 28228, "s": 28199, "text": "Create a directory in Python" } ]
PyQt5 QDateEdit - Selecting Whole Date - GeeksforGeeks
07 Jul, 2020 In this article we will see how we can select the whole date of the QDateEdit. User can set a date to the date edit with the help of cursor and the keyboard. Selecting date means the text of the date, selecting date is used for copying or overwriting the text of date edit. In order to do this we use selectAll method with the QDateEdit object Syntax : date.selectAll() Argument : It takes no argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # creating push button push = QPushButton("Select", self) # setting geometry to the push button push.setGeometry(100, 150, 120, 30) # adding action to the push button # when it get clicked push.clicked.connect(lambda: push_method()) # method called by push button def push_method(): # selecting text date.selectAll() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QDateEdit Python-gui Python-PyQt 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 26131, "s": 26103, "text": "\n07 Jul, 2020" }, { "code": null, "e": 26405, "s": 26131, "text": "In this article we will see how we can select the whole date of the QDateEdit. User can set a date to the date edit with the help of cursor and the keyboard. Selecting date means the text of the date, selecting date is used for copying or overwriting the text of date edit." }, { "code": null, "e": 26475, "s": 26405, "text": "In order to do this we use selectAll method with the QDateEdit object" }, { "code": null, "e": 26501, "s": 26475, "text": "Syntax : date.selectAll()" }, { "code": null, "e": 26533, "s": 26501, "text": "Argument : It takes no argument" }, { "code": null, "e": 26558, "s": 26533, "text": "Return : It returns None" }, { "code": null, "e": 26586, "s": 26558, "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 class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # creating push button push = QPushButton(\"Select\", self) # setting geometry to the push button push.setGeometry(100, 150, 120, 30) # adding action to the push button # when it get clicked push.clicked.connect(lambda: push_method()) # method called by push button def push_method(): # selecting text date.selectAll() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27825, "s": 26586, "text": null }, { "code": null, "e": 27834, "s": 27825, "text": "Output :" }, { "code": null, "e": 27856, "s": 27834, "text": "Python PyQt-QDateEdit" }, { "code": null, "e": 27867, "s": 27856, "text": "Python-gui" }, { "code": null, "e": 27879, "s": 27867, "text": "Python-PyQt" }, { "code": null, "e": 27886, "s": 27879, "text": "Python" }, { "code": null, "e": 27984, "s": 27886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28002, "s": 27984, "text": "Python Dictionary" }, { "code": null, "e": 28037, "s": 28002, "text": "Read a file line by line in Python" }, { "code": null, "e": 28069, "s": 28037, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28091, "s": 28069, "text": "Enumerate() in Python" }, { "code": null, "e": 28133, "s": 28091, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28163, "s": 28133, "text": "Iterate over a list in Python" }, { "code": null, "e": 28192, "s": 28163, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28236, "s": 28192, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28273, "s": 28236, "text": "Create a Pandas DataFrame from Lists" } ]
Python | Numpy numpy.matrix.T() - GeeksforGeeks
08 Apr, 2019 With the help of Numpy numpy.matrix.T() method, we can make a Transpose of any matrix either having dimension one or more than more. Syntax : numpy.matrix.T() Return : Return transpose of every matrix Example #1 :In this example we can see that with the help of matrix.T() method, we are able to transform any type of matrix. # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4]') # applying matrix.T() methodgeeks = gfg.getT() print(geeks) [[1] [2] [3] [4]] Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.T() methodgeeks = gfg.getT() print(geeks) [[1 4 7] [2 5 8] [3 6 9]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n08 Apr, 2019" }, { "code": null, "e": 25670, "s": 25537, "text": "With the help of Numpy numpy.matrix.T() method, we can make a Transpose of any matrix either having dimension one or more than more." }, { "code": null, "e": 25696, "s": 25670, "text": "Syntax : numpy.matrix.T()" }, { "code": null, "e": 25738, "s": 25696, "text": "Return : Return transpose of every matrix" }, { "code": null, "e": 25863, "s": 25738, "text": "Example #1 :In this example we can see that with the help of matrix.T() method, we are able to transform any type of matrix." }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4]') # applying matrix.T() methodgeeks = gfg.getT() print(geeks)", "e": 26060, "s": 25863, "text": null }, { "code": null, "e": 26082, "s": 26060, "text": "[[1]\n [2]\n [3]\n [4]]\n" }, { "code": null, "e": 26095, "s": 26082, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.T() methodgeeks = gfg.getT() print(geeks)", "e": 26307, "s": 26095, "text": null }, { "code": null, "e": 26336, "s": 26307, "text": "[[1 4 7]\n [2 5 8]\n [3 6 9]]\n" }, { "code": null, "e": 26365, "s": 26336, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 26378, "s": 26365, "text": "Python-numpy" }, { "code": null, "e": 26385, "s": 26378, "text": "Python" }, { "code": null, "e": 26483, "s": 26385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26515, "s": 26483, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26557, "s": 26515, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26599, "s": 26557, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26626, "s": 26599, "text": "Python Classes and Objects" }, { "code": null, "e": 26682, "s": 26626, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26721, "s": 26682, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26743, "s": 26721, "text": "Defaultdict in Python" }, { "code": null, "e": 26774, "s": 26743, "text": "Python | os.path.join() method" }, { "code": null, "e": 26803, "s": 26774, "text": "Create a directory in Python" } ]
pr command in Linux - GeeksforGeeks
28 Jan, 2022 In Linux/Unix pr command is used to prepare a file for printing by adding suitable footers, headers, and the formatted text. pr command actually adds 5 lines of margin both at the top and bottom of the page. The header part shows the date and time of the last modification of the file with the file name and the page number. Syntax: pr [options][filename] 1. To print k number of columns we use -k. Let’s say, we have a file that contains 10 numbers from 1 to 10 with every number in a new line. Now if we want to print this content in 3 columns we will use the following command. pr -3 abc.txt here abc.txt is the name of file. 2. To suppress the headers and footers the -t option is used. pr -t abc.txt After executing the above command it will give us the following output. 3. To Double the paces input, reduces clutter -d option is used. pr -d abc.txt After executing the above command it will give us the following output. 4. To provide number lines which helps in debugging the code -n option is used. pr -n abc.txt After executing the above command it will give us the following output. 5. To print the version number of the command –version is used. pr --version After executing the command, it will return us the version in the below mentioned format. 6. To open the help section of the command or to get the details of all the options and attributes of the command –help is used. pr --help After executing the command, it will return us the help section in the following way. yashdongre146 Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Characteristics of Internet of Things Advantages and Disadvantages of OOP Sensors in Internet of Things(IoT) Challenges in Internet of things (IoT) Election algorithm and distributed processing Introduction to Internet of Things (IoT) | Set 1 Introduction to Electronic Mail Communication Models in IoT (Internet of Things ) Introduction to Parallel Computing
[ { "code": null, "e": 25893, "s": 25865, "text": "\n28 Jan, 2022" }, { "code": null, "e": 26220, "s": 25893, "text": "In Linux/Unix pr command is used to prepare a file for printing by adding suitable footers, headers, and the formatted text. pr command actually adds 5 lines of margin both at the top and bottom of the page. The header part shows the date and time of the last modification of the file with the file name and the page number. " }, { "code": null, "e": 26228, "s": 26220, "text": "Syntax:" }, { "code": null, "e": 26251, "s": 26228, "text": "pr [options][filename]" }, { "code": null, "e": 26392, "s": 26251, "text": "1. To print k number of columns we use -k. Let’s say, we have a file that contains 10 numbers from 1 to 10 with every number in a new line. " }, { "code": null, "e": 26477, "s": 26392, "text": "Now if we want to print this content in 3 columns we will use the following command." }, { "code": null, "e": 26525, "s": 26477, "text": "pr -3 abc.txt\nhere abc.txt is the name of file." }, { "code": null, "e": 26587, "s": 26525, "text": "2. To suppress the headers and footers the -t option is used." }, { "code": null, "e": 26601, "s": 26587, "text": "pr -t abc.txt" }, { "code": null, "e": 26673, "s": 26601, "text": "After executing the above command it will give us the following output." }, { "code": null, "e": 26738, "s": 26673, "text": "3. To Double the paces input, reduces clutter -d option is used." }, { "code": null, "e": 26752, "s": 26738, "text": "pr -d abc.txt" }, { "code": null, "e": 26825, "s": 26752, "text": "After executing the above command it will give us the following output. " }, { "code": null, "e": 26905, "s": 26825, "text": "4. To provide number lines which helps in debugging the code -n option is used." }, { "code": null, "e": 26919, "s": 26905, "text": "pr -n abc.txt" }, { "code": null, "e": 26992, "s": 26919, "text": "After executing the above command it will give us the following output. " }, { "code": null, "e": 27057, "s": 26992, "text": "5. To print the version number of the command –version is used. " }, { "code": null, "e": 27070, "s": 27057, "text": "pr --version" }, { "code": null, "e": 27161, "s": 27070, "text": "After executing the command, it will return us the version in the below mentioned format. " }, { "code": null, "e": 27290, "s": 27161, "text": "6. To open the help section of the command or to get the details of all the options and attributes of the command –help is used." }, { "code": null, "e": 27300, "s": 27290, "text": "pr --help" }, { "code": null, "e": 27386, "s": 27300, "text": "After executing the command, it will return us the help section in the following way." }, { "code": null, "e": 27400, "s": 27386, "text": "yashdongre146" }, { "code": null, "e": 27405, "s": 27400, "text": "Misc" }, { "code": null, "e": 27410, "s": 27405, "text": "Misc" }, { "code": null, "e": 27415, "s": 27410, "text": "Misc" }, { "code": null, "e": 27513, "s": 27415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27534, "s": 27513, "text": "Activation Functions" }, { "code": null, "e": 27572, "s": 27534, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 27608, "s": 27572, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 27643, "s": 27608, "text": "Sensors in Internet of Things(IoT)" }, { "code": null, "e": 27682, "s": 27643, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 27728, "s": 27682, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 27777, "s": 27728, "text": "Introduction to Internet of Things (IoT) | Set 1" }, { "code": null, "e": 27809, "s": 27777, "text": "Introduction to Electronic Mail" }, { "code": null, "e": 27859, "s": 27809, "text": "Communication Models in IoT (Internet of Things )" } ]
Strings in LISP - GeeksforGeeks
30 Sep, 2021 A string is a set of characters. String are enclosed in double-quotes. Example: "hello geek","java","python" etc Example: LISP program to display strings Lisp ;edisplay hello geek(write-line "Hello Geek") ;display (write-line "Welcome to java") Output: Hello Geek Welcome to java Used to compare two strings. Further they can be divided into two categories. They are Case Sensitive Functions: These functions can be represented by mathematical symbols. Example: LISP program that demonstrates string case sensitive functions Lisp ; case-sensitive comparison - equal to (write (string= "Hello Geeks" "Hello Geeks")) ;new line(terpri) ; case-sensitive comparison - equal to (write (string= "Hello Geeks" "HelloGeeks")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string/= "Hello Geeks" "Hello Geeks")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string/= "Hello Geeks" "HelloGeeks")) ;new line(terpri) ; case-sensitive comparison - greater than(write (string> "Hello Geeks" "Python")) ;new line(terpri) ; case-sensitive comparison - less than(write (string< "Hello Geeks" "java")) ;new line(terpri) ; case-sensitive comparison - greater than or equal to(write (string>= "Hello Geeks" "Python")) ;new line(terpri) ; case-sensitive comparison - less than or equal to(write (string<= "Hello Geeks" "java")) ;new line(terpri) Output: T NIL NIL 5 NIL 0 NIL 0 Case INSENSITIVE FUNCTIONS These functions can be represented by expressions. Example: Lisp program that demonstrates case insensitive functions Lisp ; case-sensitive comparison - equal to (write (string-equal "Hello Geeks" "Hello Geeks")) ;new line(terpri) ; case-sensitive comparison - equal to (write (string-equal "Hello Geeks" "HelloGeeks")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string-not-equal "Hello Geeks" "Hello Geeks")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string-not-equal "Hello Geeks" "HelloGeeks")) ;new line(terpri) ; case-sensitive comparison - greater than(write (string-greaterp "Hello Geeks" "Python")) ;new line(terpri) ; case-sensitive comparison - less than(write (string-lessp "Hello Geeks" "java")) ;new line(terpri) ; case-sensitive comparison - greater than or equal to(write (string-not-lessp "Hello Geeks" "Python")) ;new line(terpri) ; case-sensitive comparison - less than or equal to(write (string-not-greaterp "Hello Geeks" "java")) ;new line(terpri) Output: T NIL NIL 5 NIL 0 NIL 0 LISP-DataTypes Picked LISP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cond Construct in LISP Data Types in LISP Packages in LISP LISP - Comparison Operators on Characters & Strings Symbols in LISP Mapping Functions in LISP Do Construct in LISP Case Construct in LISP Property Lists in LISP Naming Conventions in LISP
[ { "code": null, "e": 24837, "s": 24809, "text": "\n30 Sep, 2021" }, { "code": null, "e": 24910, "s": 24837, "text": "A string is a set of characters. String are enclosed in double-quotes. " }, { "code": null, "e": 24919, "s": 24910, "text": "Example:" }, { "code": null, "e": 24952, "s": 24919, "text": "\"hello geek\",\"java\",\"python\" etc" }, { "code": null, "e": 24993, "s": 24952, "text": "Example: LISP program to display strings" }, { "code": null, "e": 24998, "s": 24993, "text": "Lisp" }, { "code": ";edisplay hello geek(write-line \"Hello Geek\") ;display (write-line \"Welcome to java\")", "e": 25085, "s": 24998, "text": null }, { "code": null, "e": 25093, "s": 25085, "text": "Output:" }, { "code": null, "e": 25120, "s": 25093, "text": "Hello Geek\nWelcome to java" }, { "code": null, "e": 25207, "s": 25120, "text": "Used to compare two strings. Further they can be divided into two categories. They are" }, { "code": null, "e": 25233, "s": 25207, "text": "Case Sensitive Functions:" }, { "code": null, "e": 25293, "s": 25233, "text": "These functions can be represented by mathematical symbols." }, { "code": null, "e": 25365, "s": 25293, "text": "Example: LISP program that demonstrates string case sensitive functions" }, { "code": null, "e": 25370, "s": 25365, "text": "Lisp" }, { "code": "; case-sensitive comparison - equal to (write (string= \"Hello Geeks\" \"Hello Geeks\")) ;new line(terpri) ; case-sensitive comparison - equal to (write (string= \"Hello Geeks\" \"HelloGeeks\")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string/= \"Hello Geeks\" \"Hello Geeks\")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string/= \"Hello Geeks\" \"HelloGeeks\")) ;new line(terpri) ; case-sensitive comparison - greater than(write (string> \"Hello Geeks\" \"Python\")) ;new line(terpri) ; case-sensitive comparison - less than(write (string< \"Hello Geeks\" \"java\")) ;new line(terpri) ; case-sensitive comparison - greater than or equal to(write (string>= \"Hello Geeks\" \"Python\")) ;new line(terpri) ; case-sensitive comparison - less than or equal to(write (string<= \"Hello Geeks\" \"java\")) ;new line(terpri)", "e": 26229, "s": 25370, "text": null }, { "code": null, "e": 26237, "s": 26229, "text": "Output:" }, { "code": null, "e": 26261, "s": 26237, "text": "T\nNIL\nNIL\n5\nNIL\n0\nNIL\n0" }, { "code": null, "e": 26288, "s": 26261, "text": "Case INSENSITIVE FUNCTIONS" }, { "code": null, "e": 26339, "s": 26288, "text": "These functions can be represented by expressions." }, { "code": null, "e": 26406, "s": 26339, "text": "Example: Lisp program that demonstrates case insensitive functions" }, { "code": null, "e": 26411, "s": 26406, "text": "Lisp" }, { "code": "; case-sensitive comparison - equal to (write (string-equal \"Hello Geeks\" \"Hello Geeks\")) ;new line(terpri) ; case-sensitive comparison - equal to (write (string-equal \"Hello Geeks\" \"HelloGeeks\")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string-not-equal \"Hello Geeks\" \"Hello Geeks\")) ;new line(terpri) ; case-sensitive comparison - not equal to (write (string-not-equal \"Hello Geeks\" \"HelloGeeks\")) ;new line(terpri) ; case-sensitive comparison - greater than(write (string-greaterp \"Hello Geeks\" \"Python\")) ;new line(terpri) ; case-sensitive comparison - less than(write (string-lessp \"Hello Geeks\" \"java\")) ;new line(terpri) ; case-sensitive comparison - greater than or equal to(write (string-not-lessp \"Hello Geeks\" \"Python\")) ;new line(terpri) ; case-sensitive comparison - less than or equal to(write (string-not-greaterp \"Hello Geeks\" \"java\")) ;new line(terpri)", "e": 27328, "s": 26411, "text": null }, { "code": null, "e": 27336, "s": 27328, "text": "Output:" }, { "code": null, "e": 27360, "s": 27336, "text": "T\nNIL\nNIL\n5\nNIL\n0\nNIL\n0" }, { "code": null, "e": 27375, "s": 27360, "text": "LISP-DataTypes" }, { "code": null, "e": 27382, "s": 27375, "text": "Picked" }, { "code": null, "e": 27387, "s": 27382, "text": "LISP" }, { "code": null, "e": 27485, "s": 27387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27508, "s": 27485, "text": "Cond Construct in LISP" }, { "code": null, "e": 27527, "s": 27508, "text": "Data Types in LISP" }, { "code": null, "e": 27544, "s": 27527, "text": "Packages in LISP" }, { "code": null, "e": 27596, "s": 27544, "text": "LISP - Comparison Operators on Characters & Strings" }, { "code": null, "e": 27612, "s": 27596, "text": "Symbols in LISP" }, { "code": null, "e": 27638, "s": 27612, "text": "Mapping Functions in LISP" }, { "code": null, "e": 27659, "s": 27638, "text": "Do Construct in LISP" }, { "code": null, "e": 27682, "s": 27659, "text": "Case Construct in LISP" }, { "code": null, "e": 27705, "s": 27682, "text": "Property Lists in LISP" } ]
Nested if-else statement in R - GeeksforGeeks
23 Sep, 2021 In this article, we will discuss the nested if-else statement in the R programming language. The if-else statements can be nested together to form a group of statements and evaluate expressions based on the conditions one by one, beginning from the outer condition to the inner one by one respectively. An if-else statement within another if-else statement better justifies the definition. Syntax: if(condition1){ # execute only if condition 1 satisfies if(condition 2){ # execute if both condition 1 and 2 satisfy } }else{ } Example: Nested if-else statement R # creating valuesvar1 <- 6var2 <- 5var3 <- -4 # checking if-else if ladderif(var1 > 10 || var2 < 5){ print("condition1")}else{ if(var1 <4 ){ print("condition2") }else{ if(var2>10){ print("condition3") } else{ print("condition4") } }} Output: [1] "condition4" The first argument in the ifelse() method contains the condition to be evaluated. The second and third arguments contain the value on true and false evaluation of the condition respectively. In the case of evaluation with dataframe or other R objects, the columns are referred to typiusing the dataframe name. Syntax: ifelse(cond, value-on-true, value-on-false) Example: Nested if-else using ifelse R # creating a dataframe data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print("Original DataFrame")print(data_frame) data_frame$col3 = ifelse(data_frame$col1>4,"cond1 satisfied", ifelse(data_frame$col2 %in% c("A","C"), "cond2 satisfied", "both failed")) print("Modified DataFrame")print(data_frame) Output: [1] "Original DataFrame" col1 col2 1 1 A 2 2 B 3 3 C 4 4 A 5 5 B 6 6 C 7 7 A 8 8 B 9 9 C [1] "Modified DataFrame" col1 col2 col3 1 1 A cond2 satisfied 2 2 B both failed 3 3 C cond2 satisfied 4 4 A cond2 satisfied 5 5 B cond1 satisfied 6 6 C cond1 satisfied 7 7 A cond1 satisfied 8 8 B cond1 satisfied 9 9 C cond1 satisfied In the case of the nested dataframe, the nested conditions contain the dataframe name again and again. To save from this complexity and increase efficiency, the dataframe name is specified in the first argument of the with() method. Syntax: with(data-frame , ifelse()) Example: Using with() with ifelse() R # creating a dataframe data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print("Original DataFrame")print(data_frame) data_frame$col3 = with(data_frame, ifelse(col1>4,"cond1 satisfied", ifelse(col2 %in% c("A","C"), "cond2 satisifed", "both failed"))) print("Modified DataFrame")print(data_frame) Output [1] "Original DataFrame" col1 col2 1 1 A 2 2 B 3 3 C 4 4 A 5 5 B 6 6 C 7 7 A 8 8 B 9 9 C [1] "Modified DataFrame" col1 col2 col3 1 1 A cond2 satisfied 2 2 B both failed 3 3 C cond2 satisfied 4 4 A cond2 satisfied 5 5 B cond1 satisfied 6 6 C cond1 satisfied 7 7 A cond1 satisfied 8 8 B cond1 satisfied 9 9 C cond1 satisfied Picked R-basics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 Sep, 2021" }, { "code": null, "e": 26580, "s": 26487, "text": "In this article, we will discuss the nested if-else statement in the R programming language." }, { "code": null, "e": 26877, "s": 26580, "text": "The if-else statements can be nested together to form a group of statements and evaluate expressions based on the conditions one by one, beginning from the outer condition to the inner one by one respectively. An if-else statement within another if-else statement better justifies the definition." }, { "code": null, "e": 26885, "s": 26877, "text": "Syntax:" }, { "code": null, "e": 27014, "s": 26885, "text": "if(condition1){\n# execute only if condition 1 satisfies\nif(condition 2){ \n# execute if both condition 1 and 2 satisfy\n}\n}else{\n}" }, { "code": null, "e": 27048, "s": 27014, "text": "Example: Nested if-else statement" }, { "code": null, "e": 27050, "s": 27048, "text": "R" }, { "code": "# creating valuesvar1 <- 6var2 <- 5var3 <- -4 # checking if-else if ladderif(var1 > 10 || var2 < 5){ print(\"condition1\")}else{ if(var1 <4 ){ print(\"condition2\") }else{ if(var2>10){ print(\"condition3\") } else{ print(\"condition4\") } }}", "e": 27314, "s": 27050, "text": null }, { "code": null, "e": 27322, "s": 27314, "text": "Output:" }, { "code": null, "e": 27339, "s": 27322, "text": "[1] \"condition4\"" }, { "code": null, "e": 27650, "s": 27339, "text": "The first argument in the ifelse() method contains the condition to be evaluated. The second and third arguments contain the value on true and false evaluation of the condition respectively. In the case of evaluation with dataframe or other R objects, the columns are referred to typiusing the dataframe name. " }, { "code": null, "e": 27658, "s": 27650, "text": "Syntax:" }, { "code": null, "e": 27702, "s": 27658, "text": "ifelse(cond, value-on-true, value-on-false)" }, { "code": null, "e": 27739, "s": 27702, "text": "Example: Nested if-else using ifelse" }, { "code": null, "e": 27741, "s": 27739, "text": "R" }, { "code": "# creating a dataframe data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print(\"Original DataFrame\")print(data_frame) data_frame$col3 = ifelse(data_frame$col1>4,\"cond1 satisfied\", ifelse(data_frame$col2 %in% c(\"A\",\"C\"), \"cond2 satisfied\", \"both failed\")) print(\"Modified DataFrame\")print(data_frame)", "e": 28158, "s": 27741, "text": null }, { "code": null, "e": 28166, "s": 28158, "text": "Output:" }, { "code": null, "e": 28632, "s": 28166, "text": "[1] \"Original DataFrame\" \ncol1 col2 \n1 1 A \n2 2 B \n3 3 C \n4 4 A \n5 5 B \n6 6 C \n7 7 A \n8 8 B \n9 9 C \n[1] \"Modified DataFrame\"\ncol1 col2 col3 \n1 1 A cond2 satisfied \n2 2 B both failed \n3 3 C cond2 satisfied \n4 4 A cond2 satisfied \n5 5 B cond1 satisfied \n6 6 C cond1 satisfied \n7 7 A cond1 satisfied \n8 8 B cond1 satisfied \n9 9 C cond1 satisfied" }, { "code": null, "e": 28865, "s": 28632, "text": "In the case of the nested dataframe, the nested conditions contain the dataframe name again and again. To save from this complexity and increase efficiency, the dataframe name is specified in the first argument of the with() method." }, { "code": null, "e": 28874, "s": 28865, "text": "Syntax: " }, { "code": null, "e": 28902, "s": 28874, "text": "with(data-frame , ifelse())" }, { "code": null, "e": 28938, "s": 28902, "text": "Example: Using with() with ifelse()" }, { "code": null, "e": 28940, "s": 28938, "text": "R" }, { "code": "# creating a dataframe data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print(\"Original DataFrame\")print(data_frame) data_frame$col3 = with(data_frame, ifelse(col1>4,\"cond1 satisfied\", ifelse(col2 %in% c(\"A\",\"C\"), \"cond2 satisifed\", \"both failed\"))) print(\"Modified DataFrame\")print(data_frame)", "e": 29378, "s": 28940, "text": null }, { "code": null, "e": 29385, "s": 29378, "text": "Output" }, { "code": null, "e": 29851, "s": 29385, "text": "[1] \"Original DataFrame\" \ncol1 col2 \n1 1 A \n2 2 B \n3 3 C \n4 4 A \n5 5 B \n6 6 C \n7 7 A \n8 8 B \n9 9 C \n[1] \"Modified DataFrame\"\ncol1 col2 col3 \n1 1 A cond2 satisfied \n2 2 B both failed \n3 3 C cond2 satisfied \n4 4 A cond2 satisfied \n5 5 B cond1 satisfied \n6 6 C cond1 satisfied \n7 7 A cond1 satisfied \n8 8 B cond1 satisfied \n9 9 C cond1 satisfied" }, { "code": null, "e": 29858, "s": 29851, "text": "Picked" }, { "code": null, "e": 29867, "s": 29858, "text": "R-basics" }, { "code": null, "e": 29878, "s": 29867, "text": "R Language" }, { "code": null, "e": 29976, "s": 29878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30028, "s": 29976, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30063, "s": 30028, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30101, "s": 30063, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30159, "s": 30101, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30202, "s": 30159, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30251, "s": 30202, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30288, "s": 30251, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30314, "s": 30288, "text": "Time Series Analysis in R" }, { "code": null, "e": 30331, "s": 30314, "text": "R - if statement" } ]
How to create a Circular image view in Android without using any library? - GeeksforGeeks
07 Aug, 2021 This article aims to help in how to make a circular image view on an image using the Android App. A simple circular image view can be made with white border and transparent content with shape without using any library. Below are steps on how to do so: Step 1: Creating the layout of the circular image view Create a new drawable resource file in the drawable directory which defines the shape of image view that is a circle. Here filename is circular.xml XML <?xml version="1.0" encoding="utf-8"?> <!--res/drawable/circular.xml--> <!--defines the circular shape and its properties--><shape xmlns:android="http://schemas.android.com/apk/res/android" android:innerRadius="0dp" android:shape="ring" android:thicknessRatio="2.0" android:useLevel="false" > <solid android:color="@android:color/transparent" /> <stroke android:width="9dp" android:color="@android:color/white" /></shape> Step 2: Next step is to make a layerlist drawable so that it can act as background to your imageview. Create a new XML file in drawable directory with name image.xml Here filename is image.xml XML <?xml version="1.0" encoding="utf-8"?> <!--res/drawable/image.xml--><!--define layer-list--><layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <!--set image to be shown on circular image view--> <item android:drawable="@drawable/ic_launcher"/> <item android:drawable="@drawable/circular"/></layer-list> Step 3: Creating the activity_main.xml XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" > <!--put image.xml as background to your image view--> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/image"/></RelativeLayout> Step 4: Creating the backend MainActivity.java file Java package com.geeksforgeeks.circularimageview; import android.support.v7.app.AppCompatActivity;import android.graphics.drawable.ColorDrawable;import java.io.IOException; public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar; actionBar = getSupportActionBar(); ColorDrawable colorDrawable = new ColorDrawable( Color.parseColor("#0F9D58")); actionBar.setBackgroundDrawable(colorDrawable); Toast.makeText( MainActivity.this, "Circular Image View " + "without using any library", Toast.LENGTH_LONG) .show(); }} Output: Circular image view Activity containing Circular image simmytarika5 android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 26111, "s": 26083, "text": "\n07 Aug, 2021" }, { "code": null, "e": 26331, "s": 26111, "text": "This article aims to help in how to make a circular image view on an image using the Android App. A simple circular image view can be made with white border and transparent content with shape without using any library. " }, { "code": null, "e": 26365, "s": 26331, "text": "Below are steps on how to do so: " }, { "code": null, "e": 26538, "s": 26365, "text": "Step 1: Creating the layout of the circular image view Create a new drawable resource file in the drawable directory which defines the shape of image view that is a circle." }, { "code": null, "e": 26568, "s": 26538, "text": "Here filename is circular.xml" }, { "code": null, "e": 26572, "s": 26568, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--res/drawable/circular.xml--> <!--defines the circular shape and its properties--><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:innerRadius=\"0dp\" android:shape=\"ring\" android:thicknessRatio=\"2.0\" android:useLevel=\"false\" > <solid android:color=\"@android:color/transparent\" /> <stroke android:width=\"9dp\" android:color=\"@android:color/white\" /></shape>", "e": 27037, "s": 26572, "text": null }, { "code": null, "e": 27204, "s": 27037, "text": "Step 2: Next step is to make a layerlist drawable so that it can act as background to your imageview. Create a new XML file in drawable directory with name image.xml " }, { "code": null, "e": 27231, "s": 27204, "text": "Here filename is image.xml" }, { "code": null, "e": 27235, "s": 27231, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--res/drawable/image.xml--><!--define layer-list--><layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" > <!--set image to be shown on circular image view--> <item android:drawable=\"@drawable/ic_launcher\"/> <item android:drawable=\"@drawable/circular\"/></layer-list>", "e": 27573, "s": 27235, "text": null }, { "code": null, "e": 27612, "s": 27573, "text": "Step 3: Creating the activity_main.xml" }, { "code": null, "e": 27616, "s": 27612, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" android:gravity=\"center\" > <!--put image.xml as background to your image view--> <ImageView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"@drawable/image\"/></RelativeLayout>", "e": 28060, "s": 27616, "text": null }, { "code": null, "e": 28112, "s": 28060, "text": "Step 4: Creating the backend MainActivity.java file" }, { "code": null, "e": 28117, "s": 28112, "text": "Java" }, { "code": "package com.geeksforgeeks.circularimageview; import android.support.v7.app.AppCompatActivity;import android.graphics.drawable.ColorDrawable;import java.io.IOException; public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar; actionBar = getSupportActionBar(); ColorDrawable colorDrawable = new ColorDrawable( Color.parseColor(\"#0F9D58\")); actionBar.setBackgroundDrawable(colorDrawable); Toast.makeText( MainActivity.this, \"Circular Image View \" + \"without using any library\", Toast.LENGTH_LONG) .show(); }}", "e": 28974, "s": 28117, "text": null }, { "code": null, "e": 29004, "s": 28974, "text": "Output: Circular image view " }, { "code": null, "e": 29039, "s": 29004, "text": "Activity containing Circular image" }, { "code": null, "e": 29054, "s": 29041, "text": "simmytarika5" }, { "code": null, "e": 29062, "s": 29054, "text": "android" }, { "code": null, "e": 29075, "s": 29062, "text": "Android-View" }, { "code": null, "e": 29083, "s": 29075, "text": "Android" }, { "code": null, "e": 29088, "s": 29083, "text": "Java" }, { "code": null, "e": 29093, "s": 29088, "text": "Java" }, { "code": null, "e": 29101, "s": 29093, "text": "Android" }, { "code": null, "e": 29199, "s": 29101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29257, "s": 29199, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29295, "s": 29257, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29338, "s": 29295, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29371, "s": 29338, "text": "Services in Android with Example" }, { "code": null, "e": 29402, "s": 29371, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29417, "s": 29402, "text": "Arrays in Java" }, { "code": null, "e": 29461, "s": 29417, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29483, "s": 29461, "text": "For-each loop in Java" }, { "code": null, "e": 29534, "s": 29483, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Android Package Name vs Application ID - GeeksforGeeks
23 Jul, 2021 As an Android Developer, you should know that the Package Name that you choose for your app is very important. We are referring to the Package Name of the application which we declare in the Manifest.xml rather than the Java package name (although they will be identical). But there is a difference between the Package Name and the Application ID. In this article, we’ll look at the difference between the two. Every Android app has a unique application ID that looks like a Java package name, such as com.example.myapplication. This ID uniquely identifies your app in Google Play Store. If you want to upload a new version of your app, the application ID (and the certificate you sign it with) must be the same as the original APK—if you change the application ID, Google Play Store treats the APK as a completely different app. Your application ID is defined with the applicationId property in your module’s build.gradle file, as shown below: Java android { defaultConfig { applicationId "com.example.myapplication" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" } ...} The applicationId exactly matches the Java-style package name you chose during project setup in android studio. However, the application ID and package name are independent of each other beyond this point. You can change your code’s package name (your code namespace) and it will not affect the application ID, and vice versa (though, again, you should not change your application ID once you publish your app). However, changing the package name has other consequences you should be aware of, so see the section about how to change the package name. Note: Context.getPackageName() method returns your application ID. For a large project, the cost of modifying the package name is too high and almost undesirable. And often there will be different versions of a project, such as paid version and free version. In this way, the package name of the final apk can be changed by simply modifying the applicationId in app/build.gradle, so that it is a different app for Android phones. At the same time, it does not affect the code consistency during development and compilation. The package name is defined in AndroidManifest.xml at the beginning of the creation of an Android application project. The package name is just to organize your code. Although your project’s package name matches the application ID by default, you can change it. However, if you want to change your package name, be aware that the package name (as defined by your project directory structure) should always match the package attribute in the AndroidManifest.xml file as shown below. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication" android:versionCode="1" android:versionName="1.0" > The Android build tools use the package attribute for two things: It uses this name as the namespace for your app’s generated R.java class. It uses it to resolve any relative class names that are declared in the manifest file. Example: With the above manifest, an activity declared as <activity android:name=”.MainActivity”> it will actually be parsed as com.example.myapplication.MainActivity. Note: package attribute should always match your project’s base package name where you keep your activities and other app code. Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Android Listview in Java with Example Flexbox-Layout in Android How to Save Data to the Firebase Realtime Database in Android? How to Change the Background Color After Clicking the Button in Android?
[ { "code": null, "e": 26381, "s": 26353, "text": "\n23 Jul, 2021" }, { "code": null, "e": 26848, "s": 26381, "text": "As an Android Developer, you should know that the Package Name that you choose for your app is very important. We are referring to the Package Name of the application which we declare in the Manifest.xml rather than the Java package name (although they will be identical). But there is a difference between the Package Name and the Application ID. In this article, we’ll look at the difference between the two. " }, { "code": null, "e": 27382, "s": 26848, "text": "Every Android app has a unique application ID that looks like a Java package name, such as com.example.myapplication. This ID uniquely identifies your app in Google Play Store. If you want to upload a new version of your app, the application ID (and the certificate you sign it with) must be the same as the original APK—if you change the application ID, Google Play Store treats the APK as a completely different app. Your application ID is defined with the applicationId property in your module’s build.gradle file, as shown below:" }, { "code": null, "e": 27387, "s": 27382, "text": "Java" }, { "code": "android { defaultConfig { applicationId \"com.example.myapplication\" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName \"1.0\" } ...}", "e": 27575, "s": 27387, "text": null }, { "code": null, "e": 28126, "s": 27575, "text": "The applicationId exactly matches the Java-style package name you chose during project setup in android studio. However, the application ID and package name are independent of each other beyond this point. You can change your code’s package name (your code namespace) and it will not affect the application ID, and vice versa (though, again, you should not change your application ID once you publish your app). However, changing the package name has other consequences you should be aware of, so see the section about how to change the package name." }, { "code": null, "e": 28193, "s": 28126, "text": "Note: Context.getPackageName() method returns your application ID." }, { "code": null, "e": 28651, "s": 28193, "text": "For a large project, the cost of modifying the package name is too high and almost undesirable. And often there will be different versions of a project, such as paid version and free version. In this way, the package name of the final apk can be changed by simply modifying the applicationId in app/build.gradle, so that it is a different app for Android phones. At the same time, it does not affect the code consistency during development and compilation. " }, { "code": null, "e": 29134, "s": 28651, "text": "The package name is defined in AndroidManifest.xml at the beginning of the creation of an Android application project. The package name is just to organize your code. Although your project’s package name matches the application ID by default, you can change it. However, if you want to change your package name, be aware that the package name (as defined by your project directory structure) should always match the package attribute in the AndroidManifest.xml file as shown below." }, { "code": null, "e": 29138, "s": 29134, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.myapplication\" android:versionCode=\"1\" android:versionName=\"1.0\" >", "e": 29346, "s": 29138, "text": null }, { "code": null, "e": 29412, "s": 29346, "text": "The Android build tools use the package attribute for two things:" }, { "code": null, "e": 29487, "s": 29412, "text": "It uses this name as the namespace for your app’s generated R.java class. " }, { "code": null, "e": 29574, "s": 29487, "text": "It uses it to resolve any relative class names that are declared in the manifest file." }, { "code": null, "e": 29742, "s": 29574, "text": "Example: With the above manifest, an activity declared as <activity android:name=”.MainActivity”> it will actually be parsed as com.example.myapplication.MainActivity." }, { "code": null, "e": 29870, "s": 29742, "text": "Note: package attribute should always match your project’s base package name where you keep your activities and other app code." }, { "code": null, "e": 29877, "s": 29870, "text": "Picked" }, { "code": null, "e": 29885, "s": 29877, "text": "Android" }, { "code": null, "e": 29893, "s": 29885, "text": "Android" }, { "code": null, "e": 29991, "s": 29893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30029, "s": 29991, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30068, "s": 30029, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30118, "s": 30068, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30169, "s": 30118, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30211, "s": 30169, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30251, "s": 30211, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 30289, "s": 30251, "text": "Android Listview in Java with Example" }, { "code": null, "e": 30315, "s": 30289, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 30378, "s": 30315, "text": "How to Save Data to the Firebase Realtime Database in Android?" } ]
How to add a tooltip to a div using JavaScript? - GeeksforGeeks
31 Jul, 2019 Adding tooltip to div element displays a pop-up, whenever the mouse hovers over div. Syntax: < div title = "" > </div> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> Tooltip Methods: .tooltip(“show”): It is used to show the tooltip. .tooltip(“hide”): It is used to hide the tooltip. .tooltip(options): It is used to activate the tooltip. .tooltip(“destroy”): It is used to destroy the tooltip. .tooltip(“toggle”): It is used to toggle the tooltip. Tooltip Events: show.bs.tooltip: Tooltip is about to show on the screen. shown.bs.tooltip: Tooltip is fully shown on the screen. hide.bs.tooltip: Tooltip is about to hide. hidden.bs.tooltip: Tooltip is fully hidden. Return Value: It returns a pop-up when user hovers over the div element. Example 1: <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Example </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script></head> <body> <div class="container" title="ToolTip"> <h1 class="text-center "> GeeksforGeeks </h1> <h2 class="h4 text-center"> A Computer Science Portal for Geeks </h2> </div> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> </body> </html> Output:Before hovering over div: After hovering over div: Example 2: <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap Example </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script></head> <body> <div class="container" title="Wonders of the World"> <h1 class="text-center "> GeeksforGeeks </h1> <h2 class="h4"> List of 7 Wonders of the World </h2> <ul> <li>Great Wall of China</li> <li>Petra</li> <li>The Colosseum</li> <li>Chichen Itza</li> <li>Machu Picchu</li> <li>Taj Mahal</li> <li>Christ the Redeemer</li> </ul> </div> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> </body> </html> Output:Before hovering over div: After hovering over div: Browser Support: Browsers which support Tooltip: Opera Internet Explorer Safari Google Chrome Firefox JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26189, "s": 26161, "text": "\n31 Jul, 2019" }, { "code": null, "e": 26274, "s": 26189, "text": "Adding tooltip to div element displays a pop-up, whenever the mouse hovers over div." }, { "code": null, "e": 26282, "s": 26274, "text": "Syntax:" }, { "code": "< div title = \"\" > </div> <script> $(document).ready(function() { $('[data-toggle=\"tooltip\"]').tooltip(); }); </script>", "e": 26415, "s": 26282, "text": null }, { "code": null, "e": 26432, "s": 26415, "text": "Tooltip Methods:" }, { "code": null, "e": 26482, "s": 26432, "text": ".tooltip(“show”): It is used to show the tooltip." }, { "code": null, "e": 26532, "s": 26482, "text": ".tooltip(“hide”): It is used to hide the tooltip." }, { "code": null, "e": 26587, "s": 26532, "text": ".tooltip(options): It is used to activate the tooltip." }, { "code": null, "e": 26643, "s": 26587, "text": ".tooltip(“destroy”): It is used to destroy the tooltip." }, { "code": null, "e": 26697, "s": 26643, "text": ".tooltip(“toggle”): It is used to toggle the tooltip." }, { "code": null, "e": 26713, "s": 26697, "text": "Tooltip Events:" }, { "code": null, "e": 26770, "s": 26713, "text": "show.bs.tooltip: Tooltip is about to show on the screen." }, { "code": null, "e": 26826, "s": 26770, "text": "shown.bs.tooltip: Tooltip is fully shown on the screen." }, { "code": null, "e": 26869, "s": 26826, "text": "hide.bs.tooltip: Tooltip is about to hide." }, { "code": null, "e": 26913, "s": 26869, "text": "hidden.bs.tooltip: Tooltip is fully hidden." }, { "code": null, "e": 26986, "s": 26913, "text": "Return Value: It returns a pop-up when user hovers over the div element." }, { "code": null, "e": 26997, "s": 26986, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Example </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\" title=\"ToolTip\"> <h1 class=\"text-center \"> GeeksforGeeks </h1> <h2 class=\"h4 text-center\"> A Computer Science Portal for Geeks </h2> </div> <script> $(document).ready(function() { $('[data-toggle=\"tooltip\"]').tooltip(); }); </script> </body> </html>", "e": 27899, "s": 26997, "text": null }, { "code": null, "e": 27932, "s": 27899, "text": "Output:Before hovering over div:" }, { "code": null, "e": 27957, "s": 27932, "text": "After hovering over div:" }, { "code": null, "e": 27968, "s": 27957, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap Example </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\" title=\"Wonders of the World\"> <h1 class=\"text-center \"> GeeksforGeeks </h1> <h2 class=\"h4\"> List of 7 Wonders of the World </h2> <ul> <li>Great Wall of China</li> <li>Petra</li> <li>The Colosseum</li> <li>Chichen Itza</li> <li>Machu Picchu</li> <li>Taj Mahal</li> <li>Christ the Redeemer</li> </ul> </div> <script> $(document).ready(function() { $('[data-toggle=\"tooltip\"]').tooltip(); }); </script> </body> </html>", "e": 29124, "s": 27968, "text": null }, { "code": null, "e": 29157, "s": 29124, "text": "Output:Before hovering over div:" }, { "code": null, "e": 29182, "s": 29157, "text": "After hovering over div:" }, { "code": null, "e": 29231, "s": 29182, "text": "Browser Support: Browsers which support Tooltip:" }, { "code": null, "e": 29237, "s": 29231, "text": "Opera" }, { "code": null, "e": 29255, "s": 29237, "text": "Internet Explorer" }, { "code": null, "e": 29262, "s": 29255, "text": "Safari" }, { "code": null, "e": 29276, "s": 29262, "text": "Google Chrome" }, { "code": null, "e": 29284, "s": 29276, "text": "Firefox" }, { "code": null, "e": 29300, "s": 29284, "text": "JavaScript-Misc" }, { "code": null, "e": 29307, "s": 29300, "text": "Picked" }, { "code": null, "e": 29318, "s": 29307, "text": "JavaScript" }, { "code": null, "e": 29335, "s": 29318, "text": "Web Technologies" }, { "code": null, "e": 29433, "s": 29335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29473, "s": 29433, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29518, "s": 29473, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29579, "s": 29518, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29651, "s": 29579, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29697, "s": 29651, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29737, "s": 29697, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29770, "s": 29737, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29815, "s": 29770, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29858, "s": 29815, "text": "How to fetch data from an API in ReactJS ?" } ]
MySQLi - Delete Query
If you want to delete a record from any MySQL table, then you can use the SQL command DELETE FROM. You can use this command at the mysql> prompt as well as in any script like PHP. The following code block has a generic SQL syntax of the DELETE command to delete data from a MySQL table. DELETE FROM table_name [WHERE Clause] If the WHERE clause is not specified, then all the records will be deleted from the given MySQL table. If the WHERE clause is not specified, then all the records will be deleted from the given MySQL table. You can specify any condition using the WHERE clause. You can specify any condition using the WHERE clause. You can delete records in a single table at a time. You can delete records in a single table at a time. The WHERE clause is very useful when you want to delete selected rows in a table. This will use the SQL DELETE command with the WHERE clause to delete selected data into the MySQL table – tutorials_tbl. The following example will delete a record from the tutorial_tbl whose tutorial_id is 3. root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> DELETE FROM tutorials_tbl WHERE tutorial_id=3; Query OK, 1 row affected (0.23 sec) mysql> PHP uses mysqli query() or mysql_query() function to delete records in a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqli→query($sql,$resultmode) $sql Required - SQL query to delete records in a MySQL table. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. Try the following example to delete a record in a table − Copy and paste the following example as mysql_example.php − <html> <head> <title>Deleting MySQL Table record</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli→connect_errno ) { printf("Connect failed: %s<br />", $mysqli→connect_error); exit(); } printf('Connected successfully.<br />'); if ($mysqli→query('DELETE FROM tutorials_tbl where tutorial_id = 4')) { printf("Table tutorials_tbl record deleted successfully.<br />"); } if ($mysqli→errno) { printf("Could not delete record from table: %s<br />", $mysqli→error); } $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl"; $result = $mysqli→query($sql); if ($result→num_rows > 0) { while($row = $result→fetch_assoc()) { printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqli→close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script. Connected successfully. Table tutorials_tbl record deleted successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021 Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021 14 Lectures 1.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2443, "s": 2263, "text": "If you want to delete a record from any MySQL table, then you can use the SQL command DELETE FROM. You can use this command at the mysql> prompt as well as in any script like PHP." }, { "code": null, "e": 2550, "s": 2443, "text": "The following code block has a generic SQL syntax of the DELETE command to delete data from a MySQL table." }, { "code": null, "e": 2589, "s": 2550, "text": "DELETE FROM table_name [WHERE Clause]\n" }, { "code": null, "e": 2692, "s": 2589, "text": "If the WHERE clause is not specified, then all the records will be deleted from the given MySQL table." }, { "code": null, "e": 2795, "s": 2692, "text": "If the WHERE clause is not specified, then all the records will be deleted from the given MySQL table." }, { "code": null, "e": 2849, "s": 2795, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 2903, "s": 2849, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 2955, "s": 2903, "text": "You can delete records in a single table at a time." }, { "code": null, "e": 3007, "s": 2955, "text": "You can delete records in a single table at a time." }, { "code": null, "e": 3089, "s": 3007, "text": "The WHERE clause is very useful when you want to delete selected rows in a table." }, { "code": null, "e": 3210, "s": 3089, "text": "This will use the SQL DELETE command with the WHERE clause to delete selected data into the MySQL table – tutorials_tbl." }, { "code": null, "e": 3299, "s": 3210, "text": "The following example will delete a record from the tutorial_tbl whose tutorial_id is 3." }, { "code": null, "e": 3499, "s": 3299, "text": "root@host# mysql -u root -p password;\nEnter password:*******\n\nmysql> use TUTORIALS;\nDatabase changed\n\nmysql> DELETE FROM tutorials_tbl WHERE tutorial_id=3;\nQuery OK, 1 row affected (0.23 sec)\n\nmysql>" }, { "code": null, "e": 3669, "s": 3499, "text": "PHP uses mysqli query() or mysql_query() function to delete records in a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 3702, "s": 3669, "text": "$mysqli→query($sql,$resultmode)\n" }, { "code": null, "e": 3707, "s": 3702, "text": "$sql" }, { "code": null, "e": 3764, "s": 3707, "text": "Required - SQL query to delete records in a MySQL table." }, { "code": null, "e": 3776, "s": 3764, "text": "$resultmode" }, { "code": null, "e": 3924, "s": 3776, "text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used." }, { "code": null, "e": 3982, "s": 3924, "text": "Try the following example to delete a record in a table −" }, { "code": null, "e": 4042, "s": 3982, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 5521, "s": 4042, "text": "<html>\n <head>\n <title>Deleting MySQL Table record</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli→connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli→connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n\t\t \n if ($mysqli→query('DELETE FROM tutorials_tbl where tutorial_id = 4')) {\n printf(\"Table tutorials_tbl record deleted successfully.<br />\");\n }\n if ($mysqli→errno) {\n printf(\"Could not delete record from table: %s<br />\", $mysqli→error);\n }\n \n $sql = \"SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl\";\n\t\t \n $result = $mysqli→query($sql);\n \n if ($result→num_rows > 0) {\n while($row = $result→fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli→close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 5686, "s": 5521, "text": "Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script." }, { "code": null, "e": 5986, "s": 5686, "text": "Connected successfully.\nTable tutorials_tbl record deleted successfully.\nId: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021\nId: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021\nId: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021\nId: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021\n" }, { "code": null, "e": 6021, "s": 5986, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6044, "s": 6021, "text": " Stone River ELearning" }, { "code": null, "e": 6051, "s": 6044, "text": " Print" }, { "code": null, "e": 6062, "s": 6051, "text": " Add Notes" } ]
Finding Patterns In Data Using NMF | by Himanshu Sharma | Towards Data Science
NLP-Natural Language Processing is one of the hottest topics in the field of Artificial Intelligence. It helps in building applications like chatbots, voice assistants, sentiment analysis, recommendation engines, etc. It is a budding field where most related companies are investing and researching to create next-gen voice assistants. One of the most important algorithms of NLP is Topic modeling that helps in outlining the quantitative trend in text datasets and works on finding out the summary features of the dataset. In other words, it is a kind of feature engineering where we are finding out the most important feature in the dataset. NMF is an unsupervised topic modeling technique where no training data or data labels are provided. It factorizes high dimension data into lower dimension representation. Ecco is an open-source Python library that provides multiple features for exploring and explaining NLP models using interactive visualizations. In this article, we will use Ecco to perform NMF and create an interactive visualization for it. Let’s get started... We will start by installing an Ecco using pip. The command given below will do that. pip install ecco In this step, we will import the required libraries and functions to create an NMF visualization. We will also load the pre-trained Bert Model from eeco. import eccolm = ecco.from_pretrained('bert-base-uncased', activations=True) In this step, we will tokenize the data that we will be using for NMF Visualization. You can use any text that you want, I am taking an article on Sachin Tendulkar. text = ''' Sachin Tendulkar has been the most complete batsman of his time, the most prolific runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting was based on the purest principles: perfect balance, economy of movement, precision in stroke-making, and that intangible quality given only to geniuses - anticipation. If he didn't have a signature stroke - the upright, back-foot punch comes close - it's because he was equally proficient at each of the full range of orthodox shots (and plenty of improvised ones as well) and can pull them out at will.There were no apparent weaknesses in Tendulkar's game. He could score all around the wicket, off both front foot and back, could tune his technique to suit every condition, temper his game to suit every situation, and made runs in all parts of the world in all conditions.Some of his finest performances came against Australia, the overwhelmingly dominant team of his era. His century as a 19-year-old on a lightning-fast pitch at the WACA is considered one of the best innings ever to have been played in Australia. A few years later he received the ultimate compliment from the ultimate batsman: Don Bradman confided to his wife that Tendulkar reminded him of himself.Blessed with the keenest of cricket minds, and armed with a loathing for losing, Tendulkar set about doing what it took to become one of the best batsmen in the world. His greatness was established early: he was only 16 when he made his Test debut. He was hit on the mouth by Waqar Younis but continued to bat, in a blood-soaked shirt. His first Test hundred, a match-saving one at Old Trafford, came when he was 17, and he had 16 Test hundreds before he turned 25. In 2000 he became the first batsman to have scored 50 international hundreds, in 2008 he passed Brian Lara as the leading Test run-scorer, and in the years after, he went past 13,000 Test runs 30,000 international runs, and 50 Test hundreds. '''inputs = lm.tokenizer([text], return_tensors="pt")output = lm(inputs) This is the final step where we will create the visualization for NMF, we will use two types of factorization i.e. Factorization of all the layers and Factorization of the First Layer. #All layersnmf_1 = output.run_nmf(n_components=10)nmf_1.explore() #First Layernmf_2 = output.run_nmf(n_components=8, from_layer=0, to_layer=1)nmf_2.explore() Here we can clearly visualize the NMF visualization created using just a single line of code. These visualizations are interactive and highly explainable. We can clearly analyze the different topics and weights of NMF in the visualization. Go ahead try this with different datasets and create beautiful visualization. In case you find any difficulty please let me know in the response section. This article is in collaboration with Piyush Ingale. Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
[ { "code": null, "e": 508, "s": 172, "text": "NLP-Natural Language Processing is one of the hottest topics in the field of Artificial Intelligence. It helps in building applications like chatbots, voice assistants, sentiment analysis, recommendation engines, etc. It is a budding field where most related companies are investing and researching to create next-gen voice assistants." }, { "code": null, "e": 816, "s": 508, "text": "One of the most important algorithms of NLP is Topic modeling that helps in outlining the quantitative trend in text datasets and works on finding out the summary features of the dataset. In other words, it is a kind of feature engineering where we are finding out the most important feature in the dataset." }, { "code": null, "e": 987, "s": 816, "text": "NMF is an unsupervised topic modeling technique where no training data or data labels are provided. It factorizes high dimension data into lower dimension representation." }, { "code": null, "e": 1131, "s": 987, "text": "Ecco is an open-source Python library that provides multiple features for exploring and explaining NLP models using interactive visualizations." }, { "code": null, "e": 1228, "s": 1131, "text": "In this article, we will use Ecco to perform NMF and create an interactive visualization for it." }, { "code": null, "e": 1249, "s": 1228, "text": "Let’s get started..." }, { "code": null, "e": 1334, "s": 1249, "text": "We will start by installing an Ecco using pip. The command given below will do that." }, { "code": null, "e": 1351, "s": 1334, "text": "pip install ecco" }, { "code": null, "e": 1505, "s": 1351, "text": "In this step, we will import the required libraries and functions to create an NMF visualization. We will also load the pre-trained Bert Model from eeco." }, { "code": null, "e": 1581, "s": 1505, "text": "import eccolm = ecco.from_pretrained('bert-base-uncased', activations=True)" }, { "code": null, "e": 1746, "s": 1581, "text": "In this step, we will tokenize the data that we will be using for NMF Visualization. You can use any text that you want, I am taking an article on Sachin Tendulkar." }, { "code": null, "e": 3792, "s": 1746, "text": "text = ''' Sachin Tendulkar has been the most complete batsman of his time, the most prolific runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting was based on the purest principles: perfect balance, economy of movement, precision in stroke-making, and that intangible quality given only to geniuses - anticipation. If he didn't have a signature stroke - the upright, back-foot punch comes close - it's because he was equally proficient at each of the full range of orthodox shots (and plenty of improvised ones as well) and can pull them out at will.There were no apparent weaknesses in Tendulkar's game. He could score all around the wicket, off both front foot and back, could tune his technique to suit every condition, temper his game to suit every situation, and made runs in all parts of the world in all conditions.Some of his finest performances came against Australia, the overwhelmingly dominant team of his era. His century as a 19-year-old on a lightning-fast pitch at the WACA is considered one of the best innings ever to have been played in Australia. A few years later he received the ultimate compliment from the ultimate batsman: Don Bradman confided to his wife that Tendulkar reminded him of himself.Blessed with the keenest of cricket minds, and armed with a loathing for losing, Tendulkar set about doing what it took to become one of the best batsmen in the world. His greatness was established early: he was only 16 when he made his Test debut. He was hit on the mouth by Waqar Younis but continued to bat, in a blood-soaked shirt. His first Test hundred, a match-saving one at Old Trafford, came when he was 17, and he had 16 Test hundreds before he turned 25. In 2000 he became the first batsman to have scored 50 international hundreds, in 2008 he passed Brian Lara as the leading Test run-scorer, and in the years after, he went past 13,000 Test runs 30,000 international runs, and 50 Test hundreds. '''inputs = lm.tokenizer([text], return_tensors=\"pt\")output = lm(inputs)" }, { "code": null, "e": 3977, "s": 3792, "text": "This is the final step where we will create the visualization for NMF, we will use two types of factorization i.e. Factorization of all the layers and Factorization of the First Layer." }, { "code": null, "e": 4043, "s": 3977, "text": "#All layersnmf_1 = output.run_nmf(n_components=10)nmf_1.explore()" }, { "code": null, "e": 4135, "s": 4043, "text": "#First Layernmf_2 = output.run_nmf(n_components=8, from_layer=0, to_layer=1)nmf_2.explore()" }, { "code": null, "e": 4375, "s": 4135, "text": "Here we can clearly visualize the NMF visualization created using just a single line of code. These visualizations are interactive and highly explainable. We can clearly analyze the different topics and weights of NMF in the visualization." }, { "code": null, "e": 4529, "s": 4375, "text": "Go ahead try this with different datasets and create beautiful visualization. In case you find any difficulty please let me know in the response section." }, { "code": null, "e": 4582, "s": 4529, "text": "This article is in collaboration with Piyush Ingale." } ]
Python - Tuple Exercises
Now you have learned a lot about tuples, and how to use them in Python. Are you ready for a test? Try to insert the missing part to make the code work as expected: Print the first item in the fruits tuple. fruits = ("apple", "banana", "cherry") print() Go to the Exercise section and test all of our Python Tuple Exercises: Python Tuple Exercises We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 72, "s": 0, "text": "Now you have learned a lot about tuples, and how to use them in Python." }, { "code": null, "e": 98, "s": 72, "text": "Are you ready for a test?" }, { "code": null, "e": 164, "s": 98, "text": "Try to insert the missing part to make the code work as expected:" }, { "code": null, "e": 206, "s": 164, "text": "Print the first item in the fruits tuple." }, { "code": null, "e": 254, "s": 206, "text": "fruits = (\"apple\", \"banana\", \"cherry\")\nprint()\n" }, { "code": null, "e": 325, "s": 254, "text": "Go to the Exercise section and test all of our Python Tuple Exercises:" }, { "code": null, "e": 350, "s": 325, "text": "\nPython Tuple Exercises\n" }, { "code": null, "e": 383, "s": 350, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 425, "s": 383, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 532, "s": 425, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 551, "s": 532, "text": "[email protected]" } ]
How can I set a table in a JPanel in Java?
Let us first set rows and columns for our table − String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; Now, set the above in a table as rows and columns − JTable table = new JTable(rec, header); Add the table in the panel − JPanel panel = new JPanel(); panel.add(new JScrollPane(table)); The following is an example to create a table in a panel − package my; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP)); String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } } This will produce the following output −
[ { "code": null, "e": 1112, "s": 1062, "text": "Let us first set rows and columns for our table −" }, { "code": null, "e": 1348, "s": 1112, "text": "String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n};\nString[] header = { \"Rank\", \"Player\", \"Country\" };" }, { "code": null, "e": 1400, "s": 1348, "text": "Now, set the above in a table as rows and columns −" }, { "code": null, "e": 1440, "s": 1400, "text": "JTable table = new JTable(rec, header);" }, { "code": null, "e": 1469, "s": 1440, "text": "Add the table in the panel −" }, { "code": null, "e": 1533, "s": 1469, "text": "JPanel panel = new JPanel();\npanel.add(new JScrollPane(table));" }, { "code": null, "e": 1592, "s": 1533, "text": "The following is an example to create a table in a panel −" }, { "code": null, "e": 2557, "s": 1592, "text": "package my;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER, TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2598, "s": 2557, "text": "This will produce the following output −" } ]
C# Program to find the largest element from an array
Declare an array − int[] arr = { 20, 50, -35, 25, 60 }; Now to get the largest element from an array, use the Max() method − arr.Max()); Here is the complete code − Live Demo using System; using System.Linq; class Demo { static void Main() { int[] arr = { 20, 50, -35, 25, 60 }; Console.WriteLine(arr.Max()); } } 60
[ { "code": null, "e": 1081, "s": 1062, "text": "Declare an array −" }, { "code": null, "e": 1118, "s": 1081, "text": "int[] arr = { 20, 50, -35, 25, 60 };" }, { "code": null, "e": 1187, "s": 1118, "text": "Now to get the largest element from an array, use the Max() method −" }, { "code": null, "e": 1199, "s": 1187, "text": "arr.Max());" }, { "code": null, "e": 1227, "s": 1199, "text": "Here is the complete code −" }, { "code": null, "e": 1238, "s": 1227, "text": " Live Demo" }, { "code": null, "e": 1394, "s": 1238, "text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n int[] arr = { 20, 50, -35, 25, 60 };\n Console.WriteLine(arr.Max());\n }\n}" }, { "code": null, "e": 1397, "s": 1394, "text": "60" } ]
How to filter an array in Java
You can use List.removeAll() method to filter an array. import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add("F"); list.add("G"); list.add("H"); List<String> filters = new ArrayList<>(); filters.add("D"); filters.add("E"); filters.add("F"); System.out.println("Original List " + list); list.removeAll(filters); System.out.println("Filtered List " + list); } } Original List [A, B, C, D, E, F, G, H] Filtered List [A, B, C, G, H]
[ { "code": null, "e": 1119, "s": 1062, "text": "You can use List.removeAll() method to filter an array. " }, { "code": null, "e": 1709, "s": 1119, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Tester {\n public static void main(String[] args) {\n List<String> list = new ArrayList<>();\n list.add(\"A\");\n list.add(\"B\");\n list.add(\"C\");\n list.add(\"D\");\n list.add(\"E\");\n list.add(\"F\");\n list.add(\"G\");\n list.add(\"H\");\n List<String> filters = new ArrayList<>();\n filters.add(\"D\");\n filters.add(\"E\");\n filters.add(\"F\");\n System.out.println(\"Original List \" + list);\n list.removeAll(filters);\n System.out.println(\"Filtered List \" + list);\n }\n}" }, { "code": null, "e": 1778, "s": 1709, "text": "Original List [A, B, C, D, E, F, G, H]\nFiltered List [A, B, C, G, H]" } ]
Generating/Expanding your datasets with synthetic data | by Archit Yadav | Towards Data Science
As an ML practitioner or a Data Scientist, it might have been possible when we found ourselves in a situation like “if only we had more data”. There are often times when the dataset that we have is very limited and aren’t sure if the performance of our machine learning model would have been better or worse if given more amount of statistically similar data. We could of course mine more data from the same source that we got our existing data from, but that may not be possible everytime. What if there was a way to create more data from the data that we already have? Data-centric approach is becoming a common and hot topic of discussion these days, with popular names like Andrew Ng advocating the need for having/building AI solutions centered around the data rather than the model itself. Of course, having the correct model is also essential and should be kept in mind as well. The debate over data-centric vs model-centric is an important issue, as we cannot completely favour one approach over the other. Let’s ask ourselves two basic questions - Why should we let an AI, which is essentially a model (a piece of code) expand our dataset, why can’t we just take our existing dataset and do it manually?The ML algo would be generating new data based on our existing data. Isn’t it pointless letting an AI model increase dataset with even more but (sort-of) redundant information, rather than keeping less but more useful information? Why should we let an AI, which is essentially a model (a piece of code) expand our dataset, why can’t we just take our existing dataset and do it manually? The ML algo would be generating new data based on our existing data. Isn’t it pointless letting an AI model increase dataset with even more but (sort-of) redundant information, rather than keeping less but more useful information? The answer to the first question is fairly obvious because when we deal with datasets of size several thousand (even millions), manual intervention becomes next to impossible since it’s difficult to study the entire dataset and extract the important features which essentially make up the dataset. Those extracted features would then need to be replicated in a specific way so as to add more examples to the dataset. An easy way out of this is to hunt for more data. But hunting more often than not isn't easy, more specifically if the project requires a very niche or specific type of dataset. Also, in today’s world with privacy being a big deal, if the data hunting process involves scrapping users’ personal data or identity, then it may not be the most ethical way to do so. As for the second question, that is a bit tricky to answer right away, and it requires some deep reflection. The answer to this question would involve cross-checking the ML algorithm which would be responsible for generating the new data. More often than not, the need to do so depends upon the project requirements and the final outcome. The simplest way to consider this is as follows. Let’s say, we set aside a specific carefully curated test dataset for final testing. Now if the newly generated dataset, combined with the original dataset is able to improve the model within a range of threashold, it would solve our purpose and would be useful enough. Said differently, if our model’s performance improves on our unseen dataset, we could conclude that adding an augmented version of our existing data to the model improved it, and made the system a little more robust to the never-before-seen data. An excellent and detailed read on GANs can be found in a Google Developers blog post, but in very simplistic terms, a Generative Adversarial Network consists of two parties who are trying to compete with each other. One of them is trying to fool the other, and the other is trying to avoid this deception. The two parties are a generator and a discriminator, both neural networks which try to compete with each other in the following fashion: The Generator tries to generate content that is ideally supposed to look like the real content, which can be image, text, or just numerical data in general. The generator is penalised if the discriminator is able to distinguish between real and generated content The discriminator tries to tell apart the generated content and the real content. The discriminator is penalised if it’s not able to distinguish between real and generated content The end goal is for the generator to be able to produce data that looks so close to the real data that the discriminator can no longer avoid the deception, and this leaves us with more data than what we started with. ydata-synthetic is an open-source library for generating synthetic data. Currently, it supports creating regular tabular data, as well as time-series-based data. In this article, we will quickly look at generating a tabular dataset. More specifically, we will use the Credit Card Fraud Detection dataset and generate more data examples. There is an example notebook provided on ydata-synthetic’s repository, which can be opened in Google Colab to follow along in order to synthesize a tabular dataset based on the credit card dataset. Let’s read the dataset and see what coloumns make up this particular dataset We get the following coloumns: Dataset columns: ['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'Amount', 'Class'] Without getting into too many domain-specific details for the time being, these are essentially the features describing credit card transactions. There is a final coloumn in the dataset called ‘Class’, which has a value of 1 in case of fraud and 0 otherwise. The fraud cases are actually very low in this dataset compared to non-fraud, and we would like to increase the dataset for fraud examples. We hence extract only those entries from the dataset which have Class as 1, that is fraud values. We then apply a PowerTransformation in order to make the distribution Gaussian-like. We can then proceed to train our GAN model to make it study and learn about the fraud values. For this example, we’ll use a specific type of GAN model called WGAN-GP (Wasserstein GAN with Gradient Penalty). hyperparameters and training settings are defined in the form of lists and given to our model for training. Finally, we can actually generate data from the trained model by feeding it a matrix of random values as a starter. In order to visualize and compare the generated output, we take any 2 coloumns (say V10 and V17) from g_z and make a scatter plot for multiple epochs’ trained weights. So we see that the values of V17 and V10 had a pattern in our original dataset (“Actual Fraud Data”, left graphs), which the GAN tried to learn from and replicate as best as it could during training and predicting. The final values of V17 and V10 (as well as rest of the other features) at the end of the 60th epoch resemble the original dataset’s values to an extent. The complete practical exercise walkthrough can be found in the Google Colab notebook from the ydata-synthetic repository, also linked previously. We looked at the need to generate synthetic data depending upon our use case and end goal. We got a brief introduction to GAN architecture, and we also made use of ydata-synthetic in order to generate tabular data. In a future post, we could also explore the possibility of generating time series data.
[ { "code": null, "e": 743, "s": 172, "text": "As an ML practitioner or a Data Scientist, it might have been possible when we found ourselves in a situation like “if only we had more data”. There are often times when the dataset that we have is very limited and aren’t sure if the performance of our machine learning model would have been better or worse if given more amount of statistically similar data. We could of course mine more data from the same source that we got our existing data from, but that may not be possible everytime. What if there was a way to create more data from the data that we already have?" }, { "code": null, "e": 1187, "s": 743, "text": "Data-centric approach is becoming a common and hot topic of discussion these days, with popular names like Andrew Ng advocating the need for having/building AI solutions centered around the data rather than the model itself. Of course, having the correct model is also essential and should be kept in mind as well. The debate over data-centric vs model-centric is an important issue, as we cannot completely favour one approach over the other." }, { "code": null, "e": 1229, "s": 1187, "text": "Let’s ask ourselves two basic questions -" }, { "code": null, "e": 1615, "s": 1229, "text": "Why should we let an AI, which is essentially a model (a piece of code) expand our dataset, why can’t we just take our existing dataset and do it manually?The ML algo would be generating new data based on our existing data. Isn’t it pointless letting an AI model increase dataset with even more but (sort-of) redundant information, rather than keeping less but more useful information?" }, { "code": null, "e": 1771, "s": 1615, "text": "Why should we let an AI, which is essentially a model (a piece of code) expand our dataset, why can’t we just take our existing dataset and do it manually?" }, { "code": null, "e": 2002, "s": 1771, "text": "The ML algo would be generating new data based on our existing data. Isn’t it pointless letting an AI model increase dataset with even more but (sort-of) redundant information, rather than keeping less but more useful information?" }, { "code": null, "e": 2782, "s": 2002, "text": "The answer to the first question is fairly obvious because when we deal with datasets of size several thousand (even millions), manual intervention becomes next to impossible since it’s difficult to study the entire dataset and extract the important features which essentially make up the dataset. Those extracted features would then need to be replicated in a specific way so as to add more examples to the dataset. An easy way out of this is to hunt for more data. But hunting more often than not isn't easy, more specifically if the project requires a very niche or specific type of dataset. Also, in today’s world with privacy being a big deal, if the data hunting process involves scrapping users’ personal data or identity, then it may not be the most ethical way to do so." }, { "code": null, "e": 3121, "s": 2782, "text": "As for the second question, that is a bit tricky to answer right away, and it requires some deep reflection. The answer to this question would involve cross-checking the ML algorithm which would be responsible for generating the new data. More often than not, the need to do so depends upon the project requirements and the final outcome." }, { "code": null, "e": 3687, "s": 3121, "text": "The simplest way to consider this is as follows. Let’s say, we set aside a specific carefully curated test dataset for final testing. Now if the newly generated dataset, combined with the original dataset is able to improve the model within a range of threashold, it would solve our purpose and would be useful enough. Said differently, if our model’s performance improves on our unseen dataset, we could conclude that adding an augmented version of our existing data to the model improved it, and made the system a little more robust to the never-before-seen data." }, { "code": null, "e": 3993, "s": 3687, "text": "An excellent and detailed read on GANs can be found in a Google Developers blog post, but in very simplistic terms, a Generative Adversarial Network consists of two parties who are trying to compete with each other. One of them is trying to fool the other, and the other is trying to avoid this deception." }, { "code": null, "e": 4130, "s": 3993, "text": "The two parties are a generator and a discriminator, both neural networks which try to compete with each other in the following fashion:" }, { "code": null, "e": 4393, "s": 4130, "text": "The Generator tries to generate content that is ideally supposed to look like the real content, which can be image, text, or just numerical data in general. The generator is penalised if the discriminator is able to distinguish between real and generated content" }, { "code": null, "e": 4573, "s": 4393, "text": "The discriminator tries to tell apart the generated content and the real content. The discriminator is penalised if it’s not able to distinguish between real and generated content" }, { "code": null, "e": 4790, "s": 4573, "text": "The end goal is for the generator to be able to produce data that looks so close to the real data that the discriminator can no longer avoid the deception, and this leaves us with more data than what we started with." }, { "code": null, "e": 5325, "s": 4790, "text": "ydata-synthetic is an open-source library for generating synthetic data. Currently, it supports creating regular tabular data, as well as time-series-based data. In this article, we will quickly look at generating a tabular dataset. More specifically, we will use the Credit Card Fraud Detection dataset and generate more data examples. There is an example notebook provided on ydata-synthetic’s repository, which can be opened in Google Colab to follow along in order to synthesize a tabular dataset based on the credit card dataset." }, { "code": null, "e": 5402, "s": 5325, "text": "Let’s read the dataset and see what coloumns make up this particular dataset" }, { "code": null, "e": 5433, "s": 5402, "text": "We get the following coloumns:" }, { "code": null, "e": 5657, "s": 5433, "text": "Dataset columns: ['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'Amount', 'Class']" }, { "code": null, "e": 6055, "s": 5657, "text": "Without getting into too many domain-specific details for the time being, these are essentially the features describing credit card transactions. There is a final coloumn in the dataset called ‘Class’, which has a value of 1 in case of fraud and 0 otherwise. The fraud cases are actually very low in this dataset compared to non-fraud, and we would like to increase the dataset for fraud examples." }, { "code": null, "e": 6238, "s": 6055, "text": "We hence extract only those entries from the dataset which have Class as 1, that is fraud values. We then apply a PowerTransformation in order to make the distribution Gaussian-like." }, { "code": null, "e": 6553, "s": 6238, "text": "We can then proceed to train our GAN model to make it study and learn about the fraud values. For this example, we’ll use a specific type of GAN model called WGAN-GP (Wasserstein GAN with Gradient Penalty). hyperparameters and training settings are defined in the form of lists and given to our model for training." }, { "code": null, "e": 6669, "s": 6553, "text": "Finally, we can actually generate data from the trained model by feeding it a matrix of random values as a starter." }, { "code": null, "e": 6837, "s": 6669, "text": "In order to visualize and compare the generated output, we take any 2 coloumns (say V10 and V17) from g_z and make a scatter plot for multiple epochs’ trained weights." }, { "code": null, "e": 7206, "s": 6837, "text": "So we see that the values of V17 and V10 had a pattern in our original dataset (“Actual Fraud Data”, left graphs), which the GAN tried to learn from and replicate as best as it could during training and predicting. The final values of V17 and V10 (as well as rest of the other features) at the end of the 60th epoch resemble the original dataset’s values to an extent." }, { "code": null, "e": 7353, "s": 7206, "text": "The complete practical exercise walkthrough can be found in the Google Colab notebook from the ydata-synthetic repository, also linked previously." } ]
Nearest Power | Practice | GeeksforGeeks
Given two integers N and M you have to find out an integer which is a power of M and is nearest to N. Note: If there are multiple answers possible to, print the greatest number possible. Example 1: Input: N = 6, M = 3 Output: 9 Explanation: Both 3 (31) and 9 (32) are equally near to 6. But 9 is greater, so the Output is 9. Example 2: Input: N = 3, M = 2 Output: 4 Explanation: Both 2 (21) and 4 (22) are equally near to 3. But 4 is greater, so the Output is 4. Your Task: You don't need to read input or print anything. Your task is to complete the function nearestPower() which takes 2 Integers N and M as input and returns the answer. Expected Time Complexity: O(max(log(N),log(M))) Expected Auxiliary Space: O(1) Constraints: 1 <= N,M <= 109 0 amanpandey30071 month ago long long nearestPower(long long N , long long M) { long long ans=1; long long x=M; while(M<N) { ans=M; M=M*x; } if(abs(N-ans)>=abs(M-N)) return M; return ans; } 0 possible2 years ago possible simple#include<bits stdc++.h="">using namespace std;int main() {int t;cin>>t;while(t--){ long long n,m,temp,low,high; cin>>n>>m; temp=floor(log(n)/log(m)); low=pow(m,temp); high=low*m; if(n-low<high-n) cout<<low<<endl;="" else="" cout<<high<<endl;="" }="" return="" 0;="" }<="" code=""> 0 Dr. Pro6 years ago Dr. Pro @GFG Please change the input statement! It says that each test case contains two integers M and N. This implies that M and N will be input in that order but its the other way round. 0 manu agrawal6 years ago manu agrawal http://www.practice.geeksfo... why my code is giving tle it is in O(logn) 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": 426, "s": 238, "text": "Given two integers N and M you have to find out an integer which is a power of M and is nearest to N.\nNote: If there are multiple answers possible to, print the greatest number possible." }, { "code": null, "e": 439, "s": 428, "text": "Example 1:" }, { "code": null, "e": 566, "s": 439, "text": "Input:\nN = 6, M = 3\nOutput:\n9\nExplanation:\nBoth 3 (31) and 9 (32) are equally\nnear to 6. But 9 is greater,\nso the Output is 9." }, { "code": null, "e": 577, "s": 566, "text": "Example 2:" }, { "code": null, "e": 704, "s": 577, "text": "Input:\nN = 3, M = 2\nOutput:\n4\nExplanation:\nBoth 2 (21) and 4 (22) are equally\nnear to 3. But 4 is greater,\nso the Output is 4." }, { "code": null, "e": 882, "s": 706, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function nearestPower() which takes 2 Integers N and M as input and returns the answer." }, { "code": null, "e": 963, "s": 884, "text": "Expected Time Complexity: O(max(log(N),log(M)))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 994, "s": 965, "text": "Constraints:\n1 <= N,M <= 109" }, { "code": null, "e": 996, "s": 994, "text": "0" }, { "code": null, "e": 1022, "s": 996, "text": "amanpandey30071 month ago" }, { "code": null, "e": 1284, "s": 1022, "text": "long long nearestPower(long long N , long long M) { long long ans=1; long long x=M; while(M<N) { ans=M; M=M*x; } if(abs(N-ans)>=abs(M-N)) return M; return ans; }" }, { "code": null, "e": 1286, "s": 1284, "text": "0" }, { "code": null, "e": 1306, "s": 1286, "text": "possible2 years ago" }, { "code": null, "e": 1315, "s": 1306, "text": "possible" }, { "code": null, "e": 1620, "s": 1315, "text": "simple#include<bits stdc++.h=\"\">using namespace std;int main() {int t;cin>>t;while(t--){ long long n,m,temp,low,high; cin>>n>>m; temp=floor(log(n)/log(m)); low=pow(m,temp); high=low*m; if(n-low<high-n) cout<<low<<endl;=\"\" else=\"\" cout<<high<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" }<=\"\" code=\"\">" }, { "code": null, "e": 1622, "s": 1620, "text": "0" }, { "code": null, "e": 1641, "s": 1622, "text": "Dr. Pro6 years ago" }, { "code": null, "e": 1649, "s": 1641, "text": "Dr. Pro" }, { "code": null, "e": 1831, "s": 1649, "text": "@GFG Please change the input statement! It says that each test case contains two integers M and N. This implies that M and N will be input in that order but its the other way round." }, { "code": null, "e": 1833, "s": 1831, "text": "0" }, { "code": null, "e": 1857, "s": 1833, "text": "manu agrawal6 years ago" }, { "code": null, "e": 1870, "s": 1857, "text": "manu agrawal" }, { "code": null, "e": 1901, "s": 1870, "text": "http://www.practice.geeksfo..." }, { "code": null, "e": 1944, "s": 1901, "text": "why my code is giving tle it is in O(logn)" }, { "code": null, "e": 2090, "s": 1944, "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": 2126, "s": 2090, "text": " Login to access your submissions. " }, { "code": null, "e": 2136, "s": 2126, "text": "\nProblem\n" }, { "code": null, "e": 2146, "s": 2136, "text": "\nContest\n" }, { "code": null, "e": 2209, "s": 2146, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2357, "s": 2209, "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": 2565, "s": 2357, "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": 2671, "s": 2565, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Shuffle an Array in Python
Suppose we have an array A, we have to shuffle a set of numbers without duplicates. So if the input is like [1,2,3], then for shuffling, it will be [1,3,2], after resetting, if we shuffle again, it will be [2,3,1] To solve this, we will follow these steps − There will be different methods. these are init(), reset(), shuffle(). These will act like below − There will be different methods. these are init(), reset(), shuffle(). These will act like below − init will be like − init will be like − original := a copy of the given array original := a copy of the given array temp := nums temp := nums indices := a list of numbers from 0 to length of nums – 1 indices := a list of numbers from 0 to length of nums – 1 the reset() will return the original array the reset() will return the original array the shuffle() will be like − the shuffle() will be like − if length of temp is 0, then return empty array if length of temp is 0, then return empty array i := choice randomly one index from indices array, j := choose another index from indices array randomly i := choice randomly one index from indices array, j := choose another index from indices array randomly swap the elements present at index i and j swap the elements present at index i and j return temp return temp another method called getAllPermutation() will take nums, i, initially i = 0, will be like − another method called getAllPermutation() will take nums, i, initially i = 0, will be like − curr := i curr := i if i = length of nums, theninsert a copy of nums array into another array called allreturn if i = length of nums, then insert a copy of nums array into another array called all insert a copy of nums array into another array called all return return for j := curr to length of numsswap elements at index j and curr from numscall getAllPermutation(nums, curr + 1)swap elements at index j and curr from nums for j := curr to length of nums swap elements at index j and curr from nums swap elements at index j and curr from nums call getAllPermutation(nums, curr + 1) call getAllPermutation(nums, curr + 1) swap elements at index j and curr from nums swap elements at index j and curr from nums Let us see the following implementation to get better understanding − Live Demo import random class Solution(object): def __init__(self, nums): self.original = [x for x in nums] self.temp = nums self.indices = [x for x in range(len(nums))] def reset(self): return self.original def shuffle(self): if not len(self.temp): return [] i = random.choice(self.indices) j = random.choice(self.indices) self.temp[i], self.temp[j] = self.temp[j], self.temp[i] return self.temp ob = Solution([1,2,3]) print(ob.shuffle()) print(ob.reset()) print(ob.shuffle()) Initialize with [1,2,3] , then call shuffle(), reset() and shuffle() [2, 1, 3] [1, 2, 3] [2, 3, 1]
[ { "code": null, "e": 1276, "s": 1062, "text": "Suppose we have an array A, we have to shuffle a set of numbers without duplicates. So if the input is like [1,2,3], then for shuffling, it will be [1,3,2], after resetting, if we shuffle again, it will be [2,3,1]" }, { "code": null, "e": 1320, "s": 1276, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1419, "s": 1320, "text": "There will be different methods. these are init(), reset(), shuffle(). These will act like below −" }, { "code": null, "e": 1518, "s": 1419, "text": "There will be different methods. these are init(), reset(), shuffle(). These will act like below −" }, { "code": null, "e": 1538, "s": 1518, "text": "init will be like −" }, { "code": null, "e": 1558, "s": 1538, "text": "init will be like −" }, { "code": null, "e": 1596, "s": 1558, "text": "original := a copy of the given array" }, { "code": null, "e": 1634, "s": 1596, "text": "original := a copy of the given array" }, { "code": null, "e": 1647, "s": 1634, "text": "temp := nums" }, { "code": null, "e": 1660, "s": 1647, "text": "temp := nums" }, { "code": null, "e": 1718, "s": 1660, "text": "indices := a list of numbers from 0 to length of nums – 1" }, { "code": null, "e": 1776, "s": 1718, "text": "indices := a list of numbers from 0 to length of nums – 1" }, { "code": null, "e": 1819, "s": 1776, "text": "the reset() will return the original array" }, { "code": null, "e": 1862, "s": 1819, "text": "the reset() will return the original array" }, { "code": null, "e": 1891, "s": 1862, "text": "the shuffle() will be like −" }, { "code": null, "e": 1920, "s": 1891, "text": "the shuffle() will be like −" }, { "code": null, "e": 1968, "s": 1920, "text": "if length of temp is 0, then return empty array" }, { "code": null, "e": 2016, "s": 1968, "text": "if length of temp is 0, then return empty array" }, { "code": null, "e": 2121, "s": 2016, "text": "i := choice randomly one index from indices array, j := choose another index from indices array randomly" }, { "code": null, "e": 2226, "s": 2121, "text": "i := choice randomly one index from indices array, j := choose another index from indices array randomly" }, { "code": null, "e": 2269, "s": 2226, "text": "swap the elements present at index i and j" }, { "code": null, "e": 2312, "s": 2269, "text": "swap the elements present at index i and j" }, { "code": null, "e": 2324, "s": 2312, "text": "return temp" }, { "code": null, "e": 2336, "s": 2324, "text": "return temp" }, { "code": null, "e": 2429, "s": 2336, "text": "another method called getAllPermutation() will take nums, i, initially i = 0, will be like −" }, { "code": null, "e": 2522, "s": 2429, "text": "another method called getAllPermutation() will take nums, i, initially i = 0, will be like −" }, { "code": null, "e": 2532, "s": 2522, "text": "curr := i" }, { "code": null, "e": 2542, "s": 2532, "text": "curr := i" }, { "code": null, "e": 2633, "s": 2542, "text": "if i = length of nums, theninsert a copy of nums array into another array called allreturn" }, { "code": null, "e": 2661, "s": 2633, "text": "if i = length of nums, then" }, { "code": null, "e": 2719, "s": 2661, "text": "insert a copy of nums array into another array called all" }, { "code": null, "e": 2777, "s": 2719, "text": "insert a copy of nums array into another array called all" }, { "code": null, "e": 2784, "s": 2777, "text": "return" }, { "code": null, "e": 2791, "s": 2784, "text": "return" }, { "code": null, "e": 2947, "s": 2791, "text": "for j := curr to length of numsswap elements at index j and curr from numscall getAllPermutation(nums, curr + 1)swap elements at index j and curr from nums" }, { "code": null, "e": 2979, "s": 2947, "text": "for j := curr to length of nums" }, { "code": null, "e": 3023, "s": 2979, "text": "swap elements at index j and curr from nums" }, { "code": null, "e": 3067, "s": 3023, "text": "swap elements at index j and curr from nums" }, { "code": null, "e": 3106, "s": 3067, "text": "call getAllPermutation(nums, curr + 1)" }, { "code": null, "e": 3145, "s": 3106, "text": "call getAllPermutation(nums, curr + 1)" }, { "code": null, "e": 3189, "s": 3145, "text": "swap elements at index j and curr from nums" }, { "code": null, "e": 3233, "s": 3189, "text": "swap elements at index j and curr from nums" }, { "code": null, "e": 3303, "s": 3233, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3314, "s": 3303, "text": " Live Demo" }, { "code": null, "e": 3854, "s": 3314, "text": "import random\nclass Solution(object):\n def __init__(self, nums):\n self.original = [x for x in nums]\n self.temp = nums\n self.indices = [x for x in range(len(nums))]\n def reset(self):\n return self.original\n def shuffle(self):\n if not len(self.temp):\n return []\n i = random.choice(self.indices)\n j = random.choice(self.indices)\n self.temp[i], self.temp[j] = self.temp[j], self.temp[i]\n return self.temp\nob = Solution([1,2,3])\nprint(ob.shuffle())\nprint(ob.reset())\nprint(ob.shuffle())" }, { "code": null, "e": 3923, "s": 3854, "text": "Initialize with [1,2,3] , then call shuffle(), reset() and shuffle()" }, { "code": null, "e": 3953, "s": 3923, "text": "[2, 1, 3]\n[1, 2, 3]\n[2, 3, 1]" } ]
Count alphanumeric palindromes of length N - GeeksforGeeks
26 Apr, 2021 Given a positive integer N, the task is to find the number of alphanumeric palindromic strings of length N. Since the count of such strings can be very large, print the answer modulo 109 + 7. Examples: Input: N = 2Output: 62Explanation: There are 26 palindromes of the form {“AA”, “BB”, ..., “ZZ”}, 26 palindromes of the form {“aa”, “bb”, ..., “cc”} and 10 palindromes of the form {“00”, “11”, ..., “99”}. Therefore, the total number of palindromic strings = 26 + 26 + 10 = 62. Input: N = 3Output: 3844 Naive Approach: The simplest approach is to generate all possible alphanumeric strings of length N and for each string, check if it is a palindrome or not. Since, at each position, 62 characters can be placed in total. Hence, there are 62N possible strings. Time Complexity: O(N*62N)Auxiliary Space: O(N) Efficient Approach: To optimize the above approach, the idea is to use the property of palindrome. It can be observed that if the length of the string is even, then for each index i from 0 to N/2, characters at indices i and (N – 1 – i) are the same. Therefore, for each position from 0 to N/ 2 there are 62N/2 options. Similarly, if the length is odd, 62(N+1)/2 options are there. Hence, it can be said that, for some N, there are 62ceil(N/2) possible palindromic strings. Follow the steps below to solve the problem: For the given value of N, calculate 62ceil(N/2) mod 109 + 7 using Modular Exponentiation. Print 62ceil(N/2) mod 109 + 7 as the required answer. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to calculate// (x ^ y) mod pint power(int x, int y, int p){ // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;} // Driver Codeint main(){ // Given N int N = 3; int flag, k, m; // Base Case if((N == 1) || (N == 2)) cout << 62; else m = 1000000000 + 7; // Check whether n // is even or odd if(N % 2 == 0) { k = N / 2; flag = true; } else { k = (N - 1) / 2; flag = false; } if(flag != 0) { // Function Call int a = power(62, k, m); cout << a; } else { // Function Call int a = power(62, (k + 1), m); cout << a; }} // This code is contributed by sanjoy_62 // Java program for the// above approachimport java.util.*;class GFG{ // Function to calculate// (x ^ y) mod pstatic int power(int x, int y, int p){ // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;} // Driver Codepublic static void main(String[] args){ // Given N int N = 3; int flag, k, m =0; // Base Case if ((N == 1) || (N == 2)) System.out.print(62); else m = 1000000000 + 7; // Check whether n // is even or odd if (N % 2 == 0) { k = N / 2; flag = 1; } else { k = (N - 1) / 2; flag = 0; } if (flag != 0) { // Function Call int a = power(62, k, m); System.out.print(a); } else { // Function Call int a = power(62, (k + 1), m); System.out.print(a); }}} // This code is contributed by 29AjayKumar # Python3 program for the above approach # Function to calculate (x ^ y) mod pdef power(x, y, p): # Initialize result res = 1 # Update x if it is more # than or equal to p x = x % p if (x == 0): return 0 while (y > 0): # If y is odd, multiply # x with result if ((y & 1) == 1): res = (res * x) % p # y must be even now y = y >> 1 x = (x * x) % p # Return the final result return res # Driver Code # Given NN = 3 # Base Caseif((N == 1) or (N == 2)): print(62) else: m = (10**9)+7 # Check whether n # is even or odd if(N % 2 == 0): k = N//2 flag = True else: k = (N - 1)//2 flag = False if(flag): # Function Call a = power(62, k, m) print(a) else: # Function Call a = power(62, (k + 1), m) print(a) // C# program for the// above approachusing System; class GFG{ // Function to calculate// (x ^ y) mod pstatic int power(int x, int y, int p){ // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;} // Driver Codepublic static void Main(){ // Given N int N = 3; int flag, k, m = 0; // Base Case if ((N == 1) || (N == 2)) Console.Write(62); else m = 1000000000 + 7; // Check whether n // is even or odd if (N % 2 == 0) { k = N / 2; flag = 1; } else { k = (N - 1) / 2; flag = 0; } if (flag != 0) { // Function Call int a = power(62, k, m); Console.Write(a); } else { // Function Call int a = power(62, (k + 1), m); Console.Write(a); }}} // This code is contributed by code_hunt <script> // JavaScript program to implement// the above approach // Function to calculate// (x ^ y) mod pfunction power(x, y, p){ // Initialize result let res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;}// Driver Code // Given N let N = 3; let flag, k, m =0; // Base Case if ((N == 1) || (N == 2)) document.write(62); else m = 1000000000 + 7; // Check whether n // is even or odd if (N % 2 == 0) { k = N / 2; flag = 1; } else { k = (N - 1) / 2; flag = 0; } if (flag != 0) { // Function Call let a = power(62, k, m); document.write(a); } else { // Function Call let a = power(62, (k + 1), m); document.write(a); } </script> 3844 Time Complexity: O(log N)Auxiliary Space: O(N) sanjoy_62 29AjayKumar code_hunt splevel62 Modular Arithmetic palindrome permutation Permutation and Combination Combinatorial Mathematical Strings Strings Mathematical permutation Combinatorial palindrome Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to get all subsets of given size of a set Lexicographic rank of a string Print all permutations in sorted (lexicographic) order Print all subsets of given size of a set Make all combinations of size k Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 25780, "s": 25752, "text": "\n26 Apr, 2021" }, { "code": null, "e": 25972, "s": 25780, "text": "Given a positive integer N, the task is to find the number of alphanumeric palindromic strings of length N. Since the count of such strings can be very large, print the answer modulo 109 + 7." }, { "code": null, "e": 25982, "s": 25972, "text": "Examples:" }, { "code": null, "e": 26258, "s": 25982, "text": "Input: N = 2Output: 62Explanation: There are 26 palindromes of the form {“AA”, “BB”, ..., “ZZ”}, 26 palindromes of the form {“aa”, “bb”, ..., “cc”} and 10 palindromes of the form {“00”, “11”, ..., “99”}. Therefore, the total number of palindromic strings = 26 + 26 + 10 = 62." }, { "code": null, "e": 26283, "s": 26258, "text": "Input: N = 3Output: 3844" }, { "code": null, "e": 26542, "s": 26283, "text": "Naive Approach: The simplest approach is to generate all possible alphanumeric strings of length N and for each string, check if it is a palindrome or not. Since, at each position, 62 characters can be placed in total. Hence, there are 62N possible strings. " }, { "code": null, "e": 26590, "s": 26542, "text": "Time Complexity: O(N*62N)Auxiliary Space: O(N) " }, { "code": null, "e": 27109, "s": 26590, "text": "Efficient Approach: To optimize the above approach, the idea is to use the property of palindrome. It can be observed that if the length of the string is even, then for each index i from 0 to N/2, characters at indices i and (N – 1 – i) are the same. Therefore, for each position from 0 to N/ 2 there are 62N/2 options. Similarly, if the length is odd, 62(N+1)/2 options are there. Hence, it can be said that, for some N, there are 62ceil(N/2) possible palindromic strings. Follow the steps below to solve the problem:" }, { "code": null, "e": 27199, "s": 27109, "text": "For the given value of N, calculate 62ceil(N/2) mod 109 + 7 using Modular Exponentiation." }, { "code": null, "e": 27253, "s": 27199, "text": "Print 62ceil(N/2) mod 109 + 7 as the required answer." }, { "code": null, "e": 27304, "s": 27253, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27310, "s": 27304, "text": "C++14" }, { "code": null, "e": 27315, "s": 27310, "text": "Java" }, { "code": null, "e": 27323, "s": 27315, "text": "Python3" }, { "code": null, "e": 27326, "s": 27323, "text": "C#" }, { "code": null, "e": 27337, "s": 27326, "text": "Javascript" }, { "code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to calculate// (x ^ y) mod pint power(int x, int y, int p){ // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;} // Driver Codeint main(){ // Given N int N = 3; int flag, k, m; // Base Case if((N == 1) || (N == 2)) cout << 62; else m = 1000000000 + 7; // Check whether n // is even or odd if(N % 2 == 0) { k = N / 2; flag = true; } else { k = (N - 1) / 2; flag = false; } if(flag != 0) { // Function Call int a = power(62, k, m); cout << a; } else { // Function Call int a = power(62, (k + 1), m); cout << a; }} // This code is contributed by sanjoy_62", "e": 28399, "s": 27337, "text": null }, { "code": "// Java program for the// above approachimport java.util.*;class GFG{ // Function to calculate// (x ^ y) mod pstatic int power(int x, int y, int p){ // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;} // Driver Codepublic static void main(String[] args){ // Given N int N = 3; int flag, k, m =0; // Base Case if ((N == 1) || (N == 2)) System.out.print(62); else m = 1000000000 + 7; // Check whether n // is even or odd if (N % 2 == 0) { k = N / 2; flag = 1; } else { k = (N - 1) / 2; flag = 0; } if (flag != 0) { // Function Call int a = power(62, k, m); System.out.print(a); } else { // Function Call int a = power(62, (k + 1), m); System.out.print(a); }}} // This code is contributed by 29AjayKumar", "e": 29476, "s": 28399, "text": null }, { "code": "# Python3 program for the above approach # Function to calculate (x ^ y) mod pdef power(x, y, p): # Initialize result res = 1 # Update x if it is more # than or equal to p x = x % p if (x == 0): return 0 while (y > 0): # If y is odd, multiply # x with result if ((y & 1) == 1): res = (res * x) % p # y must be even now y = y >> 1 x = (x * x) % p # Return the final result return res # Driver Code # Given NN = 3 # Base Caseif((N == 1) or (N == 2)): print(62) else: m = (10**9)+7 # Check whether n # is even or odd if(N % 2 == 0): k = N//2 flag = True else: k = (N - 1)//2 flag = False if(flag): # Function Call a = power(62, k, m) print(a) else: # Function Call a = power(62, (k + 1), m) print(a)", "e": 30385, "s": 29476, "text": null }, { "code": "// C# program for the// above approachusing System; class GFG{ // Function to calculate// (x ^ y) mod pstatic int power(int x, int y, int p){ // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;} // Driver Codepublic static void Main(){ // Given N int N = 3; int flag, k, m = 0; // Base Case if ((N == 1) || (N == 2)) Console.Write(62); else m = 1000000000 + 7; // Check whether n // is even or odd if (N % 2 == 0) { k = N / 2; flag = 1; } else { k = (N - 1) / 2; flag = 0; } if (flag != 0) { // Function Call int a = power(62, k, m); Console.Write(a); } else { // Function Call int a = power(62, (k + 1), m); Console.Write(a); }}} // This code is contributed by code_hunt", "e": 31448, "s": 30385, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to calculate// (x ^ y) mod pfunction power(x, y, p){ // Initialize result let res = 1; // Update x if it is more // than or equal to p x = x % p; if (x == 0) return 0; while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; x = (x * x) % p; } // Return the final // result return res;}// Driver Code // Given N let N = 3; let flag, k, m =0; // Base Case if ((N == 1) || (N == 2)) document.write(62); else m = 1000000000 + 7; // Check whether n // is even or odd if (N % 2 == 0) { k = N / 2; flag = 1; } else { k = (N - 1) / 2; flag = 0; } if (flag != 0) { // Function Call let a = power(62, k, m); document.write(a); } else { // Function Call let a = power(62, (k + 1), m); document.write(a); } </script>", "e": 32432, "s": 31448, "text": null }, { "code": null, "e": 32437, "s": 32432, "text": "3844" }, { "code": null, "e": 32486, "s": 32439, "text": "Time Complexity: O(log N)Auxiliary Space: O(N)" }, { "code": null, "e": 32496, "s": 32486, "text": "sanjoy_62" }, { "code": null, "e": 32508, "s": 32496, "text": "29AjayKumar" }, { "code": null, "e": 32518, "s": 32508, "text": "code_hunt" }, { "code": null, "e": 32528, "s": 32518, "text": "splevel62" }, { "code": null, "e": 32547, "s": 32528, "text": "Modular Arithmetic" }, { "code": null, "e": 32558, "s": 32547, "text": "palindrome" }, { "code": null, "e": 32570, "s": 32558, "text": "permutation" }, { "code": null, "e": 32598, "s": 32570, "text": "Permutation and Combination" }, { "code": null, "e": 32612, "s": 32598, "text": "Combinatorial" }, { "code": null, "e": 32625, "s": 32612, "text": "Mathematical" }, { "code": null, "e": 32633, "s": 32625, "text": "Strings" }, { "code": null, "e": 32641, "s": 32633, "text": "Strings" }, { "code": null, "e": 32654, "s": 32641, "text": "Mathematical" }, { "code": null, "e": 32666, "s": 32654, "text": "permutation" }, { "code": null, "e": 32680, "s": 32666, "text": "Combinatorial" }, { "code": null, "e": 32691, "s": 32680, "text": "palindrome" }, { "code": null, "e": 32710, "s": 32691, "text": "Modular Arithmetic" }, { "code": null, "e": 32808, "s": 32710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32865, "s": 32808, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 32896, "s": 32865, "text": "Lexicographic rank of a string" }, { "code": null, "e": 32951, "s": 32896, "text": "Print all permutations in sorted (lexicographic) order" }, { "code": null, "e": 32992, "s": 32951, "text": "Print all subsets of given size of a set" }, { "code": null, "e": 33024, "s": 32992, "text": "Make all combinations of size k" }, { "code": null, "e": 33054, "s": 33024, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33069, "s": 33054, "text": "C++ Data Types" }, { "code": null, "e": 33112, "s": 33069, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 33131, "s": 33112, "text": "Coin Change | DP-7" } ]
How to add footnote under the X-axis using Matplotlib?
To add footnote under the X-axis using matplotlib, we can use figtext() and text() method. Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Plot x and y data points using numpy. To place the footnote, use figtext() method with x, y position and box properties. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 100) y = np.exp(x) plt.plot(x, y) plt.figtext(0.5, 0.01, "footnote: $y=e^{x}$", ha="center", fontsize=18, bbox={"facecolor": "green", "alpha": 0.75, "pad": 5}) plt.show()
[ { "code": null, "e": 1153, "s": 1062, "text": "To add footnote under the X-axis using matplotlib, we can use figtext() and text() method." }, { "code": null, "e": 1229, "s": 1153, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1269, "s": 1229, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1307, "s": 1269, "text": "Plot x and y data points using numpy." }, { "code": null, "e": 1390, "s": 1307, "text": "To place the footnote, use figtext() method with x, y position and box properties." }, { "code": null, "e": 1432, "s": 1390, "text": "To display the figure, use show() method." }, { "code": null, "e": 1767, "s": 1432, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(-2, 2, 100)\ny = np.exp(x)\n\nplt.plot(x, y)\nplt.figtext(0.5, 0.01, \"footnote: $y=e^{x}$\", ha=\"center\", fontsize=18, bbox={\"facecolor\": \"green\", \"alpha\": 0.75, \"pad\": 5})\nplt.show()" } ]
File structures (sequential files, indexing, B and B+ trees) - GeeksforGeeks
09 Oct, 2019 Here block size is 10^3 B. No. of entries in the FAT = Disk capacity/ Block size = 10^8/10^3 = 10^5 Total space consumed by FAT = 10^5 *4B = 0.4*10^6B Max. size of file that can be stored = 100*10^6-0.4*10^6 = 99.6*10^6B. So answer 99.6. Name Age Occupation Category Rama 27 CON A Abdul 22 ENG A Jeniffer 28 DOC B Maya 32 SER D Dev 24 MUS C Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies Axios in React: A Guide for Beginners How to pass property from a parent component props to a child component ? BigInt (BIG INTEGERS) in C++ with Example How to Install Flutter on Visual Studio Code? How to calculate MOVING AVERAGE in a Pandas DataFrame? Retrofit with Kotlin Coroutine in Android Get Hired With GeeksforGeeks and Win Exciting Rewards! How to insert a pandas DataFrame to an existing PostgreSQL table?
[ { "code": null, "e": 29600, "s": 29572, "text": "\n09 Oct, 2019" }, { "code": null, "e": 29958, "s": 29600, "text": "Here block size is 10^3 B.\nNo. of entries in the FAT = Disk capacity/ Block size \n = 10^8/10^3 \n = 10^5\nTotal space consumed by FAT = 10^5 *4B \n = 0.4*10^6B\nMax. size of file that can be stored = 100*10^6-0.4*10^6\n = 99.6*10^6B.\nSo answer 99.6." }, { "code": null, "e": 30174, "s": 29958, "text": "\nName Age Occupation Category\nRama 27 CON A\nAbdul 22 ENG A\nJeniffer 28 DOC B\nMaya 32 SER D\nDev 24 MUS C\n" }, { "code": null, "e": 30272, "s": 30174, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 30304, "s": 30272, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 30357, "s": 30304, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 30395, "s": 30357, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 30469, "s": 30395, "text": "How to pass property from a parent component props to a child component ?" }, { "code": null, "e": 30511, "s": 30469, "text": "BigInt (BIG INTEGERS) in C++ with Example" }, { "code": null, "e": 30557, "s": 30511, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 30612, "s": 30557, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 30654, "s": 30612, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30709, "s": 30654, "text": "Get Hired With GeeksforGeeks and Win Exciting Rewards!" } ]
Delete Cookies On All Domains using Selenium Webdriver.
We can delete cookies on all domains with Selenium. The method deleteAllCookies is used to delete all cookies from the present domain. First, we shall add cookies, then get them and finally delete all the cookies. driver.manage().deleteAllCookies(); import java.util.Set; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class DeleteCookies{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); // wait of 4 seconds driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); // setting name and value for cookie Cookie c = new Cookie("test", "selenium"); Cookie r = new Cookie("subject", "Java"); // cookie addition driver.manage().addCookie(c); driver.manage().addCookie(r); // obtain the cookies Set ck = driver.manage().getCookies(); System.out.println("Cookie count: "+ck.size()); // delete cookies driver.manage().deleteAllCookies(); // obtain the cookies after delete Set ch = driver.manage().getCookies(); System.out.println("Cookie count after delete: "+ch.size()); } }
[ { "code": null, "e": 1276, "s": 1062, "text": "We can delete cookies on all domains with Selenium. The method deleteAllCookies is used to delete all cookies from the present domain. First, we shall add cookies, then get them and finally delete all the cookies." }, { "code": null, "e": 1312, "s": 1276, "text": "driver.manage().deleteAllCookies();" }, { "code": null, "e": 2477, "s": 1312, "text": "import java.util.Set;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class DeleteCookies{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // wait of 4 seconds\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n // setting name and value for cookie\n Cookie c = new Cookie(\"test\", \"selenium\");\n Cookie r = new Cookie(\"subject\", \"Java\");\n // cookie addition\n driver.manage().addCookie(c);\n driver.manage().addCookie(r);\n // obtain the cookies\n Set ck = driver.manage().getCookies();\n System.out.println(\"Cookie count: \"+ck.size());\n // delete cookies\n driver.manage().deleteAllCookies();\n // obtain the cookies after delete\n Set ch = driver.manage().getCookies();\n System.out.println(\"Cookie count after delete: \"+ch.size());\n }\n}" } ]
Difference between DELETE, DROP and TRUNCATE - GeeksforGeeks
24 Dec, 2021 Basically, it is a Data Manipulation Language Command (DML). It is used to delete one or more tuples of a table. With the help of the “DELETE” command, we can either delete all the rows in one go or can delete rows one by one. i.e., we can use it as per the requirement or the condition using the Where clause. It is comparatively slower than the TRUNCATE command. The TRUNCATE command does not remove the structure of the table. SYNTAX – If we want to delete all the rows of the table: DELETE from; SYNTAX – If we want to delete the row of the table as per the condition then we use the WHERE clause, DELETE from WHERE ; Note – Here we can use the “ROLLBACK” command to restore the tuple because it does not auto-commit. It is a Data Definition Language Command (DDL). It is used to drop the whole table. With the help of the “DROP” command we can drop (delete) the whole structure in one go i.e. it removes the named elements of the schema. By using this command the existence of the whole table is finished or say lost. SYNTAX – If we want to drop the table: DROP table ; Note – Here we can’t restore the table by using the “ROLLBACK” command because it auto commits. It is also a Data Definition Language Command (DDL). It is used to delete all the rows of a relation (table) in one go. With the help of the “TRUNCATE” command, we can’t delete the single row as here WHERE clause is not used. By using this command the existence of all the rows of the table is lost. It is comparatively faster than the delete command as it deletes all the rows fastly. SYNTAX – If we want to use truncate : TRUNCATE; Note – Here we can’t restore the tuples of the table by using the “ROLLBACK” command. chandradharrao DBMS GATE CS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction of B-Tree Difference between Clustered and Non-clustered index CTE in SQL Introduction of ER Model SQL | Views Layers of OSI Model TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 24073, "s": 24045, "text": "\n24 Dec, 2021" }, { "code": null, "e": 24503, "s": 24073, "text": "Basically, it is a Data Manipulation Language Command (DML). It is used to delete one or more tuples of a table. With the help of the “DELETE” command, we can either delete all the rows in one go or can delete rows one by one. i.e., we can use it as per the requirement or the condition using the Where clause. It is comparatively slower than the TRUNCATE command. The TRUNCATE command does not remove the structure of the table." }, { "code": null, "e": 24560, "s": 24503, "text": "SYNTAX – If we want to delete all the rows of the table:" }, { "code": null, "e": 24573, "s": 24560, "text": "DELETE from;" }, { "code": null, "e": 24675, "s": 24573, "text": "SYNTAX – If we want to delete the row of the table as per the condition then we use the WHERE clause," }, { "code": null, "e": 24697, "s": 24675, "text": "DELETE from WHERE ;" }, { "code": null, "e": 24797, "s": 24697, "text": "Note – Here we can use the “ROLLBACK” command to restore the tuple because it does not auto-commit." }, { "code": null, "e": 25099, "s": 24797, "text": "It is a Data Definition Language Command (DDL). It is used to drop the whole table. With the help of the “DROP” command we can drop (delete) the whole structure in one go i.e. it removes the named elements of the schema. By using this command the existence of the whole table is finished or say lost. " }, { "code": null, "e": 25138, "s": 25099, "text": "SYNTAX – If we want to drop the table:" }, { "code": null, "e": 25151, "s": 25138, "text": "DROP table ;" }, { "code": null, "e": 25247, "s": 25151, "text": "Note – Here we can’t restore the table by using the “ROLLBACK” command because it auto commits." }, { "code": null, "e": 25634, "s": 25247, "text": "It is also a Data Definition Language Command (DDL). It is used to delete all the rows of a relation (table) in one go. With the help of the “TRUNCATE” command, we can’t delete the single row as here WHERE clause is not used. By using this command the existence of all the rows of the table is lost. It is comparatively faster than the delete command as it deletes all the rows fastly. " }, { "code": null, "e": 25672, "s": 25634, "text": "SYNTAX – If we want to use truncate :" }, { "code": null, "e": 25682, "s": 25672, "text": "TRUNCATE;" }, { "code": null, "e": 25768, "s": 25682, "text": "Note – Here we can’t restore the tuples of the table by using the “ROLLBACK” command." }, { "code": null, "e": 25783, "s": 25768, "text": "chandradharrao" }, { "code": null, "e": 25788, "s": 25783, "text": "DBMS" }, { "code": null, "e": 25796, "s": 25788, "text": "GATE CS" }, { "code": null, "e": 25800, "s": 25796, "text": "SQL" }, { "code": null, "e": 25805, "s": 25800, "text": "DBMS" }, { "code": null, "e": 25809, "s": 25805, "text": "SQL" }, { "code": null, "e": 25907, "s": 25809, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25930, "s": 25907, "text": "Introduction of B-Tree" }, { "code": null, "e": 25983, "s": 25930, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 25994, "s": 25983, "text": "CTE in SQL" }, { "code": null, "e": 26019, "s": 25994, "text": "Introduction of ER Model" }, { "code": null, "e": 26031, "s": 26019, "text": "SQL | Views" }, { "code": null, "e": 26051, "s": 26031, "text": "Layers of OSI Model" }, { "code": null, "e": 26064, "s": 26051, "text": "TCP/IP Model" }, { "code": null, "e": 26113, "s": 26064, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26140, "s": 26113, "text": "Types of Operating Systems" } ]
File renameTo() method in Java with examples - GeeksforGeeks
28 Jan, 2019 The renameTo() method is a part of File class. The renameTo() function is used to rename the abstract path name of a File to a given path name. The function returns true if the file is renamed else returns false Function Signature: public boolean renameTo(File destination) Syntax: file.renameTo(File destination) Parameters: The function requires File object destination as parameter, the new abstract path name of the present file. Return Value: The function returns boolean data type. The function returns true the file is renamed else returns false Exception: This method throws following exceptions: Security Exception if the method does not allow write operation of the abstract pathnames. NullPointerException if the destination filename is null. Below programs will illustrate the use of renameTo() function: Example 1: Try to rename the file program.txt to program1.txt // Java program to demonstrate// the use of File.renameTo() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program.txt"); // create the destination file object File dest = new File("F:\\program1.txt"); // check if the file can be renamed // to the abstract path name if (f.renameTo(dest)) { // display that the file is renamed // to the abstract path name System.out.println("File is renamed"); } else { // display that the file cannot be renamed // to the abstract path name System.out.println("File cannot be renamed"); } }} Output: File is renamed Example 2: Try to rename “program1.txt” to “prog.txt”, “prog.txt” is a existing file in the f: drive . // Java program to demonstrate// the use of File.renameTo() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program1.txt"); // create the destination file object File dest = new File("F:\\prog.txt"); // check if the file can be renamed // to the abstract path name if (f.renameTo(dest)) { // display that the file is renamed // to the abstract path name System.out.println("File is renamed"); } else { // display that the file cannot be renamed // to the abstract path name System.out.println("File cannot be renamed"); } }} Output: File cannot be renamed The programs might not run in an online IDE. please use an offline IDE and set the path of the file Java-File Class Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n28 Jan, 2019" }, { "code": null, "e": 24160, "s": 23948, "text": "The renameTo() method is a part of File class. The renameTo() function is used to rename the abstract path name of a File to a given path name. The function returns true if the file is renamed else returns false" }, { "code": null, "e": 24180, "s": 24160, "text": "Function Signature:" }, { "code": null, "e": 24222, "s": 24180, "text": "public boolean renameTo(File destination)" }, { "code": null, "e": 24230, "s": 24222, "text": "Syntax:" }, { "code": null, "e": 24262, "s": 24230, "text": "file.renameTo(File destination)" }, { "code": null, "e": 24382, "s": 24262, "text": "Parameters: The function requires File object destination as parameter, the new abstract path name of the present file." }, { "code": null, "e": 24501, "s": 24382, "text": "Return Value: The function returns boolean data type. The function returns true the file is renamed else returns false" }, { "code": null, "e": 24553, "s": 24501, "text": "Exception: This method throws following exceptions:" }, { "code": null, "e": 24644, "s": 24553, "text": "Security Exception if the method does not allow write operation of the abstract pathnames." }, { "code": null, "e": 24702, "s": 24644, "text": "NullPointerException if the destination filename is null." }, { "code": null, "e": 24765, "s": 24702, "text": "Below programs will illustrate the use of renameTo() function:" }, { "code": null, "e": 24827, "s": 24765, "text": "Example 1: Try to rename the file program.txt to program1.txt" }, { "code": "// Java program to demonstrate// the use of File.renameTo() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File(\"F:\\\\program.txt\"); // create the destination file object File dest = new File(\"F:\\\\program1.txt\"); // check if the file can be renamed // to the abstract path name if (f.renameTo(dest)) { // display that the file is renamed // to the abstract path name System.out.println(\"File is renamed\"); } else { // display that the file cannot be renamed // to the abstract path name System.out.println(\"File cannot be renamed\"); } }}", "e": 25615, "s": 24827, "text": null }, { "code": null, "e": 25623, "s": 25615, "text": "Output:" }, { "code": null, "e": 25639, "s": 25623, "text": "File is renamed" }, { "code": null, "e": 25742, "s": 25639, "text": "Example 2: Try to rename “program1.txt” to “prog.txt”, “prog.txt” is a existing file in the f: drive ." }, { "code": "// Java program to demonstrate// the use of File.renameTo() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File(\"F:\\\\program1.txt\"); // create the destination file object File dest = new File(\"F:\\\\prog.txt\"); // check if the file can be renamed // to the abstract path name if (f.renameTo(dest)) { // display that the file is renamed // to the abstract path name System.out.println(\"File is renamed\"); } else { // display that the file cannot be renamed // to the abstract path name System.out.println(\"File cannot be renamed\"); } }}", "e": 26525, "s": 25742, "text": null }, { "code": null, "e": 26533, "s": 26525, "text": "Output:" }, { "code": null, "e": 26557, "s": 26533, "text": "File cannot be renamed\n" }, { "code": null, "e": 26657, "s": 26557, "text": "The programs might not run in an online IDE. please use an offline IDE and set the path of the file" }, { "code": null, "e": 26673, "s": 26657, "text": "Java-File Class" }, { "code": null, "e": 26688, "s": 26673, "text": "Java-Functions" }, { "code": null, "e": 26704, "s": 26688, "text": "Java-IO package" }, { "code": null, "e": 26709, "s": 26704, "text": "Java" }, { "code": null, "e": 26714, "s": 26709, "text": "Java" }, { "code": null, "e": 26812, "s": 26714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26827, "s": 26812, "text": "Stream In Java" }, { "code": null, "e": 26873, "s": 26827, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26894, "s": 26873, "text": "Constructors in Java" }, { "code": null, "e": 26913, "s": 26894, "text": "Exceptions in Java" }, { "code": null, "e": 26930, "s": 26913, "text": "Generics in Java" }, { "code": null, "e": 26960, "s": 26930, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27003, "s": 26960, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27032, "s": 27003, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27053, "s": 27032, "text": "Introduction to Java" } ]
Set cellpadding and cellspacing in CSS - GeeksforGeeks
04 Dec, 2018 Cell Padding The cell padding is used to define the spaces between the cells and its border. If cell padding property is not apply then it will be set as default value. Example: <!DOCTYPE html><html> <head> <title>cell padding</title> <style> table, th, td { border: 2px solid green; text-align:center; } th, td { padding: 20px; background-color:none; } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Cell Padding property</h2> <h3>padding: 20px;</h3> <table style="width:70%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Harsh</td> <td>Agarwal</td> <td>15</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Ramesh</td> <td>Chandra</td> <td>28</td> </tr> </table> </center> </body></html> Output: Cell Spacing The cell spacing is used to define the space between the cells. Example: <!DOCTYPE html><html> <head> <title>cell spacing property</title> <style> table, th, td { border: 2px solid green; text-align:center; } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Cell Spacing property</h2> <h3>cellspacing = "30px"</h3> <table style="width:70%;"cellspacing="30px"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Harsh</td> <td>Agarwal</td> <td>15</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Ramesh</td> <td>Chandra</td> <td>28</td> </tr> </table> </center> </body></html> Output: Supported Browsers: The browser supported by cell padding and cell spacing are listed below: Apple Safari Google Chrome Firefox Opera Internet Explorer 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 Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24275, "s": 24247, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24288, "s": 24275, "text": "Cell Padding" }, { "code": null, "e": 24444, "s": 24288, "text": "The cell padding is used to define the spaces between the cells and its border. If cell padding property is not apply then it will be set as default value." }, { "code": null, "e": 24453, "s": 24444, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>cell padding</title> <style> table, th, td { border: 2px solid green; text-align:center; } th, td { padding: 20px; background-color:none; } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Cell Padding property</h2> <h3>padding: 20px;</h3> <table style=\"width:70%\"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Harsh</td> <td>Agarwal</td> <td>15</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Ramesh</td> <td>Chandra</td> <td>28</td> </tr> </table> </center> </body></html> ", "e": 25489, "s": 24453, "text": null }, { "code": null, "e": 25497, "s": 25489, "text": "Output:" }, { "code": null, "e": 25510, "s": 25497, "text": "Cell Spacing" }, { "code": null, "e": 25574, "s": 25510, "text": "The cell spacing is used to define the space between the cells." }, { "code": null, "e": 25583, "s": 25574, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>cell spacing property</title> <style> table, th, td { border: 2px solid green; text-align:center; } h1 { color:green; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h2>Cell Spacing property</h2> <h3>cellspacing = \"30px\"</h3> <table style=\"width:70%;\"cellspacing=\"30px\"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Harsh</td> <td>Agarwal</td> <td>15</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Ramesh</td> <td>Chandra</td> <td>28</td> </tr> </table> </center> </body></html> ", "e": 26654, "s": 25583, "text": null }, { "code": null, "e": 26662, "s": 26654, "text": "Output:" }, { "code": null, "e": 26755, "s": 26662, "text": "Supported Browsers: The browser supported by cell padding and cell spacing are listed below:" }, { "code": null, "e": 26768, "s": 26755, "text": "Apple Safari" }, { "code": null, "e": 26782, "s": 26768, "text": "Google Chrome" }, { "code": null, "e": 26790, "s": 26782, "text": "Firefox" }, { "code": null, "e": 26796, "s": 26790, "text": "Opera" }, { "code": null, "e": 26814, "s": 26796, "text": "Internet Explorer" }, { "code": null, "e": 26951, "s": 26814, "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": 26960, "s": 26951, "text": "CSS-Misc" }, { "code": null, "e": 26967, "s": 26960, "text": "Picked" }, { "code": null, "e": 26971, "s": 26967, "text": "CSS" }, { "code": null, "e": 26976, "s": 26971, "text": "HTML" }, { "code": null, "e": 26993, "s": 26976, "text": "Web Technologies" }, { "code": null, "e": 26998, "s": 26993, "text": "HTML" }, { "code": null, "e": 27096, "s": 26998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27105, "s": 27096, "text": "Comments" }, { "code": null, "e": 27118, "s": 27105, "text": "Old Comments" }, { "code": null, "e": 27180, "s": 27118, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27230, "s": 27180, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27288, "s": 27230, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27336, "s": 27288, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27373, "s": 27336, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27435, "s": 27373, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27485, "s": 27435, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27545, "s": 27485, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27593, "s": 27545, "text": "How to update Node.js and NPM to next version ?" } ]
Creating an Ethereum Token to Enable a Decentralized Rent-to-Own Network | by Evan Diewald | Towards Data Science
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. With real estate prices soaring to record heights, it has never been more difficult to qualify for a mortgage. Even those with steady, well-paying jobs can struggle to prove their creditworthiness and save up enough cash to start building equity in a home. Rent-to-Own, as the name implies, is an alternative route to homeownership in which renters have the option to purchase the property when their lease expires. While the terms of the agreement can vary, what this essentially means is that a certain portion of each rent check goes toward an eventual down payment. Ideally, this arrangement is a win-win: landlords benefit from extra-motivated tenants, and dependable renters are rewarded for their financial responsibility. However, in practice, Rent-to-Own is far from perfect. Renters who decide to move have to forfeit their accrued payments and start over. Predatory landlords change the terms at the last minute, and both parties must rely on each other to keep honest and accurate records. Fortunately, innovations in Decentralized Finance (DeFi) offer a potential solution to these problems. Using smart contracts, we can program the business logic of rent-to-own agreements as independently-verifiable transactions in an immutable ledger. We can even create an cryptocurrency-based incentive system that rewards both renters and landlords. These are the principles behind the RTO token, the non-transferrable asset class that drives a potential network of Rent-to-Own participants. Let’s start with a conceptual overview of the (preliminary) economics before diving into technical details. For the RTO system to work, it must benefit all stakeholders. First, landlords who list a home through any rent-to-own scheme expect to make a certain amount of cash during the rental period before the sale. Typically, this represents some portion of the property’s appraisal value. Once this threshold is met, they want to sell to a motivated, creditworthy buyer. But how do you go about finding such a buyer? Credit scores do not tell the whole story, and references can be easily forged. Because of the difficulty in establishing trust through these imperfect metrics, landlords often have no choice but to allow each tenant to prove themselves through firsthand experience (i.e. years of on-time payments). For this reason, most rent-to-own agreements are non-transferrable, meaning that tenants have to return to square one if they decide to move. Thus, a ubiquitous network of rent-to-own homes and participants would be advantageous. Property management companies would be one way to achieve this, but such centralized options remove individuals’ autonomy in exchange for standardization and shared infrastructure, like secure payment platforms and databases. RTO offers a decentralized alternative. We start by leveraging the secure, stable, and immutable financial transactions that are already baked into the Ethereum ecosystem, wrapping our business logic in a smart contract to establish trust among distributed network participants. Our smart contract is simple, but powerful. To list a rent-to-own home on the RTO network, landlords must first be verified by the contract administrator. Once approved, they can add their rental property, which is defined by the renter’s ETH address, an earnings threshold (representing a USD amount that they would like to recover before selling the home), and an earnings percentage (the fraction of each rental payment that will contribute toward the earnings threshold). New homes and renters are initialized with an empty RTO balance, and homes will not be sold until both buyer and seller have an RTO balance that exceeds the earnings threshold. This condition ensures that landlords are guaranteed a certain amount of profits and renters have proven themselves creditworthy. Each time rent is paid (in ETH) through this smart contract, both the renter and home acquire non-transferrable, dollar-normalized RTO. The exact amount of RTO earned is determined by the following equation: amountToMint = rentAmountEth * earningsPercent * usdPriceEth So let’s say a home has a monthly rent of $2000 (market value of about 1 ETH at the time of writing), an earnings percentage of 20%, and an earnings threshold of $20,000. With each payment, 1 ETH * 20% * ($2000/ETH) = 400 RTO are added to the balances of both renter and home. At this rate, the renter will have the opportunity to purchase the house after about 4 years of steady payments. If they decide to move, both tenant and home retain their RTO balance. It’s important to note that valid rent payments are the only way to acquire RTO — tokens are non-transferrable, non-burnable, and cannot be swapped on secondary markets, as opposed to standard ERC20 coins. Like a credit score, there are no shortcuts to establishing good financial standing. By making the critical information publicly available, the RTO network creates a competitive marketplace where, in addition to amenities and square footage, participants can compare and negotiate the terms of the earnings agreement. Even within the contract’s relatively simple boundaries, dozens of unique, mutually-beneficial scenarios can occur naturally, such as: Renter and home both start with 0 RTO and renter does not move: This represents the traditional rent-to-own structure. Both entities reach the earnings threshold at the same time, at which point the renter can buy the house. Renter RTO > Earnings Threshold & Home RTO < Earnings Threshold: Renter is ready but landlord is not. By the time both conditions are met, the renter may have enough leverage to negotiate for more a more favorable mortgage (e.g. 20 instead of 30-year term). Home RTO > Earnings & Renter RTO < Earnings Threshold: The opposite of the last scenario. Here, the renter still has to prove themselves, but they may wish to accelerate their earnings by negotiating for a higher earnings percentage. Skip this section if you’d like to get right to the demo of the decentralized application. The business logic discussed above is codified in the following smart contract, written in Solidity. If you’re familiar with object-oriented programming languages, most of the code should be pretty straightforward. I would like to highlight a couple of key functions: getThePrice(): RTO should be pegged to the dollar to account for the volatility in the price of ETH. To normalize ETH payments, we need a way to access the current USD/ETH market price. Unfortunately, we can’t just call the CoinGecko API within Solidity, but we can access a “Price Feed”, which cleverly stores the price on-chain via a Chainlink aggregator interface. More on that here. payRent(address _to): This is the heart of the smart contract, so it deserves special consideration. First of all, we make sure that the payment is made from the home’s renter to its verified landlord. Next, as a payable function, we also facilitate the transfer of ETH (L119), the amount of which is stored in the transaction data. Finally, we calculate amountToMint (see the equation above) and update the balances of home and renter accordingly. I deployed the smart contract to the Ropsten Testnet using the Remix IDE and my Metamask wallet. Here are more detailed instructions if you’re interested. Before we move on to the application, we (as the contract deployer) need to add a verified landlord and sign the transaction using the same account that deployed the contract (representing a trusted administrator). We can do that right in Remix. We can also view our contract and all associated transactions on Etherscan. The application provides methods for us to use the smart contract functions through a payment portal-esque interface. I’m using Python’s FastAPI to create the API endpoints, the Web3.py library to prepare (but not sign, more on that in a second) the Ethereum transactions, and a basic PostgreSQL database to store some off-chain data, like URL’s to images of the homes. Rather than asking the user to hard-code their private keys into the application itself (a SERIOUS security risk), we sign transactions using the popular Metamask browser extension. For example, we generate the transaction data for the payRent function like this: # from transactions.pydef payRent(landlord, amount_eth): txn_dict = to_contract.functions.payRent(w3.toChecksumAddress(landlord)).buildTransaction({ 'chainId': 3, 'value': w3.toWei(float(amount_eth), 'ether'), 'gas': 2000000, 'gasPrice': w3.toWei('2', 'gwei') }) return txn_dict We can then send this data to Metamask with a few lines of JavaScript: # from confirm_transaction.htmlsendTxnButton.addEventListener('click', () => { sendTxnButton.disabled = true; sendTxnButton.innerHTML = "Connecting to Metamask..."; ethereum .request({ method: 'eth_sendTransaction', params: [ { from: ethereum.selectedAddress, to: "{{contract_address}}", value: "{{value}}", gasPrice: '0x4A817C800', gas: '0x1E8480', data: "{{txn_data}}", chainId: '0x3' }, ], }) .then((txHash) => logTransaction(txHash)) .catch((error) => console.error);}); The full project code, with instructions of how to run the demo application, can be accessed here. Now for a quick demo that demonstrates functionality from the perspectives of both landlord and renter. Before the tenant and home can start earning RTO, our landlord will have to add their property to the smart contract. They can do that by navigating to the “View Listings” tab and filling out a quick form. Some of these values, like the street address and description, will be stored in our off-chain database. Others, like the down payment (aka earnings threshold) and earnings percentage, will be stored in the smart contract. This page simply prepares the function details, but they will then be asked to explicitly sign the transaction using their Metamask wallet. Once the asynchronously-executed transaction is approved, we can view our fancy new listing, along with the immutable details read directly from the ledger. Now that our home has been added, let’s make a dent in that earnings threshold and start mining some RTO. Clicking the “Connect Wallet” button brings us to a page that looks like this: The bright orange “Connect Metamask” button will open up a prompt from the browser extension that informs us that our application would like to (for now) simply read our wallet address. When we accept, our active ETH address will magically appear in our application page. Let’s go ahead and check our RTO balance for this wallet. Since we haven’t made any rent payments, of course we don’t have any tokens. To do this, we navigate to the “Pay Rent” tab, fill in our payment amount (in ETH), and the ETH address of our landlord. Again, the actual transaction signing and private key management is decoupled from the application itself. In this case, our simulated rent payment was 0.01 ETH, or about $20 (maybe it’s more of a tent than a home). Given an earnings percentage of 30%, we should mine about 6–7 RTO for this transaction. Let’s go ahead and check our balance again: And the same amount has also been applied to the home listing (see Balance Paid): Interestingly, like any ERC20 token, we can also view our balance right in Metamask by adding the smart contract address! This application was relatively simple to develop, but it demonstrates some significant concepts. Renters cannot fabricate their RTO balance, or obtain tokens through any other means other than steadily paying rent. Similarly, while landlords have strong incentives to participate in this network (motivated renters, guaranteed pre-sale earnings, no need to engage with centralized property management), their RTO balance is also on public display. Under traditional frameworks, establishing this trustless interaction would require painstaking recordkeeping and the threat of strong consequences to disincentivize fraudulent behavior. But with a robust public blockchain, accessing these benefits is trivial. We hear a lot about “Yield Farming”, leveraged trading, and other complicated DeFi instruments, but the most sustainable applications of cryptocurrencies involve re-thinking how we establish trust in everyday relationships. All code is available on Github.
[ { "code": null, "e": 472, "s": 172, "text": "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": 1474, "s": 472, "text": "With real estate prices soaring to record heights, it has never been more difficult to qualify for a mortgage. Even those with steady, well-paying jobs can struggle to prove their creditworthiness and save up enough cash to start building equity in a home. Rent-to-Own, as the name implies, is an alternative route to homeownership in which renters have the option to purchase the property when their lease expires. While the terms of the agreement can vary, what this essentially means is that a certain portion of each rent check goes toward an eventual down payment. Ideally, this arrangement is a win-win: landlords benefit from extra-motivated tenants, and dependable renters are rewarded for their financial responsibility. However, in practice, Rent-to-Own is far from perfect. Renters who decide to move have to forfeit their accrued payments and start over. Predatory landlords change the terms at the last minute, and both parties must rely on each other to keep honest and accurate records." }, { "code": null, "e": 2076, "s": 1474, "text": "Fortunately, innovations in Decentralized Finance (DeFi) offer a potential solution to these problems. Using smart contracts, we can program the business logic of rent-to-own agreements as independently-verifiable transactions in an immutable ledger. We can even create an cryptocurrency-based incentive system that rewards both renters and landlords. These are the principles behind the RTO token, the non-transferrable asset class that drives a potential network of Rent-to-Own participants. Let’s start with a conceptual overview of the (preliminary) economics before diving into technical details." }, { "code": null, "e": 2929, "s": 2076, "text": "For the RTO system to work, it must benefit all stakeholders. First, landlords who list a home through any rent-to-own scheme expect to make a certain amount of cash during the rental period before the sale. Typically, this represents some portion of the property’s appraisal value. Once this threshold is met, they want to sell to a motivated, creditworthy buyer. But how do you go about finding such a buyer? Credit scores do not tell the whole story, and references can be easily forged. Because of the difficulty in establishing trust through these imperfect metrics, landlords often have no choice but to allow each tenant to prove themselves through firsthand experience (i.e. years of on-time payments). For this reason, most rent-to-own agreements are non-transferrable, meaning that tenants have to return to square one if they decide to move." }, { "code": null, "e": 3522, "s": 2929, "text": "Thus, a ubiquitous network of rent-to-own homes and participants would be advantageous. Property management companies would be one way to achieve this, but such centralized options remove individuals’ autonomy in exchange for standardization and shared infrastructure, like secure payment platforms and databases. RTO offers a decentralized alternative. We start by leveraging the secure, stable, and immutable financial transactions that are already baked into the Ethereum ecosystem, wrapping our business logic in a smart contract to establish trust among distributed network participants." }, { "code": null, "e": 4305, "s": 3522, "text": "Our smart contract is simple, but powerful. To list a rent-to-own home on the RTO network, landlords must first be verified by the contract administrator. Once approved, they can add their rental property, which is defined by the renter’s ETH address, an earnings threshold (representing a USD amount that they would like to recover before selling the home), and an earnings percentage (the fraction of each rental payment that will contribute toward the earnings threshold). New homes and renters are initialized with an empty RTO balance, and homes will not be sold until both buyer and seller have an RTO balance that exceeds the earnings threshold. This condition ensures that landlords are guaranteed a certain amount of profits and renters have proven themselves creditworthy." }, { "code": null, "e": 4513, "s": 4305, "text": "Each time rent is paid (in ETH) through this smart contract, both the renter and home acquire non-transferrable, dollar-normalized RTO. The exact amount of RTO earned is determined by the following equation:" }, { "code": null, "e": 4574, "s": 4513, "text": "amountToMint = rentAmountEth * earningsPercent * usdPriceEth" }, { "code": null, "e": 5326, "s": 4574, "text": "So let’s say a home has a monthly rent of $2000 (market value of about 1 ETH at the time of writing), an earnings percentage of 20%, and an earnings threshold of $20,000. With each payment, 1 ETH * 20% * ($2000/ETH) = 400 RTO are added to the balances of both renter and home. At this rate, the renter will have the opportunity to purchase the house after about 4 years of steady payments. If they decide to move, both tenant and home retain their RTO balance. It’s important to note that valid rent payments are the only way to acquire RTO — tokens are non-transferrable, non-burnable, and cannot be swapped on secondary markets, as opposed to standard ERC20 coins. Like a credit score, there are no shortcuts to establishing good financial standing." }, { "code": null, "e": 5694, "s": 5326, "text": "By making the critical information publicly available, the RTO network creates a competitive marketplace where, in addition to amenities and square footage, participants can compare and negotiate the terms of the earnings agreement. Even within the contract’s relatively simple boundaries, dozens of unique, mutually-beneficial scenarios can occur naturally, such as:" }, { "code": null, "e": 5919, "s": 5694, "text": "Renter and home both start with 0 RTO and renter does not move: This represents the traditional rent-to-own structure. Both entities reach the earnings threshold at the same time, at which point the renter can buy the house." }, { "code": null, "e": 6177, "s": 5919, "text": "Renter RTO > Earnings Threshold & Home RTO < Earnings Threshold: Renter is ready but landlord is not. By the time both conditions are met, the renter may have enough leverage to negotiate for more a more favorable mortgage (e.g. 20 instead of 30-year term)." }, { "code": null, "e": 6411, "s": 6177, "text": "Home RTO > Earnings & Renter RTO < Earnings Threshold: The opposite of the last scenario. Here, the renter still has to prove themselves, but they may wish to accelerate their earnings by negotiating for a higher earnings percentage." }, { "code": null, "e": 6502, "s": 6411, "text": "Skip this section if you’d like to get right to the demo of the decentralized application." }, { "code": null, "e": 6603, "s": 6502, "text": "The business logic discussed above is codified in the following smart contract, written in Solidity." }, { "code": null, "e": 6770, "s": 6603, "text": "If you’re familiar with object-oriented programming languages, most of the code should be pretty straightforward. I would like to highlight a couple of key functions:" }, { "code": null, "e": 7157, "s": 6770, "text": "getThePrice(): RTO should be pegged to the dollar to account for the volatility in the price of ETH. To normalize ETH payments, we need a way to access the current USD/ETH market price. Unfortunately, we can’t just call the CoinGecko API within Solidity, but we can access a “Price Feed”, which cleverly stores the price on-chain via a Chainlink aggregator interface. More on that here." }, { "code": null, "e": 7606, "s": 7157, "text": "payRent(address _to): This is the heart of the smart contract, so it deserves special consideration. First of all, we make sure that the payment is made from the home’s renter to its verified landlord. Next, as a payable function, we also facilitate the transfer of ETH (L119), the amount of which is stored in the transaction data. Finally, we calculate amountToMint (see the equation above) and update the balances of home and renter accordingly." }, { "code": null, "e": 8007, "s": 7606, "text": "I deployed the smart contract to the Ropsten Testnet using the Remix IDE and my Metamask wallet. Here are more detailed instructions if you’re interested. Before we move on to the application, we (as the contract deployer) need to add a verified landlord and sign the transaction using the same account that deployed the contract (representing a trusted administrator). We can do that right in Remix." }, { "code": null, "e": 8083, "s": 8007, "text": "We can also view our contract and all associated transactions on Etherscan." }, { "code": null, "e": 8717, "s": 8083, "text": "The application provides methods for us to use the smart contract functions through a payment portal-esque interface. I’m using Python’s FastAPI to create the API endpoints, the Web3.py library to prepare (but not sign, more on that in a second) the Ethereum transactions, and a basic PostgreSQL database to store some off-chain data, like URL’s to images of the homes. Rather than asking the user to hard-code their private keys into the application itself (a SERIOUS security risk), we sign transactions using the popular Metamask browser extension. For example, we generate the transaction data for the payRent function like this:" }, { "code": null, "e": 9065, "s": 8717, "text": "# from transactions.pydef payRent(landlord, amount_eth): txn_dict = to_contract.functions.payRent(w3.toChecksumAddress(landlord)).buildTransaction({ 'chainId': 3, 'value': w3.toWei(float(amount_eth), 'ether'), 'gas': 2000000, 'gasPrice': w3.toWei('2', 'gwei') }) return txn_dict" }, { "code": null, "e": 9136, "s": 9065, "text": "We can then send this data to Metamask with a few lines of JavaScript:" }, { "code": null, "e": 9718, "s": 9136, "text": "# from confirm_transaction.htmlsendTxnButton.addEventListener('click', () => { sendTxnButton.disabled = true; sendTxnButton.innerHTML = \"Connecting to Metamask...\"; ethereum .request({ method: 'eth_sendTransaction', params: [ { from: ethereum.selectedAddress, to: \"{{contract_address}}\", value: \"{{value}}\", gasPrice: '0x4A817C800', gas: '0x1E8480', data: \"{{txn_data}}\", chainId: '0x3' }, ], }) .then((txHash) => logTransaction(txHash)) .catch((error) => console.error);});" }, { "code": null, "e": 9817, "s": 9718, "text": "The full project code, with instructions of how to run the demo application, can be accessed here." }, { "code": null, "e": 10127, "s": 9817, "text": "Now for a quick demo that demonstrates functionality from the perspectives of both landlord and renter. Before the tenant and home can start earning RTO, our landlord will have to add their property to the smart contract. They can do that by navigating to the “View Listings” tab and filling out a quick form." }, { "code": null, "e": 10490, "s": 10127, "text": "Some of these values, like the street address and description, will be stored in our off-chain database. Others, like the down payment (aka earnings threshold) and earnings percentage, will be stored in the smart contract. This page simply prepares the function details, but they will then be asked to explicitly sign the transaction using their Metamask wallet." }, { "code": null, "e": 10647, "s": 10490, "text": "Once the asynchronously-executed transaction is approved, we can view our fancy new listing, along with the immutable details read directly from the ledger." }, { "code": null, "e": 10753, "s": 10647, "text": "Now that our home has been added, let’s make a dent in that earnings threshold and start mining some RTO." }, { "code": null, "e": 10832, "s": 10753, "text": "Clicking the “Connect Wallet” button brings us to a page that looks like this:" }, { "code": null, "e": 11162, "s": 10832, "text": "The bright orange “Connect Metamask” button will open up a prompt from the browser extension that informs us that our application would like to (for now) simply read our wallet address. When we accept, our active ETH address will magically appear in our application page. Let’s go ahead and check our RTO balance for this wallet." }, { "code": null, "e": 11360, "s": 11162, "text": "Since we haven’t made any rent payments, of course we don’t have any tokens. To do this, we navigate to the “Pay Rent” tab, fill in our payment amount (in ETH), and the ETH address of our landlord." }, { "code": null, "e": 11467, "s": 11360, "text": "Again, the actual transaction signing and private key management is decoupled from the application itself." }, { "code": null, "e": 11708, "s": 11467, "text": "In this case, our simulated rent payment was 0.01 ETH, or about $20 (maybe it’s more of a tent than a home). Given an earnings percentage of 30%, we should mine about 6–7 RTO for this transaction. Let’s go ahead and check our balance again:" }, { "code": null, "e": 11790, "s": 11708, "text": "And the same amount has also been applied to the home listing (see Balance Paid):" }, { "code": null, "e": 11912, "s": 11790, "text": "Interestingly, like any ERC20 token, we can also view our balance right in Metamask by adding the smart contract address!" }, { "code": null, "e": 12846, "s": 11912, "text": "This application was relatively simple to develop, but it demonstrates some significant concepts. Renters cannot fabricate their RTO balance, or obtain tokens through any other means other than steadily paying rent. Similarly, while landlords have strong incentives to participate in this network (motivated renters, guaranteed pre-sale earnings, no need to engage with centralized property management), their RTO balance is also on public display. Under traditional frameworks, establishing this trustless interaction would require painstaking recordkeeping and the threat of strong consequences to disincentivize fraudulent behavior. But with a robust public blockchain, accessing these benefits is trivial. We hear a lot about “Yield Farming”, leveraged trading, and other complicated DeFi instruments, but the most sustainable applications of cryptocurrencies involve re-thinking how we establish trust in everyday relationships." } ]
How to catch EnvironmentError Exception in Python?
EnvironmentError is the base class for errors that come from outside of Python (the operating system, filesystem, etc.). EnvironmentError Exception is a subclass of the StandarError class. It is the base class for IOError and OSError exceptions. It is not actually raised unlike its subclass errors like IOError and OSError. Any example of an IOError or OSError should be an example of Environment Error as well. import sys try: f = open ( "JohnDoe.txt", 'r' ) except Exception as e: print e print sys.exc_type [Errno 2] No such file or directory: 'JohnDoe.txt' <type 'exceptions.IOError'>
[ { "code": null, "e": 1387, "s": 1062, "text": "EnvironmentError is the base class for errors that come from outside of Python (the operating system, filesystem, etc.). EnvironmentError Exception is a subclass of the StandarError class. It is the base class for IOError and OSError exceptions. It is not actually raised unlike its subclass errors like IOError and OSError." }, { "code": null, "e": 1475, "s": 1387, "text": "Any example of an IOError or OSError should be an example of Environment Error as well." }, { "code": null, "e": 1573, "s": 1475, "text": "import sys\ntry:\nf = open ( \"JohnDoe.txt\", 'r' )\nexcept Exception as e:\nprint e\nprint sys.exc_type" }, { "code": null, "e": 1652, "s": 1573, "text": "[Errno 2] No such file or directory: 'JohnDoe.txt'\n<type 'exceptions.IOError'>" } ]
Using PyFlux To Predict Temperature Data | by Michael Grogan | Towards Data Science
PyFlux is a time series library built for Python, which integrates probability modelling with time series analysis. In this example, let us see how this library can be used to predict temperature patterns for Dublin Airport, Ireland, using monthly data from November 1941 — January 2018. Here is a short overview of the data: meant stands for mean temperature, and it is this variable that we are interested in forecasting using PyFlux. To configure the ARIMA model within PyFlux, we must specify: the probability distribution the autoregressive (AR) term the moving average (MA) term Let’s plot a histogram of the mean monthly temperature data: While no set of data ever perfectly approximates a normal distribution, the shape of the histogram above broadly indicates that the data follows this pattern. In this regard, pf.Normal() will be specified as the distribution when building the model. The lag drop-off for the partial autocorrelation function will be used to determine the AR term, while the lag drop-off for the autocorrelation function on the differenced series is used to determine the MA term. More information on determination of AR and MA terms can be found here. From examining the partial autocorrelation function, we can see that the correlation has dropped off at lag 2. In this regard, the AR term in the model is set to 2. Now, let’s examine the autocorrelation function for the differenced series. Here, we see that the correlation has dropped off at lag 3. Accordingly, the MA term in the model is set to 3. Now that the probability distribution, along with the AR and MA terms have been identified, the model can be defined accordingly. model = pf.ARIMA(data=train, ar=2, ma=3, target='meant', family=pf.Normal()) The maximum likelihood point mass estimate is used to estimate the latent variables, in the same manner as used in the PyFlux documentation: >>> x = model.fit("MLE")>>> x.summary()Normal ARIMA(2,0,3) ======================================================= ==================================================Dependent Variable: meant Method: MLE Start Date: 4 Log Likelihood: -1552.9713 End Date: 821 AIC: 3119.9426 Number of observations: 818 BIC: 3152.8907 ====================================================================Latent Variable Estimate Std Error z P>|z| 95% C.I. ======================================== ========== ========== Constant 2.1524 0.0809 26.597 0.0 (1.9938 | 2.311) AR(1) 1.6733 0.0168 99.6646 0.0 (1.6404 | 1.7063) AR(2) -0.8992 0.0029 -310.825 0.0 (-0.9048 | -0.8935) MA(1) -0.6943 0.0466 -14.8874 0.0 (-0.7857 | -0.6029) MA(2) 0.3329 0.048 6.9348 0.0 (0.2388 | 0.427) MA(3) 0.0402 0.0547 0.7348 0.4625 (-0.067 | 0.1475) Normal Scale 1.9222 ==================================================================== Now, the model fit and predictions can be plotted: model.plot_fit(figsize=(15,10)) Given that a seasonal component has not been specified in this model, the probability forecast does seem to pick up the highs and lows in the data quite well. Moreover, the probability forecasts can be of use in predicting extreme weather patterns. For instance, we see that during lower temperatures in winter, the graph illustrates a mean temperature of about 5°C. However, the probability bounds also illustrate that during particularly cold winters, this could drop to between 0°C and -5°C. Conversely, the summer months show a mean temperature of 15°C, but this could potentially rise to between 20°C and 25°C during hotter summer months. In this example, you have seen: How PyFlux can be used to probabilistically make forecasts using an ARIMA model Configuration of an ARIMA model within PyFlux Interpretation of forecasts made using the model Many thanks for your time, and the relevant code and datasets can be found here. 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 parties mentioned in this article. GitHub: RJT1990/pyflux Identifying the numbers of AR or MA terms in an ARIMA model Met Eireann: Historical Weather Data PyFlux Documentation: ARIMA Models
[ { "code": null, "e": 288, "s": 172, "text": "PyFlux is a time series library built for Python, which integrates probability modelling with time series analysis." }, { "code": null, "e": 460, "s": 288, "text": "In this example, let us see how this library can be used to predict temperature patterns for Dublin Airport, Ireland, using monthly data from November 1941 — January 2018." }, { "code": null, "e": 498, "s": 460, "text": "Here is a short overview of the data:" }, { "code": null, "e": 609, "s": 498, "text": "meant stands for mean temperature, and it is this variable that we are interested in forecasting using PyFlux." }, { "code": null, "e": 670, "s": 609, "text": "To configure the ARIMA model within PyFlux, we must specify:" }, { "code": null, "e": 699, "s": 670, "text": "the probability distribution" }, { "code": null, "e": 728, "s": 699, "text": "the autoregressive (AR) term" }, { "code": null, "e": 757, "s": 728, "text": "the moving average (MA) term" }, { "code": null, "e": 818, "s": 757, "text": "Let’s plot a histogram of the mean monthly temperature data:" }, { "code": null, "e": 1068, "s": 818, "text": "While no set of data ever perfectly approximates a normal distribution, the shape of the histogram above broadly indicates that the data follows this pattern. In this regard, pf.Normal() will be specified as the distribution when building the model." }, { "code": null, "e": 1353, "s": 1068, "text": "The lag drop-off for the partial autocorrelation function will be used to determine the AR term, while the lag drop-off for the autocorrelation function on the differenced series is used to determine the MA term. More information on determination of AR and MA terms can be found here." }, { "code": null, "e": 1518, "s": 1353, "text": "From examining the partial autocorrelation function, we can see that the correlation has dropped off at lag 2. In this regard, the AR term in the model is set to 2." }, { "code": null, "e": 1594, "s": 1518, "text": "Now, let’s examine the autocorrelation function for the differenced series." }, { "code": null, "e": 1705, "s": 1594, "text": "Here, we see that the correlation has dropped off at lag 3. Accordingly, the MA term in the model is set to 3." }, { "code": null, "e": 1835, "s": 1705, "text": "Now that the probability distribution, along with the AR and MA terms have been identified, the model can be defined accordingly." }, { "code": null, "e": 1912, "s": 1835, "text": "model = pf.ARIMA(data=train, ar=2, ma=3, target='meant', family=pf.Normal())" }, { "code": null, "e": 2053, "s": 1912, "text": "The maximum likelihood point mass estimate is used to estimate the latent variables, in the same manner as used in the PyFlux documentation:" }, { "code": null, "e": 3512, "s": 2053, "text": ">>> x = model.fit(\"MLE\")>>> x.summary()Normal ARIMA(2,0,3) ======================================================= ==================================================Dependent Variable: meant Method: MLE Start Date: 4 Log Likelihood: -1552.9713 End Date: 821 AIC: 3119.9426 Number of observations: 818 BIC: 3152.8907 ====================================================================Latent Variable Estimate Std Error z P>|z| 95% C.I. ======================================== ========== ========== Constant 2.1524 0.0809 26.597 0.0 (1.9938 | 2.311) AR(1) 1.6733 0.0168 99.6646 0.0 (1.6404 | 1.7063) AR(2) -0.8992 0.0029 -310.825 0.0 (-0.9048 | -0.8935) MA(1) -0.6943 0.0466 -14.8874 0.0 (-0.7857 | -0.6029) MA(2) 0.3329 0.048 6.9348 0.0 (0.2388 | 0.427) MA(3) 0.0402 0.0547 0.7348 0.4625 (-0.067 | 0.1475) Normal Scale 1.9222 ====================================================================" }, { "code": null, "e": 3563, "s": 3512, "text": "Now, the model fit and predictions can be plotted:" }, { "code": null, "e": 3595, "s": 3563, "text": "model.plot_fit(figsize=(15,10))" }, { "code": null, "e": 3844, "s": 3595, "text": "Given that a seasonal component has not been specified in this model, the probability forecast does seem to pick up the highs and lows in the data quite well. Moreover, the probability forecasts can be of use in predicting extreme weather patterns." }, { "code": null, "e": 4090, "s": 3844, "text": "For instance, we see that during lower temperatures in winter, the graph illustrates a mean temperature of about 5°C. However, the probability bounds also illustrate that during particularly cold winters, this could drop to between 0°C and -5°C." }, { "code": null, "e": 4239, "s": 4090, "text": "Conversely, the summer months show a mean temperature of 15°C, but this could potentially rise to between 20°C and 25°C during hotter summer months." }, { "code": null, "e": 4271, "s": 4239, "text": "In this example, you have seen:" }, { "code": null, "e": 4351, "s": 4271, "text": "How PyFlux can be used to probabilistically make forecasts using an ARIMA model" }, { "code": null, "e": 4397, "s": 4351, "text": "Configuration of an ARIMA model within PyFlux" }, { "code": null, "e": 4446, "s": 4397, "text": "Interpretation of forecasts made using the model" }, { "code": null, "e": 4527, "s": 4446, "text": "Many thanks for your time, and the relevant code and datasets can be found here." }, { "code": null, "e": 4905, "s": 4527, "text": "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 parties mentioned in this article." }, { "code": null, "e": 4928, "s": 4905, "text": "GitHub: RJT1990/pyflux" }, { "code": null, "e": 4988, "s": 4928, "text": "Identifying the numbers of AR or MA terms in an ARIMA model" }, { "code": null, "e": 5025, "s": 4988, "text": "Met Eireann: Historical Weather Data" } ]
What is overloading in C#?
C# provides two techniques to implement static polymorphism − Function overloading Operator overloading Two or more than two methods having the same name but different parameters is what we call function overloading in C#. Function overloading in C# can be performed by changing the number of arguments and the data type of the arguments. Let’s say you have a function that prints multiplication of numbers, then our overloaded methods will have the same name but different number of arguments − public static int mulDisplay(int one, int two) { } public static int mulDisplay(int one, int two, int three) { } public static int mulDisplay(int one, int two, int three, int four) { } The following is an example showing how to implement function overloading − Live Demo using System; public class Demo { public static int mulDisplay(int one, int two) { return one * two; } public static int mulDisplay(int one, int two, int three) { return one * two * three; } public static int mulDisplay(int one, int two, int three, int four) { return one * two * three * four; } } public class Program { public static void Main() { Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15)); Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20)); Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7)); } } Multiplication of two numbers: 150 Multiplication of three numbers: 2080 Multiplication of four numbers: 1470 Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. The following shows which operators can be overloaded and which you cannot overload −
[ { "code": null, "e": 1124, "s": 1062, "text": "C# provides two techniques to implement static polymorphism −" }, { "code": null, "e": 1145, "s": 1124, "text": "Function overloading" }, { "code": null, "e": 1166, "s": 1145, "text": "Operator overloading" }, { "code": null, "e": 1285, "s": 1166, "text": "Two or more than two methods having the same name but different parameters is what we call function overloading in C#." }, { "code": null, "e": 1401, "s": 1285, "text": "Function overloading in C# can be performed by changing the number of arguments and the data type of the arguments." }, { "code": null, "e": 1558, "s": 1401, "text": "Let’s say you have a function that prints multiplication of numbers, then our overloaded methods will have the same name but different number of arguments −" }, { "code": null, "e": 1743, "s": 1558, "text": "public static int mulDisplay(int one, int two) { }\npublic static int mulDisplay(int one, int two, int three) { }\npublic static int mulDisplay(int one, int two, int three, int four) { }" }, { "code": null, "e": 1819, "s": 1743, "text": "The following is an example showing how to implement function overloading −" }, { "code": null, "e": 1830, "s": 1819, "text": " Live Demo" }, { "code": null, "e": 2494, "s": 1830, "text": "using System;\npublic class Demo {\n public static int mulDisplay(int one, int two) {\n return one * two;\n }\n\n public static int mulDisplay(int one, int two, int three) {\n return one * two * three;\n }\n \n public static int mulDisplay(int one, int two, int three, int four) {\n return one * two * three * four;\n }\n}\n\npublic class Program {\n public static void Main() {\n Console.WriteLine(\"Multiplication of two numbers: \"+Demo.mulDisplay(10, 15));\n Console.WriteLine(\"Multiplication of three numbers: \"+Demo.mulDisplay(8, 13, 20));\n Console.WriteLine(\"Multiplication of four numbers: \"+Demo.mulDisplay(3, 7, 10, 7));\n }\n}" }, { "code": null, "e": 2604, "s": 2494, "text": "Multiplication of two numbers: 150\nMultiplication of three numbers: 2080\nMultiplication of four numbers: 1470" }, { "code": null, "e": 2734, "s": 2604, "text": "Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined." }, { "code": null, "e": 2820, "s": 2734, "text": "The following shows which operators can be overloaded and which you cannot overload −" } ]
How to create a new column in an R data frame based on some condition of another column?
Sometimes we want to change a column or create a new by using other columns of a data frame in R, this is mostly required when we want to create a categorical column but it can be done for numerical columns as well. For example, we might want to create a column based on salary for which if salaries are greater than the salary in another column then adding those salaries otherwise taking the difference between them. This will help us to understand whether the salaries in two columns are equivalent, lesser, or greater. In R, we can use transform function for this purpose. Consider the below data frame: Live Demo > set.seed(1001) > x1<-rpois(20,1) > y1<-rpois(20,5) > df1<-data.frame(x1,y1) > df1 x1 y1 1 4 6 2 1 4 3 1 9 4 1 6 5 1 4 6 2 7 7 0 6 8 0 3 9 0 8 10 2 4 11 1 5 12 0 9 13 2 10 14 1 4 15 0 3 16 2 2 17 0 2 18 0 6 19 0 6 20 2 2 Creating a column z1 in which y1 will be subtracted from x1 if x1 is greater than y1, otherwise added: > df1<-transform(df1,z1=ifelse(x1>y1,x1-y1,x1+y1)) > df1 x1 y1 z1 1 4 6 10 2 1 4 5 3 1 9 10 4 1 6 7 5 1 4 5 6 2 7 9 7 0 6 6 8 0 3 3 9 0 8 8 10 2 4 6 11 1 5 6 12 0 9 9 13 2 10 12 14 1 4 5 15 0 3 3 16 2 2 4 17 0 2 2 18 0 6 6 19 0 6 6 20 2 2 4 > df2<-transform(df1,z1=ifelse(x1 df2 x1 y1 z1 1 4 6 2 2 1 4 3 3 1 9 8 4 1 6 5 5 1 4 3 6 2 7 5 7 0 6 6 8 0 3 3 9 0 8 8 10 2 4 2 11 1 5 4 12 0 9 9 13 2 10 8 14 1 4 3 15 0 3 3 16 2 2 4 17 0 2 2 18 0 6 6 19 0 6 6 20 2 2 4 > df3<-transform(df1,z1=ifelse(x1==y1,x1*y1,x1/y1)) > df3 x1 y1 z1 1 4 6 0.6666667 2 1 4 0.2500000 3 1 9 0.1111111 4 1 6 0.1666667 5 1 4 0.2500000 6 2 7 0.2857143 7 0 6 0.0000000 8 0 3 0.0000000 9 0 8 0.0000000 10 2 4 0.5000000 11 1 5 0.2000000 12 0 9 0.0000000 13 2 10 0.2000000 14 1 4 0.2500000 15 0 3 0.0000000 16 2 2 4.0000000 17 0 2 0.0000000 18 0 6 0.0000000 19 0 6 0.0000000 20 2 2 4.0000000
[ { "code": null, "e": 1639, "s": 1062, "text": "Sometimes we want to change a column or create a new by using other columns of a data frame in R, this is mostly required when we want to create a categorical column but it can be done for numerical columns as well. For example, we might want to create a column based on salary for which if salaries are greater than the salary in another column then adding those salaries otherwise taking the difference between them. This will help us to understand whether the salaries in two columns are equivalent, lesser, or greater. In R, we can use transform function for this purpose." }, { "code": null, "e": 1670, "s": 1639, "text": "Consider the below data frame:" }, { "code": null, "e": 1680, "s": 1670, "text": "Live Demo" }, { "code": null, "e": 1764, "s": 1680, "text": "> set.seed(1001)\n> x1<-rpois(20,1)\n> y1<-rpois(20,5)\n> df1<-data.frame(x1,y1)\n> df1" }, { "code": null, "e": 1933, "s": 1764, "text": " x1 y1\n1 4 6\n2 1 4\n3 1 9\n4 1 6\n5 1 4\n6 2 7\n7 0 6\n8 0 3\n9 0 8\n10 2 4 \n11 1 5\n12 0 9\n13 2 10\n14 1 4\n15 0 3\n16 2 2\n17 0 2\n18 0 6\n19 0 6\n20 2 2" }, { "code": null, "e": 2036, "s": 1933, "text": "Creating a column z1 in which y1 will be subtracted from x1 if x1 is greater than y1, otherwise added:" }, { "code": null, "e": 2093, "s": 2036, "text": "> df1<-transform(df1,z1=ifelse(x1>y1,x1-y1,x1+y1))\n> df1" }, { "code": null, "e": 2324, "s": 2093, "text": " x1 y1 z1\n1 4 6 10\n2 1 4 5\n3 1 9 10\n4 1 6 7\n5 1 4 5\n6 2 7 9\n7 0 6 6\n8 0 3 3\n9 0 8 8\n10 2 4 6\n11 1 5 6\n12 0 9 9\n13 2 10 12\n14 1 4 5\n15 0 3 3\n16 2 2 4\n17 0 2 2\n18 0 6 6\n19 0 6 6\n20 2 2 4" }, { "code": null, "e": 2362, "s": 2324, "text": "> df2<-transform(df1,z1=ifelse(x1 df2" }, { "code": null, "e": 2593, "s": 2362, "text": " x1 y1 z1\n1 4 6 2\n2 1 4 3\n3 1 9 8\n4 1 6 5\n5 1 4 3\n6 2 7 5\n7 0 6 6\n8 0 3 3\n9 0 8 8\n10 2 4 2\n11 1 5 4\n12 0 9 9\n13 2 10 8\n14 1 4 3\n15 0 3 3\n16 2 2 4\n17 0 2 2\n18 0 6 6\n19 0 6 6\n20 2 2 4" }, { "code": null, "e": 2651, "s": 2593, "text": "> df3<-transform(df1,z1=ifelse(x1==y1,x1*y1,x1/y1))\n> df3" }, { "code": null, "e": 2994, "s": 2651, "text": " x1 y1 z1\n1 4 6 0.6666667\n2 1 4 0.2500000\n3 1 9 0.1111111\n4 1 6 0.1666667\n5 1 4 0.2500000\n6 2 7 0.2857143\n7 0 6 0.0000000\n8 0 3 0.0000000\n9 0 8 0.0000000\n10 2 4 0.5000000\n11 1 5 0.2000000\n12 0 9 0.0000000\n13 2 10 0.2000000\n14 1 4 0.2500000\n15 0 3 0.0000000\n16 2 2 4.0000000\n17 0 2 0.0000000\n18 0 6 0.0000000\n19 0 6 0.0000000\n20 2 2 4.0000000" } ]
Anomaly Detection in Process Control Data with Machine Learning | by Nicholas Lewis | Towards Data Science
Anomaly detection is a powerful application of machine learning in a real-world situation. From detecting fraudulent transactions to forecasting component failure, we can train a machine learning model to determine when something out of the ordinary is occurring. When it comes to machine learning, I’m a huge advocate for learning by experiment. The actual math behind machine learning models can be a bit of a black box, but that doesn’t keep it from being useful; in fact, I feel like that’s one of the advantages of machine learning. You can apply the same algorithms to solving a whole gamut of problems. Sometimes, the best way to learn is to handle some real data and see what happens with it. In this example, we’ll be able to generate some real data with the Temperate Control Lab device and train a supervised classifier to detect anomalies. The TCLab is a great little device for generating real data with a simple plug-and-play Arduino device. If you want to create your own data for this, there are great introductory resources found here; otherwise, I included data I generated on my own TCLab device in the Github repository. If you want to run these examples on your own, you can download and follow the code here. The TCLab is a simple Arduino device with two heaters and two temperature sensors. It’s a simple plug and play device, with a plug to power the heaters and a USB port to communicate with the computer. The heater level can be adjusted in a Python script (be sure to pip install tclab), and the temperature sensor is used to read the temperature surrounding each heater. For this example, we’ll keep it basic and just use one heater and sensor, but the same principles could also be applied to the 2-heater system, or even more complex systems such as what you might find in a chemical refinery. We can imagine the problem as this: we have a heater for our garage workshop, with a simple on/off setting. We can program the heater to turn on or off for certain amounts of time each day to keep the temperature at a comfortable level. There are, of course, more sophisticated control systems we could use; however, this is designed as an introduction to anomaly detection with machine learning, so we’ll keep the raw data simple for now. Under normal circumstances, it’s a simple enough exercise to verify that the heater is on and doing its job — just look at the temperature and see if it’s going up. But what if there are external factors that complicate the evaluation? Maybe the garage door was left open and lets a draft in, or perhaps some of your equipment starts overheating. Or worse yet, what if there’s a cyberattack on the temperature control, and it’s masked by the attackers? Is there a way to look at the data we’re gathering and determine when something is going wrong? This is the heart of anomaly detection. With a supervised classifier, we can look at the sensor data and train it to classify when the heater is on or off. Since we also know when the heater should be on or off, we can then apply the classifier to any new data coming in and determine whether the behavior lines up with the data we see. If the two don’t match, we know there’s an anomaly of some type, and can investigate further. To simulate this scenario, we’ll generate a data file from the TCLab, turning the heater on and off at different intervals. If you’re having trouble with your TCLab setup, there are some great troubleshooting resources here. To start, we’ll set up a few arrays to store the data, which we’ll collect in 1 second intervals. The heater on/off cycling will be pretty simple for now, just turning it all the way on or off and leaving it for a few minutes. We’ll run for an hour to make sure we have lots of data to train and validate on. # Run time in minutes run_time = 60.0 # 1 cycle per second cycles = int(60.0*run_time) # Time array tm = np.array(range(cycles)).astype(float) ### Generate on/off inputs for heater 1 (Q1) ### Q1 = np.zeros(cycles) end = 15 # leave 1st 15 seconds of Q1 as 0 on = False while end <= cycles: start = end end += random.randint(150,300) # keep new Q1 value for varied amount of time on = not on if on: Q1[start:end] = 1 else: Q1[start:end] = 0 The TCLab inputs are straightforward, setting lab.Q1 to either on or off, depending on what we generated. We only turn the heater on 70% to avoid overheating, and then record the temperature at each time point from lab.T1 . Finally, let the loop delay for 1 second. # Connect to Arduino and generate anomaly-free data with tclab.TCLab() as lab: # Print current T1, T2 print('Temperature 1: {0:0.2f} °C'.format(lab.T1)) print('Temperature 2: {0:0.2f} °C'.format(lab.T2)) # Temperature (C) T1 = np.ones(cycles) * lab.T1 # measured T (degC) # Run TCLab to generate training data start_time = time.time() for i in range(cycles): # Record time t = time.time() tm[i] = t - start_time # Turn on heater to 70% when Q1 is 1 lab.Q1(Q1[i] * 70) # Record T1 (degC) T1[i] = lab.T1 # Delay 1 second while time.time() < t + 1.0: pass The anomalous data is created in basically the same way, but with only 20 minutes. The big difference is that I blow a fan across the heater at a specified time, simulating a draft in the garage. The convection from the fan will naturally cool the system, counteracting what the heater is trying to do. Since this is unanticipated, we should see the classifier pick this up — perhaps indicating the heater is off when we know it’s on. Let’s go ahead and find out if it works! One of the keys to machine learning is investigating how to frame your data in a way that is useful for the model. When I do any project in machine learning, this is often the most time-consuming step. If I get it right, the model works like a charm; otherwise, I can spend hours or even days of frustration, wondering why my model won’t work. You should always scale your data for machine learning applications, and this can easily be done with the MinMaxScaler from scikit-learn. In addition, check that the format of your data is correct for the model (for example, does the shape of a numpy array match what the classifier expects? If not, you’ll likely get a warning). Let’s see what this looks like so far. Note that we don’t scale the y data because it’s already just 0's and 1's. # Split into input and output data Xtrain = train[['T1']].values ytrain = train[['Q1']].values # Formatting shape of y data to remove warning ytrain = np.ravel(ytrain) # Scale s = MinMaxScaler() Xtrain_s = s.fit_transform(Xtrain) You’ll notice that our input is just the temperature, and the output we’re trying to predict is the heater status (on or off). Is this effective? Can the classifier tell if the heater is on or off based only on the temperature? Thankfully with scikit-learn, training and predicting with a supervised classifier is just a few lines of code. We’ll also be using the Logistic Regression classifier, but there are many other supervised classifiers you could use. # Load classifier model; default hyperparameters lr = LogisticRegression() # Fit classifier on training data and predict lr.fit(Xtrain_s,ytrain) yp = lr.predict(Xtrain_s) train['LR_predict'] = yp Plotting the results yields this: The answer to if we can just use the raw temperature as the input is an emphatic no. This makes intuitive sense — for example, at 35°C, the heater is either on or off. However, the change in temperature would tell us a whole lot about what the heater is doing. This introduces the realm of feature engineering, another important part of setting up a problem for machine learning. We can create additional features out of what we already have. What other data can we glean from just the raw temperature? We can get the 1st and 2nd derivatives, the standard deviation over the past few readings, and even look at long-term difference trends. Another trick to try is log scaling the data, especially if it’s log distributed. These are all new features, and some of them may just well be the silver bullet to feed into the classifier for good performance! Again, some domain knowledge and intuition of the specific problem is really useful for feature engineering. Let’s start with looking at the change in temperature. There’s a bit of sensor noise, and so taking a rolling average of the temperature gives a nicer plot that will likely result in better performance. Let’s see how that does. The only difference is that we create the dT column in our dataframe and use that as the input feature. We also have to drop any data with NaN values. The result...is pretty good! There are a few misses, but those are always on the edge when the heater has just turned on or off. We could look into more features such as the 2nd derivative that might help with this, but for now, this looks like it will do the trick. Best practice before setting out to use the trained classifier dictates validating the performance on data that has never been seen. I personally like to try it out on the original training data initially, just as a gut check; if it doesn’t work there, it won’t work on new data. However, we saw that it worked well on the above data, so let’s do this check now on a new set of data. You can either generate a new anomaly-free data file from the TCLab, or use the train_test_split from scikit-learn. Note that we only use the transform feature on the data scaling, since we’ve already fit the scaler and used that scaling to train the classifier. Here’s a plot of the results: It checks out. Again, there are the fringe cases when the heater turns on or off. We could look into additional features to feed into the classifier, or even change the hyperparameters for the classifier, but for a simple demo, this is sufficient. Here is where the rubber hits the road. We know the classifier works well to tell us when the heater is on or off. Can it tell us when something unexpected is happening? The process is really the same. The only difference is now we have an anomaly in the data. We’ll create the new feature (change in temperature, using the smoothed rolling average), scale the data, and feed it into the classifier to predict. Here are the results: This looks like it worked well! We see the prediction is that the heater is off when the fan is running, when in reality the heater is on, there’s just an anomalous event. Even after the fan goes off, the system is re-equilibrating, so there’s some additional mismatch between what’s actually going on with the heater and what the classifier is predicting. If an operator is looking at the data coming in, they can compare what they expect the heater to be doing and what the classifier is predicting; any discrepancies indicate an anomaly that can be investigated. This was a neat experiment with just one type of anomaly, using data that we generated right here on our tabletop! Sure it’s simple, but these kinds of problems can quickly become complex. The guiding principles are the same, though. What other anomalous events might happen? We could simulate anomalous outside heat by turning on heater 2. We could simulate colder ambient temperature by running the TCLab in a colder room. There’s also a neat trick with these devices: if you make a cell phone call near the sensor, the waves interfere with the signal and you can get a completely new type of anomaly. What kinds of features would be useful for detecting these other types of anomalies? Could we tune the hyperparameters to improve the performance? Finally, perhaps my favorite strategy when it comes to classifiers is to train several different classifiers, and then take an aggregate score. Go ahead and try out some other types of classifiers from scikit-learn. Which ones work well? Which don’t? If you find 4 or 5 that work pretty well, you could train all of them, and then only flag something as an anomaly if a majority of classifiers show a mismatch. Was this helpful? Did you like being able to generate your own data? What other ideas have you found useful for anomaly detection? Thanks for reading, and I hope this introduction opened up some new ideas for your own projects.
[ { "code": null, "e": 435, "s": 171, "text": "Anomaly detection is a powerful application of machine learning in a real-world situation. From detecting fraudulent transactions to forecasting component failure, we can train a machine learning model to determine when something out of the ordinary is occurring." }, { "code": null, "e": 872, "s": 435, "text": "When it comes to machine learning, I’m a huge advocate for learning by experiment. The actual math behind machine learning models can be a bit of a black box, but that doesn’t keep it from being useful; in fact, I feel like that’s one of the advantages of machine learning. You can apply the same algorithms to solving a whole gamut of problems. Sometimes, the best way to learn is to handle some real data and see what happens with it." }, { "code": null, "e": 1402, "s": 872, "text": "In this example, we’ll be able to generate some real data with the Temperate Control Lab device and train a supervised classifier to detect anomalies. The TCLab is a great little device for generating real data with a simple plug-and-play Arduino device. If you want to create your own data for this, there are great introductory resources found here; otherwise, I included data I generated on my own TCLab device in the Github repository. If you want to run these examples on your own, you can download and follow the code here." }, { "code": null, "e": 1996, "s": 1402, "text": "The TCLab is a simple Arduino device with two heaters and two temperature sensors. It’s a simple plug and play device, with a plug to power the heaters and a USB port to communicate with the computer. The heater level can be adjusted in a Python script (be sure to pip install tclab), and the temperature sensor is used to read the temperature surrounding each heater. For this example, we’ll keep it basic and just use one heater and sensor, but the same principles could also be applied to the 2-heater system, or even more complex systems such as what you might find in a chemical refinery." }, { "code": null, "e": 2436, "s": 1996, "text": "We can imagine the problem as this: we have a heater for our garage workshop, with a simple on/off setting. We can program the heater to turn on or off for certain amounts of time each day to keep the temperature at a comfortable level. There are, of course, more sophisticated control systems we could use; however, this is designed as an introduction to anomaly detection with machine learning, so we’ll keep the raw data simple for now." }, { "code": null, "e": 3025, "s": 2436, "text": "Under normal circumstances, it’s a simple enough exercise to verify that the heater is on and doing its job — just look at the temperature and see if it’s going up. But what if there are external factors that complicate the evaluation? Maybe the garage door was left open and lets a draft in, or perhaps some of your equipment starts overheating. Or worse yet, what if there’s a cyberattack on the temperature control, and it’s masked by the attackers? Is there a way to look at the data we’re gathering and determine when something is going wrong? This is the heart of anomaly detection." }, { "code": null, "e": 3416, "s": 3025, "text": "With a supervised classifier, we can look at the sensor data and train it to classify when the heater is on or off. Since we also know when the heater should be on or off, we can then apply the classifier to any new data coming in and determine whether the behavior lines up with the data we see. If the two don’t match, we know there’s an anomaly of some type, and can investigate further." }, { "code": null, "e": 3641, "s": 3416, "text": "To simulate this scenario, we’ll generate a data file from the TCLab, turning the heater on and off at different intervals. If you’re having trouble with your TCLab setup, there are some great troubleshooting resources here." }, { "code": null, "e": 3950, "s": 3641, "text": "To start, we’ll set up a few arrays to store the data, which we’ll collect in 1 second intervals. The heater on/off cycling will be pretty simple for now, just turning it all the way on or off and leaving it for a few minutes. We’ll run for an hour to make sure we have lots of data to train and validate on." }, { "code": null, "e": 4430, "s": 3950, "text": "# Run time in minutes\nrun_time = 60.0\n\n# 1 cycle per second\ncycles = int(60.0*run_time)\n\n# Time array\ntm = np.array(range(cycles)).astype(float)\n\n### Generate on/off inputs for heater 1 (Q1) ###\nQ1 = np.zeros(cycles)\n\nend = 15 # leave 1st 15 seconds of Q1 as 0\non = False\nwhile end <= cycles:\n start = end\n end += random.randint(150,300) # keep new Q1 value for varied amount of time\n on = not on\n if on:\n Q1[start:end] = 1\n else:\n Q1[start:end] = 0\n" }, { "code": null, "e": 4696, "s": 4430, "text": "The TCLab inputs are straightforward, setting lab.Q1 to either on or off, depending on what we generated. We only turn the heater on 70% to avoid overheating, and then record the temperature at each time point from lab.T1 . Finally, let the loop delay for 1 second." }, { "code": null, "e": 5374, "s": 4696, "text": "# Connect to Arduino and generate anomaly-free data\nwith tclab.TCLab() as lab: \n\n # Print current T1, T2\n print('Temperature 1: {0:0.2f} °C'.format(lab.T1))\n print('Temperature 2: {0:0.2f} °C'.format(lab.T2))\n\n # Temperature (C)\n T1 = np.ones(cycles) * lab.T1 # measured T (degC)\n\n # Run TCLab to generate training data\n start_time = time.time()\n\n for i in range(cycles):\n # Record time\n t = time.time()\n tm[i] = t - start_time\n\n # Turn on heater to 70% when Q1 is 1\n lab.Q1(Q1[i] * 70)\n\n # Record T1 (degC)\n T1[i] = lab.T1\n\n # Delay 1 second\n while time.time() < t + 1.0:\n pass\n" }, { "code": null, "e": 5850, "s": 5374, "text": "The anomalous data is created in basically the same way, but with only 20 minutes. The big difference is that I blow a fan across the heater at a specified time, simulating a draft in the garage. The convection from the fan will naturally cool the system, counteracting what the heater is trying to do. Since this is unanticipated, we should see the classifier pick this up — perhaps indicating the heater is off when we know it’s on. Let’s go ahead and find out if it works!" }, { "code": null, "e": 6194, "s": 5850, "text": "One of the keys to machine learning is investigating how to frame your data in a way that is useful for the model. When I do any project in machine learning, this is often the most time-consuming step. If I get it right, the model works like a charm; otherwise, I can spend hours or even days of frustration, wondering why my model won’t work." }, { "code": null, "e": 6638, "s": 6194, "text": "You should always scale your data for machine learning applications, and this can easily be done with the MinMaxScaler from scikit-learn. In addition, check that the format of your data is correct for the model (for example, does the shape of a numpy array match what the classifier expects? If not, you’ll likely get a warning). Let’s see what this looks like so far. Note that we don’t scale the y data because it’s already just 0's and 1's." }, { "code": null, "e": 6871, "s": 6638, "text": "# Split into input and output data\nXtrain = train[['T1']].values\nytrain = train[['Q1']].values\n\n# Formatting shape of y data to remove warning\nytrain = np.ravel(ytrain)\n\n# Scale\ns = MinMaxScaler()\nXtrain_s = s.fit_transform(Xtrain)\n" }, { "code": null, "e": 7330, "s": 6871, "text": "You’ll notice that our input is just the temperature, and the output we’re trying to predict is the heater status (on or off). Is this effective? Can the classifier tell if the heater is on or off based only on the temperature? Thankfully with scikit-learn, training and predicting with a supervised classifier is just a few lines of code. We’ll also be using the Logistic Regression classifier, but there are many other supervised classifiers you could use." }, { "code": null, "e": 7528, "s": 7330, "text": "# Load classifier model; default hyperparameters\nlr = LogisticRegression()\n\n# Fit classifier on training data and predict\nlr.fit(Xtrain_s,ytrain)\nyp = lr.predict(Xtrain_s)\ntrain['LR_predict'] = yp\n" }, { "code": null, "e": 7562, "s": 7528, "text": "Plotting the results yields this:" }, { "code": null, "e": 7823, "s": 7562, "text": "The answer to if we can just use the raw temperature as the input is an emphatic no. This makes intuitive sense — for example, at 35°C, the heater is either on or off. However, the change in temperature would tell us a whole lot about what the heater is doing." }, { "code": null, "e": 8414, "s": 7823, "text": "This introduces the realm of feature engineering, another important part of setting up a problem for machine learning. We can create additional features out of what we already have. What other data can we glean from just the raw temperature? We can get the 1st and 2nd derivatives, the standard deviation over the past few readings, and even look at long-term difference trends. Another trick to try is log scaling the data, especially if it’s log distributed. These are all new features, and some of them may just well be the silver bullet to feed into the classifier for good performance!" }, { "code": null, "e": 8726, "s": 8414, "text": "Again, some domain knowledge and intuition of the specific problem is really useful for feature engineering. Let’s start with looking at the change in temperature. There’s a bit of sensor noise, and so taking a rolling average of the temperature gives a nicer plot that will likely result in better performance." }, { "code": null, "e": 8902, "s": 8726, "text": "Let’s see how that does. The only difference is that we create the dT column in our dataframe and use that as the input feature. We also have to drop any data with NaN values." }, { "code": null, "e": 9169, "s": 8902, "text": "The result...is pretty good! There are a few misses, but those are always on the edge when the heater has just turned on or off. We could look into more features such as the 2nd derivative that might help with this, but for now, this looks like it will do the trick." }, { "code": null, "e": 9816, "s": 9169, "text": "Best practice before setting out to use the trained classifier dictates validating the performance on data that has never been seen. I personally like to try it out on the original training data initially, just as a gut check; if it doesn’t work there, it won’t work on new data. However, we saw that it worked well on the above data, so let’s do this check now on a new set of data. You can either generate a new anomaly-free data file from the TCLab, or use the train_test_split from scikit-learn. Note that we only use the transform feature on the data scaling, since we’ve already fit the scaler and used that scaling to train the classifier." }, { "code": null, "e": 9846, "s": 9816, "text": "Here’s a plot of the results:" }, { "code": null, "e": 10094, "s": 9846, "text": "It checks out. Again, there are the fringe cases when the heater turns on or off. We could look into additional features to feed into the classifier, or even change the hyperparameters for the classifier, but for a simple demo, this is sufficient." }, { "code": null, "e": 10264, "s": 10094, "text": "Here is where the rubber hits the road. We know the classifier works well to tell us when the heater is on or off. Can it tell us when something unexpected is happening?" }, { "code": null, "e": 10505, "s": 10264, "text": "The process is really the same. The only difference is now we have an anomaly in the data. We’ll create the new feature (change in temperature, using the smoothed rolling average), scale the data, and feed it into the classifier to predict." }, { "code": null, "e": 10527, "s": 10505, "text": "Here are the results:" }, { "code": null, "e": 11093, "s": 10527, "text": "This looks like it worked well! We see the prediction is that the heater is off when the fan is running, when in reality the heater is on, there’s just an anomalous event. Even after the fan goes off, the system is re-equilibrating, so there’s some additional mismatch between what’s actually going on with the heater and what the classifier is predicting. If an operator is looking at the data coming in, they can compare what they expect the heater to be doing and what the classifier is predicting; any discrepancies indicate an anomaly that can be investigated." }, { "code": null, "e": 11327, "s": 11093, "text": "This was a neat experiment with just one type of anomaly, using data that we generated right here on our tabletop! Sure it’s simple, but these kinds of problems can quickly become complex. The guiding principles are the same, though." }, { "code": null, "e": 11844, "s": 11327, "text": "What other anomalous events might happen? We could simulate anomalous outside heat by turning on heater 2. We could simulate colder ambient temperature by running the TCLab in a colder room. There’s also a neat trick with these devices: if you make a cell phone call near the sensor, the waves interfere with the signal and you can get a completely new type of anomaly. What kinds of features would be useful for detecting these other types of anomalies? Could we tune the hyperparameters to improve the performance?" }, { "code": null, "e": 12255, "s": 11844, "text": "Finally, perhaps my favorite strategy when it comes to classifiers is to train several different classifiers, and then take an aggregate score. Go ahead and try out some other types of classifiers from scikit-learn. Which ones work well? Which don’t? If you find 4 or 5 that work pretty well, you could train all of them, and then only flag something as an anomaly if a majority of classifiers show a mismatch." } ]
What are sealed modifiers in C#?
When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method. Let us see an example − The following example won’t allow you to override the method display() because it has a sealed modifier for the ClassTwo derived class − ClassOne is our base class, whereas ClassTwo and ClassThree are derived classes − class ClassOne { public virtual void display() { Console.WriteLine("baseclass"); } } class ClassTwo : ClassOne { public sealed override void display() { Console.WriteLine("ClassTwoderivedClass"); } } class ClassThree : ClassTwo { public override void display() { Console.WriteLine("ClassThree: Another Derived Class"); } } Above, under ClassThree derived class we have tried to override the sealed method. This will show an error since it is not allowed when you use the sealed method.
[ { "code": null, "e": 1262, "s": 1062, "text": "When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method." }, { "code": null, "e": 1286, "s": 1262, "text": "Let us see an example −" }, { "code": null, "e": 1423, "s": 1286, "text": "The following example won’t allow you to override the method display() because it has a sealed modifier for the ClassTwo derived class −" }, { "code": null, "e": 1505, "s": 1423, "text": "ClassOne is our base class, whereas ClassTwo and ClassThree are derived classes −" }, { "code": null, "e": 1866, "s": 1505, "text": "class ClassOne {\n public virtual void display() {\n Console.WriteLine(\"baseclass\");\n }\n}\n\nclass ClassTwo : ClassOne {\n public sealed override void display() {\n Console.WriteLine(\"ClassTwoderivedClass\");\n }\n}\n\nclass ClassThree : ClassTwo {\n public override void display() {\n Console.WriteLine(\"ClassThree: Another Derived Class\");\n }\n}" }, { "code": null, "e": 2029, "s": 1866, "text": "Above, under ClassThree derived class we have tried to override the sealed method. This will show an error since it is not allowed when you use the sealed method." } ]
Convert C/C++ code to assembly language
Here we will see how to generate assembly language output from C or C++ source code using gcc. The gcc provides a great feature to get all intermediate outputs from a source code while executing. To get the assembler output we can use the option ‘-S’ for the gcc. This option shows the output after compiling, but before sending to the assembler. The syntax of this command is like below. gcc –S program.cpp Now, let us see how to output will be look like. Here we are using a simple program. In this program two numbers are stored into the variables x and y, then store the sum into another variable, after that print the result. #include <iostream> using namespace std; main() { int x, y, sum; x = 50; y = 60; sum = x + y; cout << "Sum is: " << sum << endl; } .file "test_cpp.cpp" .text .section .rodata .type _ZStL19piecewise_construct, @object .size _ZStL19piecewise_construct, 1 _ZStL19piecewise_construct: .zero 1 .local _ZStL8__ioinit .comm _ZStL8__ioinit,1,1 .LC0: .string "Sum is: " .text .globl main .type main, @function main: .LFB1493: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 subq $16, %rsp movl $50, -12(%rbp) movl $60, -8(%rbp) movl -12(%rbp), %edx movl -8(%rbp), %eax addl %edx, %eax movl %eax, -4(%rbp) leaq .LC0(%rip), %rsi leaq _ZSt4cout(%rip), %rdi call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT movq %rax, %rdx movl -4(%rbp), %eax movl %eax, %esi movq %rdx, %rdi call _ZNSolsEi@PLT movq %rax, %rdx movq _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip), %rax movq %rax, %rsi movq %rdx, %rdi call _ZNSolsEPFRSoS_E@PLT movl $0, %eax leave .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE1493: .size main, .-main .type _Z41__static_initialization_and_destruction_0ii, @function _Z41__static_initialization_and_destruction_0ii: .LFB1982: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 subq $16, %rsp movl %edi, -4(%rbp) movl %esi, -8(%rbp) cmpl $1, -4(%rbp) jne .L5 cmpl $65535, -8(%rbp) jne .L5 leaq _ZStL8__ioinit(%rip), %rdi call _ZNSt8ios_base4InitC1Ev@PLT leaq __dso_handle(%rip), %rdx leaq _ZStL8__ioinit(%rip), %rsi movq _ZNSt8ios_base4InitD1Ev@GOTPCREL(%rip), %rax movq %rax, %rdi call __cxa_atexit@PLT .L5: nop leave .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE1982: .size _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii .type _GLOBAL__sub_I_main, @function _GLOBAL__sub_I_main: .LFB1983: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl $65535, %esi movl $1, %edi call _Z41__static_initialization_and_destruction_0ii popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE1983: .size _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main .section .init_array,"aw" .align 8 .quad _GLOBAL__sub_I_main .hidden __dso_handle .ident "GCC: (Ubuntu 7.3.0-16ubuntu3) 7.3.0" .section .note.GNU-stack,"",@progbits
[ { "code": null, "e": 1157, "s": 1062, "text": "Here we will see how to generate assembly language output from C or C++ source code using gcc." }, { "code": null, "e": 1451, "s": 1157, "text": "The gcc provides a great feature to get all intermediate outputs from a source code while executing. To get the assembler output we can use the option ‘-S’ for the gcc. This option shows the output after compiling, but before sending to the assembler. The syntax of this command is like below." }, { "code": null, "e": 1470, "s": 1451, "text": "gcc –S program.cpp" }, { "code": null, "e": 1693, "s": 1470, "text": "Now, let us see how to output will be look like. Here we are using a simple program. In this program two numbers are stored into the variables x and y, then store the sum into another variable, after that print the result." }, { "code": null, "e": 1839, "s": 1693, "text": "#include <iostream>\nusing namespace std;\nmain() {\n int x, y, sum;\n x = 50;\n y = 60;\n sum = x + y;\n cout << \"Sum is: \" << sum << endl;\n}" }, { "code": null, "e": 4061, "s": 1839, "text": ".file \"test_cpp.cpp\"\n.text\n.section .rodata\n.type _ZStL19piecewise_construct, @object\n.size _ZStL19piecewise_construct, 1\n_ZStL19piecewise_construct:\n.zero 1\n.local _ZStL8__ioinit\n.comm _ZStL8__ioinit,1,1\n.LC0:\n.string \"Sum is: \"\n.text\n.globl main\n.type main, @function\nmain:\n.LFB1493:\n.cfi_startproc\npushq %rbp\n.cfi_def_cfa_offset 16\n.cfi_offset 6, -16\nmovq %rsp, %rbp\n.cfi_def_cfa_register 6\nsubq $16, %rsp\nmovl $50, -12(%rbp)\nmovl $60, -8(%rbp)\nmovl -12(%rbp), %edx\nmovl -8(%rbp), %eax\naddl %edx, %eax\nmovl %eax, -4(%rbp)\nleaq .LC0(%rip), %rsi\nleaq _ZSt4cout(%rip), %rdi\ncall _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT\nmovq %rax, %rdx\nmovl -4(%rbp), %eax\nmovl %eax, %esi\nmovq %rdx, %rdi\ncall _ZNSolsEi@PLT\nmovq %rax, %rdx\nmovq\n_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip),\n%rax\nmovq %rax, %rsi\nmovq %rdx, %rdi\ncall _ZNSolsEPFRSoS_E@PLT\nmovl $0, %eax\nleave\n.cfi_def_cfa 7, 8\nret\n.cfi_endproc\n.LFE1493:\n.size main, .-main\n.type _Z41__static_initialization_and_destruction_0ii, @function\n_Z41__static_initialization_and_destruction_0ii:\n.LFB1982:\n.cfi_startproc\npushq %rbp\n.cfi_def_cfa_offset 16\n.cfi_offset 6, -16\nmovq %rsp, %rbp\n.cfi_def_cfa_register 6\nsubq $16, %rsp\nmovl %edi, -4(%rbp)\nmovl %esi, -8(%rbp)\ncmpl $1, -4(%rbp)\njne .L5\ncmpl $65535, -8(%rbp)\njne .L5\nleaq _ZStL8__ioinit(%rip), %rdi\ncall _ZNSt8ios_base4InitC1Ev@PLT\nleaq __dso_handle(%rip), %rdx\nleaq _ZStL8__ioinit(%rip), %rsi\nmovq _ZNSt8ios_base4InitD1Ev@GOTPCREL(%rip), %rax\nmovq %rax, %rdi\ncall __cxa_atexit@PLT\n.L5:\nnop\nleave\n.cfi_def_cfa 7, 8\nret\n.cfi_endproc\n.LFE1982:\n.size _Z41__static_initialization_and_destruction_0ii,\n.-_Z41__static_initialization_and_destruction_0ii\n.type _GLOBAL__sub_I_main, @function\n_GLOBAL__sub_I_main:\n.LFB1983:\n.cfi_startproc\npushq %rbp\n.cfi_def_cfa_offset 16\n.cfi_offset 6, -16\nmovq %rsp, %rbp\n.cfi_def_cfa_register 6\nmovl $65535, %esi\nmovl $1, %edi\ncall _Z41__static_initialization_and_destruction_0ii\npopq %rbp\n.cfi_def_cfa 7, 8\nret\n.cfi_endproc\n.LFE1983:\n.size _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main\n.section .init_array,\"aw\"\n.align 8\n.quad _GLOBAL__sub_I_main\n.hidden __dso_handle\n.ident \"GCC: (Ubuntu 7.3.0-16ubuntu3) 7.3.0\"\n.section .note.GNU-stack,\"\",@progbits" } ]
Add the element in a Python list with help of indexing
A python list is a collection data type that is ordered and changeable. Also, it allows duplicate members. It is the most frequently used collection data type used in Python programs. We will see how we can add an element to a list using the index feature. But before adding the element in an existing link, let's access the elements in a list using the index feature. every element in the list is associated with an index and that is how the elements remain ordered. We can access the elements by looping through the indexes. The below program prints the elements at indices 1 and 2. The last index value is not included in the search. Live Demo vowels_list = ['a','i','o', 'u'] print(vowels_list[1:3]) Running the above code gives us the following result: ['i', 'o'] We can also use the same concept to add the element at a particular index. In the below program we are adding the element at index position 1. Live Demo vowels = ['a','i','o', 'u'] print("values before indexing are :",vowels) #index vowels.insert(1, 'e') print('\nafter adding the element at the index 1 is : ', vowels) Running the above code gives us the following result: values before indexing are : ['a', 'i', 'o', 'u'] after adding the element at the index 1 is : ['a', 'e', 'i', 'o', 'u']
[ { "code": null, "e": 1319, "s": 1062, "text": "A python list is a collection data type that is ordered and changeable. Also, it allows duplicate members. It is the most frequently used collection data type used in Python programs. We will see how we can add an element to a list using the index feature." }, { "code": null, "e": 1431, "s": 1319, "text": "But before adding the element in an existing link, let's access the elements in a list using the index feature." }, { "code": null, "e": 1699, "s": 1431, "text": "every element in the list is associated with an index and that is how the elements remain ordered. We can access the elements by looping through the indexes. The below program prints the elements at indices 1 and 2. The last index value is not included in the search." }, { "code": null, "e": 1710, "s": 1699, "text": " Live Demo" }, { "code": null, "e": 1767, "s": 1710, "text": "vowels_list = ['a','i','o', 'u']\nprint(vowels_list[1:3])" }, { "code": null, "e": 1821, "s": 1767, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 1832, "s": 1821, "text": "['i', 'o']" }, { "code": null, "e": 1975, "s": 1832, "text": "We can also use the same concept to add the element at a particular index. In the below program we are adding the element at index position 1." }, { "code": null, "e": 1986, "s": 1975, "text": " Live Demo" }, { "code": null, "e": 2155, "s": 1986, "text": "vowels = ['a','i','o', 'u']\n\nprint(\"values before indexing are :\",vowels)\n#index\nvowels.insert(1, 'e')\n\nprint('\\nafter adding the element at the index 1 is : ', vowels)" }, { "code": null, "e": 2209, "s": 2155, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2330, "s": 2209, "text": "values before indexing are : ['a', 'i', 'o', 'u']\nafter adding the element at the index 1 is : ['a', 'e', 'i', 'o', 'u']" } ]
Find column with maximum sum in a Matrix using C++.
Suppose we have a matrix of size M x N. We have to find the column, that has a maximum sum. In this program we will not follow some tricky approach, we will traverse the array column-wise, then get the sum of each column, if the sum is the max, then print the sum and the column index. #include<iostream> #define M 5 #define N 5 using namespace std; int colSum(int colIndex, int mat[M][N]){ int sum = 0; for(int i = 0; i<M; i++){ sum += mat[i][colIndex]; } return sum; } void maxColumnSum(int mat[M][N]) { int index = -1; int maxSum = INT_MIN; for (int i = 0; i < N; i++) { int sum = colSum(i, mat); if (sum > maxSum) { maxSum = sum; index = i; } } cout << "Index: " << index << ", Column Sum: " << maxSum; } int main() { int mat[M][N] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; maxColumnSum(mat); } Index: 4, Column Sum: 31
[ { "code": null, "e": 1348, "s": 1062, "text": "Suppose we have a matrix of size M x N. We have to find the column, that has a maximum sum. In this program we will not follow some tricky approach, we will traverse the array column-wise, then get the sum of each column, if the sum is the max, then print the sum and the column index." }, { "code": null, "e": 2031, "s": 1348, "text": "#include<iostream>\n#define M 5\n#define N 5\nusing namespace std;\nint colSum(int colIndex, int mat[M][N]){\n int sum = 0;\n for(int i = 0; i<M; i++){\n sum += mat[i][colIndex];\n }\n return sum;\n}\nvoid maxColumnSum(int mat[M][N]) {\n int index = -1;\n int maxSum = INT_MIN;\n for (int i = 0; i < N; i++) {\n int sum = colSum(i, mat);\n if (sum > maxSum) {\n maxSum = sum;\n index = i;\n }\n }\n cout << \"Index: \" << index << \", Column Sum: \" << maxSum;\n}\nint main() {\n int mat[M][N] = {\n { 1, 2, 3, 4, 5 },\n { 5, 3, 1, 4, 2 },\n { 5, 6, 7, 8, 9 },\n { 0, 6, 3, 4, 12 },\n { 9, 7, 12, 4, 3 },\n };\n maxColumnSum(mat);\n}" }, { "code": null, "e": 2056, "s": 2031, "text": "Index: 4, Column Sum: 31" } ]
How to change the state of react component on click? - GeeksforGeeks
11 Feb, 2022 To change the state of the React component is useful when you are working on a single page application, it simply replaces the content of the existing component for the user without reloading the webpage. We have to set initial state value inside constructor function and set click event handler of the element upon which click, results in changing state. Then pass the function to the click handler and change the state of the component inside the function using setState. The setState function used to change the state of the component directly or with the callback approach as mentioned below. Syntax: this.setState({ stateName : new-state-value}) this.setState(st => { st.stateName = new-state-value }) Example 1: This example illustrates how to change the state of the component on click. index.js: Javascript import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) App.js: Javascript import React, { Component } from 'react' class App extends Component { constructor(props){ super(props) // Set initial state this.state = {msg : 'Hi, There!'} // Binding this keyword this.handleClick = this.handleClick.bind(this) } handleClick(){ // Changing state this.setState({msg : 'Welcome to the React world!'}) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> {/* Set click handler */} <button onClick={this.handleClick}> Click here! </button> </div> ) }} export default App Output: Example 2: index.js: Javascript import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) App.js: Javascript import React, { Component } from 'react' class App extends Component { static defaultProps = { courseContent : [ 'JSX', 'React Props', 'React State', 'React Lifecycle Methods', 'React Event Handlers', 'React Router', 'React Hooks', 'Readux', 'React Context' ] } constructor(props){ super(props) // Set initial state this.state = {msg : 'React Course', content:''} // Binding this keyword this.handleClick = this.handleClick.bind(this) } renderContent(){ return ( <ul> {this.props.courseContent.map(content => ( <li>{content}</li> ))} </ul> ) } handleClick(){ // Changing state this.setState({ msg : 'Course Content', content : this.renderContent() }) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> <p>{this.state.content}</p> {/* Set click handler */} <button onClick={this.handleClick}> Click here to know contents! </button> </div> ) }} export default App Output: rkbhola5 react-js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? How to append HTML code to a div using JavaScript ? File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 27142, "s": 27114, "text": "\n11 Feb, 2022" }, { "code": null, "e": 27348, "s": 27142, "text": "To change the state of the React component is useful when you are working on a single page application, it simply replaces the content of the existing component for the user without reloading the webpage. " }, { "code": null, "e": 27740, "s": 27348, "text": "We have to set initial state value inside constructor function and set click event handler of the element upon which click, results in changing state. Then pass the function to the click handler and change the state of the component inside the function using setState. The setState function used to change the state of the component directly or with the callback approach as mentioned below." }, { "code": null, "e": 27748, "s": 27740, "text": "Syntax:" }, { "code": null, "e": 27794, "s": 27748, "text": "this.setState({ stateName : new-state-value})" }, { "code": null, "e": 27852, "s": 27794, "text": "this.setState(st => {\n st.stateName = new-state-value\n})" }, { "code": null, "e": 27939, "s": 27852, "text": "Example 1: This example illustrates how to change the state of the component on click." }, { "code": null, "e": 27949, "s": 27939, "text": "index.js:" }, { "code": null, "e": 27960, "s": 27949, "text": "Javascript" }, { "code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))", "e": 28099, "s": 27960, "text": null }, { "code": null, "e": 28107, "s": 28099, "text": "App.js:" }, { "code": null, "e": 28118, "s": 28107, "text": "Javascript" }, { "code": "import React, { Component } from 'react' class App extends Component { constructor(props){ super(props) // Set initial state this.state = {msg : 'Hi, There!'} // Binding this keyword this.handleClick = this.handleClick.bind(this) } handleClick(){ // Changing state this.setState({msg : 'Welcome to the React world!'}) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> {/* Set click handler */} <button onClick={this.handleClick}> Click here! </button> </div> ) }} export default App", "e": 28738, "s": 28118, "text": null }, { "code": null, "e": 28747, "s": 28738, "text": "Output: " }, { "code": null, "e": 28759, "s": 28747, "text": "Example 2: " }, { "code": null, "e": 28769, "s": 28759, "text": "index.js:" }, { "code": null, "e": 28780, "s": 28769, "text": "Javascript" }, { "code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))", "e": 28919, "s": 28780, "text": null }, { "code": null, "e": 28927, "s": 28919, "text": "App.js:" }, { "code": null, "e": 28938, "s": 28927, "text": "Javascript" }, { "code": "import React, { Component } from 'react' class App extends Component { static defaultProps = { courseContent : [ 'JSX', 'React Props', 'React State', 'React Lifecycle Methods', 'React Event Handlers', 'React Router', 'React Hooks', 'Readux', 'React Context' ] } constructor(props){ super(props) // Set initial state this.state = {msg : 'React Course', content:''} // Binding this keyword this.handleClick = this.handleClick.bind(this) } renderContent(){ return ( <ul> {this.props.courseContent.map(content => ( <li>{content}</li> ))} </ul> ) } handleClick(){ // Changing state this.setState({ msg : 'Course Content', content : this.renderContent() }) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> <p>{this.state.content}</p> {/* Set click handler */} <button onClick={this.handleClick}> Click here to know contents! </button> </div> ) }} export default App", "e": 30034, "s": 28938, "text": null }, { "code": null, "e": 30042, "s": 30034, "text": "Output:" }, { "code": null, "e": 30051, "s": 30042, "text": "rkbhola5" }, { "code": null, "e": 30060, "s": 30051, "text": "react-js" }, { "code": null, "e": 30071, "s": 30060, "text": "JavaScript" }, { "code": null, "e": 30088, "s": 30071, "text": "Web Technologies" }, { "code": null, "e": 30186, "s": 30088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30231, "s": 30186, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30292, "s": 30231, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30361, "s": 30292, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 30413, "s": 30361, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30440, "s": 30413, "text": "File uploading in React.js" }, { "code": null, "e": 30482, "s": 30440, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30515, "s": 30482, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30558, "s": 30515, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30620, "s": 30558, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Setting up PostgreSQL in Debian-based Linux | by Colton Magnant | Towards Data Science
In trying to set up a PostgreSQL server in my Linux boxes to practice SQL commands on my own, I ran into a few snags along the way, so I decided to put together this tutorial for my future self in case I ever needed to install again. After installing the base system, I was also able to obtain a dump from a small test database for practice purposes... so I’ve also included the commands I used to load this database file. Note: This process was tested on Linux Mint 19 Tara and Ubuntu 18.04 around November of 2019. Many of the steps below were obtained from this nice Wixel post: https://wixelhq.com/blog/how-to-install-postgresql-on-ubuntu-remote-access Preparation and Installation The default repositories for Ubuntu and Mint (and others) have the Postgres packages so we can use apt to install. $ sudo apt update$ sudo apt install postgresql postgresql-contrib Setup of Roles The installation of Postgres creates a user postgres with access to a default postgres database. Access this by first switching to the postgres user and running psql. $ sudo -i -u postgrespostgres@server:~$ psql You now have direct access to the default postgres database. Note that “\q” allows you to exit the Postgres prompt. postgres=# \q Now that you have confirmed the functionality of Postgres, it’s time to set up roles. Still within the postgres account, execute the following. postgres@server:~$ createuser --interactive This will guide you through the process of setting up a new user. More details on other flags can be found in the createuser man pages. Note: it may be useful to first create a role with the same name as your user account as the superuser. Running psql now (as the username with the same name as the role you just created) will result in an error. Although you have created a role, the default database for each role is the database with the same name as the role. It is therefore necessary to either supply the name of the database you wish to connect to or create a corresponding database, addressed in the following sections. Access a Particular Database Assuming that your role (your username) has been granted access to a database {dbname}, you can simply run the following from your command prompt. $ psql {dbname} You may also specify a role {role} other than your username as follows. $ psql -U {role} {dbname} Creating a New Database As the postgres user, execute the following command. Note: replace {dbname} with the name of your desired database, often the name of the role created above. postgres@server:~$ createdb {dbname} Loading of Database If you have been given a dump of a database, here denoted by {filename}.sql, the following will create the database in your PostgreSQL server and load the file data into the database. Note: replace {username} with an existing role in your PostgreSQL server, replace {dbname} with the name of an existing database in your PostgreSQL server, and replace {filename} with the name of your .sql file. $ createdb -U {username} {dbname}$ psql {dbname} < {filename}.sql Now you’re all ready to SELECT something FROM your_tables.
[ { "code": null, "e": 595, "s": 172, "text": "In trying to set up a PostgreSQL server in my Linux boxes to practice SQL commands on my own, I ran into a few snags along the way, so I decided to put together this tutorial for my future self in case I ever needed to install again. After installing the base system, I was also able to obtain a dump from a small test database for practice purposes... so I’ve also included the commands I used to load this database file." }, { "code": null, "e": 689, "s": 595, "text": "Note: This process was tested on Linux Mint 19 Tara and Ubuntu 18.04 around November of 2019." }, { "code": null, "e": 829, "s": 689, "text": "Many of the steps below were obtained from this nice Wixel post: https://wixelhq.com/blog/how-to-install-postgresql-on-ubuntu-remote-access" }, { "code": null, "e": 858, "s": 829, "text": "Preparation and Installation" }, { "code": null, "e": 973, "s": 858, "text": "The default repositories for Ubuntu and Mint (and others) have the Postgres packages so we can use apt to install." }, { "code": null, "e": 1039, "s": 973, "text": "$ sudo apt update$ sudo apt install postgresql postgresql-contrib" }, { "code": null, "e": 1054, "s": 1039, "text": "Setup of Roles" }, { "code": null, "e": 1221, "s": 1054, "text": "The installation of Postgres creates a user postgres with access to a default postgres database. Access this by first switching to the postgres user and running psql." }, { "code": null, "e": 1266, "s": 1221, "text": "$ sudo -i -u postgrespostgres@server:~$ psql" }, { "code": null, "e": 1382, "s": 1266, "text": "You now have direct access to the default postgres database. Note that “\\q” allows you to exit the Postgres prompt." }, { "code": null, "e": 1396, "s": 1382, "text": "postgres=# \\q" }, { "code": null, "e": 1540, "s": 1396, "text": "Now that you have confirmed the functionality of Postgres, it’s time to set up roles. Still within the postgres account, execute the following." }, { "code": null, "e": 1584, "s": 1540, "text": "postgres@server:~$ createuser --interactive" }, { "code": null, "e": 1720, "s": 1584, "text": "This will guide you through the process of setting up a new user. More details on other flags can be found in the createuser man pages." }, { "code": null, "e": 1824, "s": 1720, "text": "Note: it may be useful to first create a role with the same name as your user account as the superuser." }, { "code": null, "e": 2213, "s": 1824, "text": "Running psql now (as the username with the same name as the role you just created) will result in an error. Although you have created a role, the default database for each role is the database with the same name as the role. It is therefore necessary to either supply the name of the database you wish to connect to or create a corresponding database, addressed in the following sections." }, { "code": null, "e": 2242, "s": 2213, "text": "Access a Particular Database" }, { "code": null, "e": 2389, "s": 2242, "text": "Assuming that your role (your username) has been granted access to a database {dbname}, you can simply run the following from your command prompt." }, { "code": null, "e": 2405, "s": 2389, "text": "$ psql {dbname}" }, { "code": null, "e": 2477, "s": 2405, "text": "You may also specify a role {role} other than your username as follows." }, { "code": null, "e": 2503, "s": 2477, "text": "$ psql -U {role} {dbname}" }, { "code": null, "e": 2527, "s": 2503, "text": "Creating a New Database" }, { "code": null, "e": 2685, "s": 2527, "text": "As the postgres user, execute the following command. Note: replace {dbname} with the name of your desired database, often the name of the role created above." }, { "code": null, "e": 2722, "s": 2685, "text": "postgres@server:~$ createdb {dbname}" }, { "code": null, "e": 2742, "s": 2722, "text": "Loading of Database" }, { "code": null, "e": 3138, "s": 2742, "text": "If you have been given a dump of a database, here denoted by {filename}.sql, the following will create the database in your PostgreSQL server and load the file data into the database. Note: replace {username} with an existing role in your PostgreSQL server, replace {dbname} with the name of an existing database in your PostgreSQL server, and replace {filename} with the name of your .sql file." }, { "code": null, "e": 3204, "s": 3138, "text": "$ createdb -U {username} {dbname}$ psql {dbname} < {filename}.sql" } ]
Flatten 2D Vector in C++
Suppose we have a 2D vector, we have to design and implement an iterator to flatten that 2d vector. There will be different methods as follows − next() − This will return the next element of the current element next() − This will return the next element of the current element hasNext() − This will check whether next element is present or not hasNext() − This will check whether next element is present or not So, if the input is like [[1,2],[3],[4]] then if we call the functions as follows − iterator.next(); iterator.next(); iterator.next(); iterator.next(); iterator.next(); iterator.next(); iterator.hasNext(); iterator.hasNext(); iterator.hasNext(); iterator.hasNext(); iterator.next(); iterator.next(); iterator.hasNext(); iterator.hasNext(); then the output will be [1,2,3,true, true,4,false] To solve this, we will follow these steps − Define one 2D array v Define one 2D array v Define initializer this will take one 2D array v, Define initializer this will take one 2D array v, rowPointer := 0 rowPointer := 0 colPointer := 0 colPointer := 0 n := size of v n := size of v while (rowPointer < n and colPointer >= size of v[rowPointer]), do −(increase rowPointer by 1) while (rowPointer < n and colPointer >= size of v[rowPointer]), do − (increase rowPointer by 1) (increase rowPointer by 1) Define a function next() Define a function next() x := v[rowPointer, colPointer] x := v[rowPointer, colPointer] (increase colPointer by 1) (increase colPointer by 1) if colPointer is same as size of v[rowPointer], then −colPointer := 0(increase rowPointer by 1)while (rowPointer < n and colPointer >= size of v[rowPointer]), do −(increase rowPointer by 1) if colPointer is same as size of v[rowPointer], then − colPointer := 0 colPointer := 0 (increase rowPointer by 1) (increase rowPointer by 1) while (rowPointer < n and colPointer >= size of v[rowPointer]), do −(increase rowPointer by 1) while (rowPointer < n and colPointer >= size of v[rowPointer]), do − (increase rowPointer by 1) (increase rowPointer by 1) return x return x Define a function hasNext() Define a function hasNext() return false when rowPointer is same as n return false when rowPointer is same as n Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Vector2D { public: int rowPointer, colPointer; int n; vector<vector<int< > v; Vector2D(vector<vector<int< >& v){ this->v = v; rowPointer = 0; colPointer = 0; n = v.size(); while (rowPointer < n && colPointer >= v[rowPointer].size()){ rowPointer++; } } int next(){ //cout << rowPointer << " " << colPointer << endl; int x = v[rowPointer][colPointer]; colPointer++; if (colPointer == v[rowPointer].size()) { colPointer = 0; rowPointer++; while (rowPointer < n && colPointer >= v[rowPointer].size()) { rowPointer++; } } return x; } bool hasNext(){ return !(rowPointer == n); } }; main(){ vector<vector<int<> v = {{1,2},{3},{4}}; Vector2D ob(v); cout << (ob.next()) << endl; cout << (ob.next()) << endl; cout << (ob.next()) << endl; cout << (ob.hasNext()) << endl; cout << (ob.next()) << endl; cout << (ob.hasNext()); } ob.next() ob.next() ob.next() ob.hasNext() ob.next() ob.hasNext() 1 2 3 1 4 0
[ { "code": null, "e": 1207, "s": 1062, "text": "Suppose we have a 2D vector, we have to design and implement an iterator to flatten that 2d vector. There will be different methods as follows −" }, { "code": null, "e": 1273, "s": 1207, "text": "next() − This will return the next element of the current element" }, { "code": null, "e": 1339, "s": 1273, "text": "next() − This will return the next element of the current element" }, { "code": null, "e": 1406, "s": 1339, "text": "hasNext() − This will check whether next element is present or not" }, { "code": null, "e": 1473, "s": 1406, "text": "hasNext() − This will check whether next element is present or not" }, { "code": null, "e": 1557, "s": 1473, "text": "So, if the input is like [[1,2],[3],[4]] then if we call the functions as follows −" }, { "code": null, "e": 1574, "s": 1557, "text": "iterator.next();" }, { "code": null, "e": 1591, "s": 1574, "text": "iterator.next();" }, { "code": null, "e": 1608, "s": 1591, "text": "iterator.next();" }, { "code": null, "e": 1625, "s": 1608, "text": "iterator.next();" }, { "code": null, "e": 1642, "s": 1625, "text": "iterator.next();" }, { "code": null, "e": 1659, "s": 1642, "text": "iterator.next();" }, { "code": null, "e": 1679, "s": 1659, "text": "iterator.hasNext();" }, { "code": null, "e": 1699, "s": 1679, "text": "iterator.hasNext();" }, { "code": null, "e": 1719, "s": 1699, "text": "iterator.hasNext();" }, { "code": null, "e": 1739, "s": 1719, "text": "iterator.hasNext();" }, { "code": null, "e": 1756, "s": 1739, "text": "iterator.next();" }, { "code": null, "e": 1773, "s": 1756, "text": "iterator.next();" }, { "code": null, "e": 1793, "s": 1773, "text": "iterator.hasNext();" }, { "code": null, "e": 1813, "s": 1793, "text": "iterator.hasNext();" }, { "code": null, "e": 1864, "s": 1813, "text": "then the output will be [1,2,3,true, true,4,false]" }, { "code": null, "e": 1908, "s": 1864, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1930, "s": 1908, "text": "Define one 2D array v" }, { "code": null, "e": 1952, "s": 1930, "text": "Define one 2D array v" }, { "code": null, "e": 2002, "s": 1952, "text": "Define initializer this will take one 2D array v," }, { "code": null, "e": 2052, "s": 2002, "text": "Define initializer this will take one 2D array v," }, { "code": null, "e": 2068, "s": 2052, "text": "rowPointer := 0" }, { "code": null, "e": 2084, "s": 2068, "text": "rowPointer := 0" }, { "code": null, "e": 2100, "s": 2084, "text": "colPointer := 0" }, { "code": null, "e": 2116, "s": 2100, "text": "colPointer := 0" }, { "code": null, "e": 2131, "s": 2116, "text": "n := size of v" }, { "code": null, "e": 2146, "s": 2131, "text": "n := size of v" }, { "code": null, "e": 2241, "s": 2146, "text": "while (rowPointer < n and colPointer >= size of v[rowPointer]), do −(increase rowPointer by 1)" }, { "code": null, "e": 2310, "s": 2241, "text": "while (rowPointer < n and colPointer >= size of v[rowPointer]), do −" }, { "code": null, "e": 2337, "s": 2310, "text": "(increase rowPointer by 1)" }, { "code": null, "e": 2364, "s": 2337, "text": "(increase rowPointer by 1)" }, { "code": null, "e": 2389, "s": 2364, "text": "Define a function next()" }, { "code": null, "e": 2414, "s": 2389, "text": "Define a function next()" }, { "code": null, "e": 2445, "s": 2414, "text": "x := v[rowPointer, colPointer]" }, { "code": null, "e": 2476, "s": 2445, "text": "x := v[rowPointer, colPointer]" }, { "code": null, "e": 2503, "s": 2476, "text": "(increase colPointer by 1)" }, { "code": null, "e": 2530, "s": 2503, "text": "(increase colPointer by 1)" }, { "code": null, "e": 2720, "s": 2530, "text": "if colPointer is same as size of v[rowPointer], then −colPointer := 0(increase rowPointer by 1)while (rowPointer < n and colPointer >= size of v[rowPointer]), do −(increase rowPointer by 1)" }, { "code": null, "e": 2775, "s": 2720, "text": "if colPointer is same as size of v[rowPointer], then −" }, { "code": null, "e": 2791, "s": 2775, "text": "colPointer := 0" }, { "code": null, "e": 2807, "s": 2791, "text": "colPointer := 0" }, { "code": null, "e": 2834, "s": 2807, "text": "(increase rowPointer by 1)" }, { "code": null, "e": 2861, "s": 2834, "text": "(increase rowPointer by 1)" }, { "code": null, "e": 2956, "s": 2861, "text": "while (rowPointer < n and colPointer >= size of v[rowPointer]), do −(increase rowPointer by 1)" }, { "code": null, "e": 3025, "s": 2956, "text": "while (rowPointer < n and colPointer >= size of v[rowPointer]), do −" }, { "code": null, "e": 3052, "s": 3025, "text": "(increase rowPointer by 1)" }, { "code": null, "e": 3079, "s": 3052, "text": "(increase rowPointer by 1)" }, { "code": null, "e": 3088, "s": 3079, "text": "return x" }, { "code": null, "e": 3097, "s": 3088, "text": "return x" }, { "code": null, "e": 3125, "s": 3097, "text": "Define a function hasNext()" }, { "code": null, "e": 3153, "s": 3125, "text": "Define a function hasNext()" }, { "code": null, "e": 3195, "s": 3153, "text": "return false when rowPointer is same as n" }, { "code": null, "e": 3237, "s": 3195, "text": "return false when rowPointer is same as n" }, { "code": null, "e": 3307, "s": 3237, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3318, "s": 3307, "text": " Live Demo" }, { "code": null, "e": 4372, "s": 3318, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Vector2D {\npublic:\n int rowPointer, colPointer;\n int n;\n vector<vector<int< > v;\n Vector2D(vector<vector<int< >& v){\n this->v = v;\n rowPointer = 0;\n colPointer = 0;\n n = v.size();\n while (rowPointer < n && colPointer >= v[rowPointer].size()){\n rowPointer++;\n }\n }\n int next(){\n //cout << rowPointer << \" \" << colPointer << endl;\n int x = v[rowPointer][colPointer];\n colPointer++;\n if (colPointer == v[rowPointer].size()) {\n colPointer = 0;\n rowPointer++;\n while (rowPointer < n && colPointer >= v[rowPointer].size()) {\n rowPointer++;\n }\n }\n return x;\n }\n bool hasNext(){\n return !(rowPointer == n);\n }\n};\nmain(){\n vector<vector<int<> v = {{1,2},{3},{4}};\n Vector2D ob(v);\n cout << (ob.next()) << endl;\n cout << (ob.next()) << endl;\n cout << (ob.next()) << endl;\n cout << (ob.hasNext()) << endl;\n cout << (ob.next()) << endl;\n cout << (ob.hasNext());\n}" }, { "code": null, "e": 4438, "s": 4372, "text": "ob.next()\nob.next()\nob.next()\nob.hasNext()\nob.next()\nob.hasNext()" }, { "code": null, "e": 4450, "s": 4438, "text": "1\n2\n3\n1\n4\n0" } ]
Python Dictionaries: Everything You Need to Know | by Dario Radečić | Towards Data Science
Dictionaries are awesome. They allow you to store and structure nested data in a clean and easy-to-access way. Today we’ll explore everything there is to Python dictionaries and see how you can use them to structure your applications. Don’t feel like reading? Check out my video on the topic: Dictionaries are somewhat similar to lists. Both are dynamic, meaning they can store any data types, and both are mutable, meaning you can change them throughout the application. What makes dictionaries different is the storage type. They store key-value pairs instead of a raw number or text. Further, you can access dictionary elements through a key instead of an index position, as is the case with lists. Accessing a key returns a value — that’s the general behavior you should remember. Here’s what you’ll learn today: Declaring a dictionary Basic dictionary operations Nested dictionaries Check if a key exists in a dictionary Dictionary methods Dictionary unpacking Dictionary comprehensions There are many topics to cover. Please follow them in specified order if this concept is new to you. If not, feel free to skip to any section. There are multiple ways to create a dictionary. None of them is better than the other, so feel free to pick one that best suits your coding style. The first way is the one you’ll find in most of the examples online, so we’ll stick to it throughout the article. In this style, you are putting keys and values separated by a colon inside curly brackets. Here’s an example: d = { 'Country': 'USA', 'Capital': 'Washington, D.C.' } The second style uses the dict keyword to declare a dictionary, and than places the elements as tuples (key, value) inside a list: d = dict([ ('Country', 'USA'), ('Capital', 'Washington, D.C.') ]) It’s not the most convenient method if you ask me. There are way too many parentheses, which ruin the code’s cleanness if the dictionary has nested elements. The third approach also uses the dict keyword, but the style looks more like assigning values to function parameters: d = dict( Country='USA', Capital='Washington, D.C.' ) Note how quotes aren’t placed around the keys with this approach. Once again — the style you choose is irrelevant. In this section, you’ll learn how to access dictionary values, change them, and delete them. To access dictionary values, you can use the dict[key] syntax. Let’s see how to print values of both Country and City from the dictionary d: print(d['Country'], d['Capital']) Executing this code prints “USA Washington, D.C.” to the console. Next, let’s see how to change the values. You can still use the dict[key] syntax, but you’ll have to assign a value this time. Here’s how: d['Country'] = 'France' d['Capital'] = 'Paris' If you were to reuse the first code snippet from this section, “France Paris” would be printed to the console. Finally, let’s see how to delete a key. Python has a del keyword that does the job. Here’s how to use it: del d['Capital'] If you were to print the entire dictionary, “{‘Country’: ‘France’}” would show. The Capital key was deleted successfully. Nested dictionaries have either dictionaries or lists as values for some keys. If you make a request to almost any REST API, chances are the JSON response will contain nested elements. To oversimply, consider JSON and nested dictionaries as synonyms. Therefore, it’s essential to know how to work with them. Let’s declare a nested dictionary: weather = { 'Country': 'USA', 'City': 'Washington, D.C.', 'Temperature': { 'Unit': 'F', 'Value': 54.3 }} The Temperature key has a dictionary for a value, which further has two key-value pairs inside. The nesting can get a lot more complicated, but the principles remain identical. Let’s now see how to access the City key. This should be a no-brainer, as the mentioned key isn’t nested: weather['City'] The value of “Washington, D.C.” is printed to the console. Let’s spice things up a bit. To practice accessing nested values, you’ll have to access the value located at Temperature > Value key. Here’s how: weather['Temperature']['Value'] The value of “54.3” is printed to the console. And that’s all you should know about nesting. Once again, nesting can get way more complicated, but the logic behind accessing elements always stays the same. Checking if a key exists is common when working on programming or data science tasks. In this section, you’ll learn how to check if a key exists, if a key doesn’t exist, and how to check if multiple keys exist. Let’s start with checking if a single key exists. You can use Python’s in keyword to perform the check: 'Country' in weather The code above outputs True to the console. Let’s perform the same check for a key that doesn’t exist: 'Humidity' in weather As you would expect, False is printed to the console. Let’s now see how to check if a key doesn’t exist in a dictionary. You can use Python’s not keyword combined with in. Here’s an example: 'Humidity' not in weather The above code prints False to the console. Finally, let’s see how to check for multiple keys. You can use Python’s and and or keywords, depending on if you need all keys to be present or only one: 'City' in weather and 'Humidity' in weather 'City' in weather or 'Humidity' in weather The first line outputs False, and the second one True. You can put as many conditions as you need; there’s no need to stop at two. This section is the most useful one for practical work. You’ll learn which methods you can call on dictionaries and how they behave. This method is used to grab a value for a particular key. Here’s how to grab the value for City of the weather dictionary: weather.get('City') As you would expect, “Washington, D.C.” is printed to the console. This method returns all of the keys present in a given dictionary: weather.keys() The output is: dict_keys(['Country', 'City', 'Temperature']). The values() method is very similar to the previous one, but returns dictionary values instead: weather.values() The output is: dict_values(['USA', 'Washington, D.C.', {'Unit': 'F', 'Value': 54.3}]) This method returns a list of key-value pairs found in a dictionary: weather.items() The output is: dict_items([('Country', 'USA'), ('City', 'Washington, D.C.'), ('Temperature', {'Unit': 'F', 'Value': 54.3})]) The pop() method removes a key-value pair from the dictionary and returns the value. The removed value can be stored in a variable: pop_item = weather.pop('City') weather After removing the City key, the dictionary looks like this: {'Country': 'USA', 'Temperature': {'Unit': 'F', 'Value': 54.3}}. This method is similar to the previous one, but it always removes the last key-value pair. The removed value can be stored in a variable: last_item = weather.popitem() weather The output is: {'Country': 'USA'}. As you can see, the Temperature key and its value were successfully removed. This method is used to delete everything from a dictionary. Here’s an example: weather.clear() weather The output is an empty dictionary — {}. This is the last method we’ll cover today. Put simply, it is used to merge two dictionaries. If the same keys appear in both dictionaries, the value of the latter is preserved: d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} d2 = {'d': 10, 'e': 11, 'f': 12} d1.update(d2) d1 Here’s the output: {'a': 1, 'b': 2, 'c': 3, 'd': 10, 'e': 11, 'f': 12}. The unpacking operator provides a more Pythonic way of performing dictionary updates. Unpacking is widely used in data science, for example to train a machine learning model with a set of hyperparameters stored as key-value pairs in a dictionary. To perform the unpacking, you can use the ** operator before a dictionary. Let’s cover unpacking with an example. Suppose you have the following two dictionaries: d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} d2 = {'e': 5, 'f': 6, 'g': 7} You want to store all key-value pairs in a single dictionary. Here’s how to do this with unpacking: unpacked = {**d1, **d2} Neat, right? The unpacked dictionary contains the following elements: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7} Don’t let the fancy naming fool you — this is a simple concept. You are probably already familiar with comprehensions, but with lists. As it turns out, you can do the same with dictionaries. If you aren’t familiar, don’t worry, there isn’t much to it. Dictionary comprehensions are methods for transforming one dictionary into another. Comprehensions are a neat way to avoid writing loops. Let’s get practical. Suppose you have the following dictionary of scores on a test: scores = { 'Bob': 56, 'Mark': 48, 'Sarah': 77, 'Joel': 49, 'Jane': 64 } For whatever reason, you’re feeling generous today and are giving ten extra points to every student. Instead of writing a loop and reassigning values in that way, you can use comprehensions: added_10 = {key: value + 10 for (key, value) in scores.items()} The added_10 dictionary contains the following: {'Bob': 66, 'Mark': 58, 'Sarah': 87, 'Joel': 59, 'Jane': 74}. Awesome! For the next example, you want to find out which students passed the test. 50 points is the pass threshold: has_passed = {key: True if value > 50 else False for (key, value) in scores.items()} The has_passeddictionary looks like this: {'Bob': True, 'Mark': False, 'Sarah': True, 'Joel': False, 'Jane': True}. And that’s just for today. Let’s wrap things up in the next section. Today you’ve learned pretty much everything there is about dictionaries. You can do other things, of course, but I didn’t find them useful in my daily job. This article alone should serve you well for any use case — from programming to data science and machine learning. What’s your most common operation performed with dictionaries? Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Originally published at https://betterdatascience.com on November 20, 2020.
[ { "code": null, "e": 407, "s": 172, "text": "Dictionaries are awesome. They allow you to store and structure nested data in a clean and easy-to-access way. Today we’ll explore everything there is to Python dictionaries and see how you can use them to structure your applications." }, { "code": null, "e": 465, "s": 407, "text": "Don’t feel like reading? Check out my video on the topic:" }, { "code": null, "e": 644, "s": 465, "text": "Dictionaries are somewhat similar to lists. Both are dynamic, meaning they can store any data types, and both are mutable, meaning you can change them throughout the application." }, { "code": null, "e": 874, "s": 644, "text": "What makes dictionaries different is the storage type. They store key-value pairs instead of a raw number or text. Further, you can access dictionary elements through a key instead of an index position, as is the case with lists." }, { "code": null, "e": 957, "s": 874, "text": "Accessing a key returns a value — that’s the general behavior you should remember." }, { "code": null, "e": 989, "s": 957, "text": "Here’s what you’ll learn today:" }, { "code": null, "e": 1012, "s": 989, "text": "Declaring a dictionary" }, { "code": null, "e": 1040, "s": 1012, "text": "Basic dictionary operations" }, { "code": null, "e": 1060, "s": 1040, "text": "Nested dictionaries" }, { "code": null, "e": 1098, "s": 1060, "text": "Check if a key exists in a dictionary" }, { "code": null, "e": 1117, "s": 1098, "text": "Dictionary methods" }, { "code": null, "e": 1138, "s": 1117, "text": "Dictionary unpacking" }, { "code": null, "e": 1164, "s": 1138, "text": "Dictionary comprehensions" }, { "code": null, "e": 1307, "s": 1164, "text": "There are many topics to cover. Please follow them in specified order if this concept is new to you. If not, feel free to skip to any section." }, { "code": null, "e": 1454, "s": 1307, "text": "There are multiple ways to create a dictionary. None of them is better than the other, so feel free to pick one that best suits your coding style." }, { "code": null, "e": 1678, "s": 1454, "text": "The first way is the one you’ll find in most of the examples online, so we’ll stick to it throughout the article. In this style, you are putting keys and values separated by a colon inside curly brackets. Here’s an example:" }, { "code": null, "e": 1742, "s": 1678, "text": "d = { 'Country': 'USA', 'Capital': 'Washington, D.C.' }" }, { "code": null, "e": 1873, "s": 1742, "text": "The second style uses the dict keyword to declare a dictionary, and than places the elements as tuples (key, value) inside a list:" }, { "code": null, "e": 1947, "s": 1873, "text": "d = dict([ ('Country', 'USA'), ('Capital', 'Washington, D.C.') ])" }, { "code": null, "e": 2105, "s": 1947, "text": "It’s not the most convenient method if you ask me. There are way too many parentheses, which ruin the code’s cleanness if the dictionary has nested elements." }, { "code": null, "e": 2223, "s": 2105, "text": "The third approach also uses the dict keyword, but the style looks more like assigning values to function parameters:" }, { "code": null, "e": 2285, "s": 2223, "text": "d = dict( Country='USA', Capital='Washington, D.C.' )" }, { "code": null, "e": 2351, "s": 2285, "text": "Note how quotes aren’t placed around the keys with this approach." }, { "code": null, "e": 2400, "s": 2351, "text": "Once again — the style you choose is irrelevant." }, { "code": null, "e": 2493, "s": 2400, "text": "In this section, you’ll learn how to access dictionary values, change them, and delete them." }, { "code": null, "e": 2634, "s": 2493, "text": "To access dictionary values, you can use the dict[key] syntax. Let’s see how to print values of both Country and City from the dictionary d:" }, { "code": null, "e": 2668, "s": 2634, "text": "print(d['Country'], d['Capital'])" }, { "code": null, "e": 2734, "s": 2668, "text": "Executing this code prints “USA Washington, D.C.” to the console." }, { "code": null, "e": 2873, "s": 2734, "text": "Next, let’s see how to change the values. You can still use the dict[key] syntax, but you’ll have to assign a value this time. Here’s how:" }, { "code": null, "e": 2920, "s": 2873, "text": "d['Country'] = 'France' d['Capital'] = 'Paris'" }, { "code": null, "e": 3031, "s": 2920, "text": "If you were to reuse the first code snippet from this section, “France Paris” would be printed to the console." }, { "code": null, "e": 3137, "s": 3031, "text": "Finally, let’s see how to delete a key. Python has a del keyword that does the job. Here’s how to use it:" }, { "code": null, "e": 3154, "s": 3137, "text": "del d['Capital']" }, { "code": null, "e": 3276, "s": 3154, "text": "If you were to print the entire dictionary, “{‘Country’: ‘France’}” would show. The Capital key was deleted successfully." }, { "code": null, "e": 3584, "s": 3276, "text": "Nested dictionaries have either dictionaries or lists as values for some keys. If you make a request to almost any REST API, chances are the JSON response will contain nested elements. To oversimply, consider JSON and nested dictionaries as synonyms. Therefore, it’s essential to know how to work with them." }, { "code": null, "e": 3619, "s": 3584, "text": "Let’s declare a nested dictionary:" }, { "code": null, "e": 3750, "s": 3619, "text": "weather = { 'Country': 'USA', 'City': 'Washington, D.C.', 'Temperature': { 'Unit': 'F', 'Value': 54.3 }}" }, { "code": null, "e": 3927, "s": 3750, "text": "The Temperature key has a dictionary for a value, which further has two key-value pairs inside. The nesting can get a lot more complicated, but the principles remain identical." }, { "code": null, "e": 4033, "s": 3927, "text": "Let’s now see how to access the City key. This should be a no-brainer, as the mentioned key isn’t nested:" }, { "code": null, "e": 4049, "s": 4033, "text": "weather['City']" }, { "code": null, "e": 4108, "s": 4049, "text": "The value of “Washington, D.C.” is printed to the console." }, { "code": null, "e": 4254, "s": 4108, "text": "Let’s spice things up a bit. To practice accessing nested values, you’ll have to access the value located at Temperature > Value key. Here’s how:" }, { "code": null, "e": 4286, "s": 4254, "text": "weather['Temperature']['Value']" }, { "code": null, "e": 4333, "s": 4286, "text": "The value of “54.3” is printed to the console." }, { "code": null, "e": 4492, "s": 4333, "text": "And that’s all you should know about nesting. Once again, nesting can get way more complicated, but the logic behind accessing elements always stays the same." }, { "code": null, "e": 4703, "s": 4492, "text": "Checking if a key exists is common when working on programming or data science tasks. In this section, you’ll learn how to check if a key exists, if a key doesn’t exist, and how to check if multiple keys exist." }, { "code": null, "e": 4807, "s": 4703, "text": "Let’s start with checking if a single key exists. You can use Python’s in keyword to perform the check:" }, { "code": null, "e": 4828, "s": 4807, "text": "'Country' in weather" }, { "code": null, "e": 4931, "s": 4828, "text": "The code above outputs True to the console. Let’s perform the same check for a key that doesn’t exist:" }, { "code": null, "e": 4953, "s": 4931, "text": "'Humidity' in weather" }, { "code": null, "e": 5007, "s": 4953, "text": "As you would expect, False is printed to the console." }, { "code": null, "e": 5144, "s": 5007, "text": "Let’s now see how to check if a key doesn’t exist in a dictionary. You can use Python’s not keyword combined with in. Here’s an example:" }, { "code": null, "e": 5170, "s": 5144, "text": "'Humidity' not in weather" }, { "code": null, "e": 5214, "s": 5170, "text": "The above code prints False to the console." }, { "code": null, "e": 5368, "s": 5214, "text": "Finally, let’s see how to check for multiple keys. You can use Python’s and and or keywords, depending on if you need all keys to be present or only one:" }, { "code": null, "e": 5455, "s": 5368, "text": "'City' in weather and 'Humidity' in weather 'City' in weather or 'Humidity' in weather" }, { "code": null, "e": 5586, "s": 5455, "text": "The first line outputs False, and the second one True. You can put as many conditions as you need; there’s no need to stop at two." }, { "code": null, "e": 5719, "s": 5586, "text": "This section is the most useful one for practical work. You’ll learn which methods you can call on dictionaries and how they behave." }, { "code": null, "e": 5842, "s": 5719, "text": "This method is used to grab a value for a particular key. Here’s how to grab the value for City of the weather dictionary:" }, { "code": null, "e": 5862, "s": 5842, "text": "weather.get('City')" }, { "code": null, "e": 5929, "s": 5862, "text": "As you would expect, “Washington, D.C.” is printed to the console." }, { "code": null, "e": 5996, "s": 5929, "text": "This method returns all of the keys present in a given dictionary:" }, { "code": null, "e": 6011, "s": 5996, "text": "weather.keys()" }, { "code": null, "e": 6073, "s": 6011, "text": "The output is: dict_keys(['Country', 'City', 'Temperature'])." }, { "code": null, "e": 6169, "s": 6073, "text": "The values() method is very similar to the previous one, but returns dictionary values instead:" }, { "code": null, "e": 6186, "s": 6169, "text": "weather.values()" }, { "code": null, "e": 6272, "s": 6186, "text": "The output is: dict_values(['USA', 'Washington, D.C.', {'Unit': 'F', 'Value': 54.3}])" }, { "code": null, "e": 6341, "s": 6272, "text": "This method returns a list of key-value pairs found in a dictionary:" }, { "code": null, "e": 6357, "s": 6341, "text": "weather.items()" }, { "code": null, "e": 6482, "s": 6357, "text": "The output is: dict_items([('Country', 'USA'), ('City', 'Washington, D.C.'), ('Temperature', {'Unit': 'F', 'Value': 54.3})])" }, { "code": null, "e": 6614, "s": 6482, "text": "The pop() method removes a key-value pair from the dictionary and returns the value. The removed value can be stored in a variable:" }, { "code": null, "e": 6653, "s": 6614, "text": "pop_item = weather.pop('City') weather" }, { "code": null, "e": 6779, "s": 6653, "text": "After removing the City key, the dictionary looks like this: {'Country': 'USA', 'Temperature': {'Unit': 'F', 'Value': 54.3}}." }, { "code": null, "e": 6917, "s": 6779, "text": "This method is similar to the previous one, but it always removes the last key-value pair. The removed value can be stored in a variable:" }, { "code": null, "e": 6955, "s": 6917, "text": "last_item = weather.popitem() weather" }, { "code": null, "e": 7067, "s": 6955, "text": "The output is: {'Country': 'USA'}. As you can see, the Temperature key and its value were successfully removed." }, { "code": null, "e": 7146, "s": 7067, "text": "This method is used to delete everything from a dictionary. Here’s an example:" }, { "code": null, "e": 7170, "s": 7146, "text": "weather.clear() weather" }, { "code": null, "e": 7210, "s": 7170, "text": "The output is an empty dictionary — {}." }, { "code": null, "e": 7387, "s": 7210, "text": "This is the last method we’ll cover today. Put simply, it is used to merge two dictionaries. If the same keys appear in both dictionaries, the value of the latter is preserved:" }, { "code": null, "e": 7475, "s": 7387, "text": "d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} d2 = {'d': 10, 'e': 11, 'f': 12} d1.update(d2) d1" }, { "code": null, "e": 7547, "s": 7475, "text": "Here’s the output: {'a': 1, 'b': 2, 'c': 3, 'd': 10, 'e': 11, 'f': 12}." }, { "code": null, "e": 7794, "s": 7547, "text": "The unpacking operator provides a more Pythonic way of performing dictionary updates. Unpacking is widely used in data science, for example to train a machine learning model with a set of hyperparameters stored as key-value pairs in a dictionary." }, { "code": null, "e": 7869, "s": 7794, "text": "To perform the unpacking, you can use the ** operator before a dictionary." }, { "code": null, "e": 7957, "s": 7869, "text": "Let’s cover unpacking with an example. Suppose you have the following two dictionaries:" }, { "code": null, "e": 8025, "s": 7957, "text": "d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} d2 = {'e': 5, 'f': 6, 'g': 7}" }, { "code": null, "e": 8125, "s": 8025, "text": "You want to store all key-value pairs in a single dictionary. Here’s how to do this with unpacking:" }, { "code": null, "e": 8149, "s": 8125, "text": "unpacked = {**d1, **d2}" }, { "code": null, "e": 8276, "s": 8149, "text": "Neat, right? The unpacked dictionary contains the following elements: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7}" }, { "code": null, "e": 8467, "s": 8276, "text": "Don’t let the fancy naming fool you — this is a simple concept. You are probably already familiar with comprehensions, but with lists. As it turns out, you can do the same with dictionaries." }, { "code": null, "e": 8666, "s": 8467, "text": "If you aren’t familiar, don’t worry, there isn’t much to it. Dictionary comprehensions are methods for transforming one dictionary into another. Comprehensions are a neat way to avoid writing loops." }, { "code": null, "e": 8750, "s": 8666, "text": "Let’s get practical. Suppose you have the following dictionary of scores on a test:" }, { "code": null, "e": 8842, "s": 8750, "text": "scores = { 'Bob': 56, 'Mark': 48, 'Sarah': 77, 'Joel': 49, 'Jane': 64 }" }, { "code": null, "e": 9033, "s": 8842, "text": "For whatever reason, you’re feeling generous today and are giving ten extra points to every student. Instead of writing a loop and reassigning values in that way, you can use comprehensions:" }, { "code": null, "e": 9097, "s": 9033, "text": "added_10 = {key: value + 10 for (key, value) in scores.items()}" }, { "code": null, "e": 9207, "s": 9097, "text": "The added_10 dictionary contains the following: {'Bob': 66, 'Mark': 58, 'Sarah': 87, 'Joel': 59, 'Jane': 74}." }, { "code": null, "e": 9324, "s": 9207, "text": "Awesome! For the next example, you want to find out which students passed the test. 50 points is the pass threshold:" }, { "code": null, "e": 9409, "s": 9324, "text": "has_passed = {key: True if value > 50 else False for (key, value) in scores.items()}" }, { "code": null, "e": 9525, "s": 9409, "text": "The has_passeddictionary looks like this: {'Bob': True, 'Mark': False, 'Sarah': True, 'Joel': False, 'Jane': True}." }, { "code": null, "e": 9594, "s": 9525, "text": "And that’s just for today. Let’s wrap things up in the next section." }, { "code": null, "e": 9750, "s": 9594, "text": "Today you’ve learned pretty much everything there is about dictionaries. You can do other things, of course, but I didn’t find them useful in my daily job." }, { "code": null, "e": 9865, "s": 9750, "text": "This article alone should serve you well for any use case — from programming to data science and machine learning." }, { "code": null, "e": 9928, "s": 9865, "text": "What’s your most common operation performed with dictionaries?" }, { "code": null, "e": 10111, "s": 9928, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 10122, "s": 10111, "text": "medium.com" } ]
Change Image Dynamically when User Scrolls Down | Set 2 - GeeksforGeeks
05 Jun, 2020 Change Image Dynamically when User Scrolls using JavaScript | Set 1 There may be situations where the image would need to change dynamically based on the user’s input. In this case, when the user scrolls down. Approach: Setting up a scroll event listener to know the user has scrolled the page. Calculating the pixels that have been scrolled up vertically by the user. It is accessed by using the scrollTop element.document.documentElement.scrollTop document.documentElement.scrollTop Using that value to change the source of the image dynamically. Example 1: In this example, we will change the source of the image whenever the page is scrolled 150 pixels vertically. The page consists of an image and a section for the text. They are styled through internal CSS. The window.onscroll listener would call a function every timewhen the user scrolls. Then, the called function selects the image using document.getElementById("myImage") and changes the source path of the image whenever the scrolled pixels crosses 150px. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title> How to change image dynamically when user scrolls down? </title> <style media="screen"> img { position: fixed; width: 30%; } .main-content { padding-left: 35%; height: 1000px; } h1, h3 { color: green; } </style></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png" alt="GeeksforGeeks Logo" id="myImage"> <div class="main-content"> <h1>GeeksforGeeks</h1> <h3>First Image Section</h3> <p> Scroll past the below line to see the change </p> <hr> <h3>Second Image Section</h3> <p> Scroll back up to see the original image </p> </div> <script> window.onscroll = function () { scrollFunction(); }; function scrollFunction() { var image = document.getElementById("myImage"); if (document.documentElement.scrollTop > 150) image.src = "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png"; else image.src = "https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png"; } </script></body> </html> Output: Example 2: In this example, we will change the arrangement of the images dynamically depending on how much the user has scrolled down. The page consists of four images given a sticky position at the bottom of the page. The function called by the scroll listener shuffles the source of the image dynamically. This gives us a spinning look for the images. <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> How to Change Image Dynamically when User Scrolls using JavaScript ? </title> <style media="screen"> .main-content { height: 800px; } .footer { position: sticky; bottom: 0; background-color: white; } .footerRow::after { content: ""; clear: both; display: table; position: sticky; bottom: 0; width: 100%; } .footerColumn { float: left; width: 25%; display: table; position: relative; margin: auto; } img { width: 100%; } h1, h3 { color: green; } </style></head> <body> <div class="main-content"> <h1>GeeksforGeeks</h1> <h3>Section One</h3> <p>Scroll here to see the change</p> <hr> <h3>Section Two</h3> <p>Scroll here to see the change</p> <hr> <h3>Section Three</h3> <p>Scroll here to see the change</p> <hr> <h3>Section Four</h3> <p>Scroll here to see the change</p> <hr> </div> <div class="footer"> <div class="footerRow"> <div class="footerColumn"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png" id="image1"> </div> <div class="footerColumn"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png" id="image2"> </div> <div class="footerColumn"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200121120603/GeeksforGeeks30.png" id="image3"> </div> <div class="footerColumn"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20191026152101/geeks_for_geeks.jpg" id="image4"> </div> </div> </div> <script> window.onscroll = function () { scrollFunction(); }; function scrollFunction() { var imageSource1 = "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png"; var imageSource2 = "https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png"; var imageSource3 = "https://media.geeksforgeeks.org/wp-content/uploads/20200121120603/GeeksforGeeks30.png"; var imageSource4 = "https://media.geeksforgeeks.org/wp-content/uploads/20191026152101/geeks_for_geeks.jpg"; var image1 = document.getElementById("image1"); var image2 = document.getElementById("image2"); var image3 = document.getElementById("image3"); var image4 = document.getElementById("image4"); if (document.documentElement.scrollTop < 150) { image1.src = imageSource1; image2.src = imageSource2; image3.src = imageSource3; image4.src = imageSource4; } else if ( document.documentElement.scrollTop < 250) { image1.src = imageSource2; image2.src = imageSource3; image3.src = imageSource4; image4.src = imageSource1; } else if ( document.documentElement.scrollTop < 350) { image1.src = imageSource3; image2.src = imageSource4; image3.src = imageSource1; image4.src = imageSource2; } else { image1.src = imageSource4; image2.src = imageSource1; image3.src = imageSource2; image4.src = imageSource3; } } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? How to apply style to parent if it has child with CSS? How to auto-resize an image to fit a div container 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": 25068, "s": 25040, "text": "\n05 Jun, 2020" }, { "code": null, "e": 25136, "s": 25068, "text": "Change Image Dynamically when User Scrolls using JavaScript | Set 1" }, { "code": null, "e": 25278, "s": 25136, "text": "There may be situations where the image would need to change dynamically based on the user’s input. In this case, when the user scrolls down." }, { "code": null, "e": 25288, "s": 25278, "text": "Approach:" }, { "code": null, "e": 25363, "s": 25288, "text": "Setting up a scroll event listener to know the user has scrolled the page." }, { "code": null, "e": 25518, "s": 25363, "text": "Calculating the pixels that have been scrolled up vertically by the user. It is accessed by using the scrollTop element.document.documentElement.scrollTop" }, { "code": null, "e": 25553, "s": 25518, "text": "document.documentElement.scrollTop" }, { "code": null, "e": 25617, "s": 25553, "text": "Using that value to change the source of the image dynamically." }, { "code": null, "e": 25833, "s": 25617, "text": "Example 1: In this example, we will change the source of the image whenever the page is scrolled 150 pixels vertically. The page consists of an image and a section for the text. They are styled through internal CSS." }, { "code": null, "e": 26087, "s": 25833, "text": "The window.onscroll listener would call a function every timewhen the user scrolls. Then, the called function selects the image using document.getElementById(\"myImage\") and changes the source path of the image whenever the scrolled pixels crosses 150px." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title> How to change image dynamically when user scrolls down? </title> <style media=\"screen\"> img { position: fixed; width: 30%; } .main-content { padding-left: 35%; height: 1000px; } h1, h3 { color: green; } </style></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png\" alt=\"GeeksforGeeks Logo\" id=\"myImage\"> <div class=\"main-content\"> <h1>GeeksforGeeks</h1> <h3>First Image Section</h3> <p> Scroll past the below line to see the change </p> <hr> <h3>Second Image Section</h3> <p> Scroll back up to see the original image </p> </div> <script> window.onscroll = function () { scrollFunction(); }; function scrollFunction() { var image = document.getElementById(\"myImage\"); if (document.documentElement.scrollTop > 150) image.src = \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\"; else image.src = \"https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png\"; } </script></body> </html>", "e": 27527, "s": 26087, "text": null }, { "code": null, "e": 27535, "s": 27527, "text": "Output:" }, { "code": null, "e": 27754, "s": 27535, "text": "Example 2: In this example, we will change the arrangement of the images dynamically depending on how much the user has scrolled down. The page consists of four images given a sticky position at the bottom of the page." }, { "code": null, "e": 27889, "s": 27754, "text": "The function called by the scroll listener shuffles the source of the image dynamically. This gives us a spinning look for the images." }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> How to Change Image Dynamically when User Scrolls using JavaScript ? </title> <style media=\"screen\"> .main-content { height: 800px; } .footer { position: sticky; bottom: 0; background-color: white; } .footerRow::after { content: \"\"; clear: both; display: table; position: sticky; bottom: 0; width: 100%; } .footerColumn { float: left; width: 25%; display: table; position: relative; margin: auto; } img { width: 100%; } h1, h3 { color: green; } </style></head> <body> <div class=\"main-content\"> <h1>GeeksforGeeks</h1> <h3>Section One</h3> <p>Scroll here to see the change</p> <hr> <h3>Section Two</h3> <p>Scroll here to see the change</p> <hr> <h3>Section Three</h3> <p>Scroll here to see the change</p> <hr> <h3>Section Four</h3> <p>Scroll here to see the change</p> <hr> </div> <div class=\"footer\"> <div class=\"footerRow\"> <div class=\"footerColumn\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\" id=\"image1\"> </div> <div class=\"footerColumn\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png\" id=\"image2\"> </div> <div class=\"footerColumn\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200121120603/GeeksforGeeks30.png\" id=\"image3\"> </div> <div class=\"footerColumn\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191026152101/geeks_for_geeks.jpg\" id=\"image4\"> </div> </div> </div> <script> window.onscroll = function () { scrollFunction(); }; function scrollFunction() { var imageSource1 = \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\"; var imageSource2 = \"https://media.geeksforgeeks.org/wp-content/uploads/20200122115631/GeeksforGeeks210.png\"; var imageSource3 = \"https://media.geeksforgeeks.org/wp-content/uploads/20200121120603/GeeksforGeeks30.png\"; var imageSource4 = \"https://media.geeksforgeeks.org/wp-content/uploads/20191026152101/geeks_for_geeks.jpg\"; var image1 = document.getElementById(\"image1\"); var image2 = document.getElementById(\"image2\"); var image3 = document.getElementById(\"image3\"); var image4 = document.getElementById(\"image4\"); if (document.documentElement.scrollTop < 150) { image1.src = imageSource1; image2.src = imageSource2; image3.src = imageSource3; image4.src = imageSource4; } else if ( document.documentElement.scrollTop < 250) { image1.src = imageSource2; image2.src = imageSource3; image3.src = imageSource4; image4.src = imageSource1; } else if ( document.documentElement.scrollTop < 350) { image1.src = imageSource3; image2.src = imageSource4; image3.src = imageSource1; image4.src = imageSource2; } else { image1.src = imageSource4; image2.src = imageSource1; image3.src = imageSource2; image4.src = imageSource3; } } </script></body> </html>", "e": 31808, "s": 27889, "text": null }, { "code": null, "e": 31816, "s": 31808, "text": "Output:" }, { "code": null, "e": 31825, "s": 31816, "text": "CSS-Misc" }, { "code": null, "e": 31835, "s": 31825, "text": "HTML-Misc" }, { "code": null, "e": 31851, "s": 31835, "text": "JavaScript-Misc" }, { "code": null, "e": 31858, "s": 31851, "text": "Picked" }, { "code": null, "e": 31862, "s": 31858, "text": "CSS" }, { "code": null, "e": 31867, "s": 31862, "text": "HTML" }, { "code": null, "e": 31878, "s": 31867, "text": "JavaScript" }, { "code": null, "e": 31895, "s": 31878, "text": "Web Technologies" }, { "code": null, "e": 31922, "s": 31895, "text": "Web technologies Questions" }, { "code": null, "e": 31927, "s": 31922, "text": "HTML" }, { "code": null, "e": 32025, "s": 31927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32062, "s": 32025, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32091, "s": 32062, "text": "Form validation using jQuery" }, { "code": null, "e": 32130, "s": 32091, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32185, "s": 32130, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 32247, "s": 32185, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 32307, "s": 32247, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32368, "s": 32307, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32421, "s": 32368, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32471, "s": 32421, "text": "How to Insert Form Data into Database using PHP ?" } ]
Array of Doubled Pairs in C++
Suppose we have an array of integers A with even length, now we have to say true if and only if it is possible to reorder it in such a way that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2. So if the input is like [3,1,3,6] then the result will be false, where as [4,-2,2,-4], will return true. To solve this, we will follow these steps − Create a map m, n := size of A, store the frequency of each element in A into map m Create a map m, n := size of A, store the frequency of each element in A into map m cnt := size of A cnt := size of A for each key-value pair kv in mapif m[key of kv] > 0, thenif m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by xotherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0 for each key-value pair kv in map if m[key of kv] > 0, thenif m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by xotherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0 if m[key of kv] > 0, then if m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by x if m[key of kv] is not 0 and m[2* key of kv] > 0 x := min of m[key of kv] and m[2* key of kv] x := min of m[key of kv] and m[2* key of kv] cnt := cnt – (x * 2) cnt := cnt – (x * 2) decrease m[2 * key of kv] by x decrease m[2 * key of kv] by x decrease m[key of kv] by x decrease m[key of kv] by x otherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0 otherwise when key of kv = 0, then cnt := cnt – m[key of kv] cnt := cnt – m[key of kv] m[key of kv] := 0 m[key of kv] := 0 return false when cnt is non-zero, otherwise true return false when cnt is non-zero, otherwise true Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: bool canReorderDoubled(vector<int>& A) { map <int, int> m; int n = A.size(); for(int i = 0; i < n; i++){ m[A[i]]++; } int cnt = A.size(); map <int, int> :: iterator it = m.begin(); while(it != m.end()){ if(m[it->first] > 0){ if(it->first != 0 && m[it->first * 2] > 0){ int x = min(m[it->first], m[it->first * 2]); cnt -= (x * 2); m[it->first * 2] -= x; m[it->first] -= x; }else if(it->first == 0){ cnt -= m[it->first]; m[it->first] = 0; } } it++; } return !cnt; } }; main(){ vector<int> v1 = {3,1,3,6}; Solution ob; cout << (ob.canReorderDoubled(v1)) << endl; v1 = {4,-2,2,-4}; cout << (ob.canReorderDoubled(v1)); } [3,1,3,6] [4,-2,2,-4] 0 1
[ { "code": null, "e": 1370, "s": 1062, "text": "Suppose we have an array of integers A with even length, now we have to say true if and only if it is possible to reorder it in such a way that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2. So if the input is like [3,1,3,6] then the result will be false, where as [4,-2,2,-4], will return true." }, { "code": null, "e": 1414, "s": 1370, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1498, "s": 1414, "text": "Create a map m, n := size of A, store the frequency of each element in A into map m" }, { "code": null, "e": 1582, "s": 1498, "text": "Create a map m, n := size of A, store the frequency of each element in A into map m" }, { "code": null, "e": 1599, "s": 1582, "text": "cnt := size of A" }, { "code": null, "e": 1616, "s": 1599, "text": "cnt := size of A" }, { "code": null, "e": 1919, "s": 1616, "text": "for each key-value pair kv in mapif m[key of kv] > 0, thenif m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by xotherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0" }, { "code": null, "e": 1953, "s": 1919, "text": "for each key-value pair kv in map" }, { "code": null, "e": 2223, "s": 1953, "text": "if m[key of kv] > 0, thenif m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by xotherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0" }, { "code": null, "e": 2249, "s": 2223, "text": "if m[key of kv] > 0, then" }, { "code": null, "e": 2418, "s": 2249, "text": "if m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by x" }, { "code": null, "e": 2467, "s": 2418, "text": "if m[key of kv] is not 0 and m[2* key of kv] > 0" }, { "code": null, "e": 2512, "s": 2467, "text": "x := min of m[key of kv] and m[2* key of kv]" }, { "code": null, "e": 2557, "s": 2512, "text": "x := min of m[key of kv] and m[2* key of kv]" }, { "code": null, "e": 2578, "s": 2557, "text": "cnt := cnt – (x * 2)" }, { "code": null, "e": 2599, "s": 2578, "text": "cnt := cnt – (x * 2)" }, { "code": null, "e": 2630, "s": 2599, "text": "decrease m[2 * key of kv] by x" }, { "code": null, "e": 2661, "s": 2630, "text": "decrease m[2 * key of kv] by x" }, { "code": null, "e": 2688, "s": 2661, "text": "decrease m[key of kv] by x" }, { "code": null, "e": 2715, "s": 2688, "text": "decrease m[key of kv] by x" }, { "code": null, "e": 2792, "s": 2715, "text": "otherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0" }, { "code": null, "e": 2827, "s": 2792, "text": "otherwise when key of kv = 0, then" }, { "code": null, "e": 2853, "s": 2827, "text": "cnt := cnt – m[key of kv]" }, { "code": null, "e": 2879, "s": 2853, "text": "cnt := cnt – m[key of kv]" }, { "code": null, "e": 2897, "s": 2879, "text": "m[key of kv] := 0" }, { "code": null, "e": 2915, "s": 2897, "text": "m[key of kv] := 0" }, { "code": null, "e": 2965, "s": 2915, "text": "return false when cnt is non-zero, otherwise true" }, { "code": null, "e": 3015, "s": 2965, "text": "return false when cnt is non-zero, otherwise true" }, { "code": null, "e": 3085, "s": 3015, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3096, "s": 3085, "text": " Live Demo" }, { "code": null, "e": 4023, "s": 3096, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n bool canReorderDoubled(vector<int>& A) {\n map <int, int> m;\n int n = A.size();\n for(int i = 0; i < n; i++){\n m[A[i]]++;\n }\n int cnt = A.size();\n map <int, int> :: iterator it = m.begin();\n while(it != m.end()){\n if(m[it->first] > 0){\n if(it->first != 0 && m[it->first * 2] > 0){\n int x = min(m[it->first], m[it->first * 2]);\n cnt -= (x * 2);\n m[it->first * 2] -= x;\n m[it->first] -= x;\n }else if(it->first == 0){\n cnt -= m[it->first];\n m[it->first] = 0;\n }\n }\n it++;\n }\n return !cnt;\n }\n};\nmain(){\n vector<int> v1 = {3,1,3,6};\n Solution ob;\n cout << (ob.canReorderDoubled(v1)) << endl;\n v1 = {4,-2,2,-4};\n cout << (ob.canReorderDoubled(v1));\n}" }, { "code": null, "e": 4045, "s": 4023, "text": "[3,1,3,6]\n[4,-2,2,-4]" }, { "code": null, "e": 4049, "s": 4045, "text": "0\n1" } ]
How To Change The Size Of Figures In Matplotlib | Towards Data Science
Resizing figures generated through matplotlib in Python is a common task when it comes to visualizing data. In today’s short guide we will discuss a few possible ways for adjusting the size of the generated plots. Specifically, we will discuss how to do so: Using matplotlib.pyplot.figure() Using set_size_inches() by modifying rcParams['figure.figsize'] Additionally, we will discuss how to resize a figure using a factor/ratio of the existing (default) size. First, let’s create a figure using some dummy data that we’ll use throughout this article in order to demonstrate a couple of concepts. import matplotlib.pyplot as pltx = y = range(1, 10)plt.plot(x, y)plt.show() The figure shown below is generated using the default size, as defined in rcParams['figure.figsize'] . The first option you have is to call matplotlib.pyplot.figure that is used to create a new figure or activate an existing one. The method accepts an argument called figsize that is used to specify the width and height of the figure (in inches). Additionally, you can even specify dpi that corresponds to the resolution of the figure in dots-per-inch. import matplotlib.pyplot as pltfrom matplotlib.pyplot import figurefigure(figsize=(3, 2), dpi=80)x = y = range(1, 10)plt.plot(x, y)plt.show() The second option you have is matplotlib.figure.set_size_inches() that is used to set the figure size in inches. import matplotlib.pyplot as pltx = y = range(1, 10)plt.plot(x, y)plt.gcf().set_size_inches(3, 2)plt.show() If you want to modify the size of a figure without using the figure environment, then you can also update matplotlib.rcParams which is an instance of RcParams for handling default Matplotlib values. import matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = (3, 2)x = y = range(1, 10)plt.plot(x, y)plt.show() Note that the above will have effect on every figure generated unless you specify different size for a specific figure. If for any reason you want to set back the default values of this parameter, you can simply use rcParamsDefault as shown below plt.rcParams['figure.figsize']=plt.rcParamsDefault['figure.figsize'] Now if you wish to resize a figure using a hardcoded factor or ratio in relation say to another figure, then you can do so using the commands below: figure_size = plt.gcf().get_size_inches()factor = 0.8plt.gcf().set_size_inches(factor * figure_size) In today’s short guide we discussed how to resize figures generated using matplotlib library. We explore a few possible options but you should make sure to use the one that suits your needs (e.g. depending on whether you want to specify the size for all the figures and plots, or just a specific on). Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You may also like
[ { "code": null, "e": 386, "s": 172, "text": "Resizing figures generated through matplotlib in Python is a common task when it comes to visualizing data. In today’s short guide we will discuss a few possible ways for adjusting the size of the generated plots." }, { "code": null, "e": 430, "s": 386, "text": "Specifically, we will discuss how to do so:" }, { "code": null, "e": 463, "s": 430, "text": "Using matplotlib.pyplot.figure()" }, { "code": null, "e": 487, "s": 463, "text": "Using set_size_inches()" }, { "code": null, "e": 527, "s": 487, "text": "by modifying rcParams['figure.figsize']" }, { "code": null, "e": 633, "s": 527, "text": "Additionally, we will discuss how to resize a figure using a factor/ratio of the existing (default) size." }, { "code": null, "e": 769, "s": 633, "text": "First, let’s create a figure using some dummy data that we’ll use throughout this article in order to demonstrate a couple of concepts." }, { "code": null, "e": 845, "s": 769, "text": "import matplotlib.pyplot as pltx = y = range(1, 10)plt.plot(x, y)plt.show()" }, { "code": null, "e": 948, "s": 845, "text": "The figure shown below is generated using the default size, as defined in rcParams['figure.figsize'] ." }, { "code": null, "e": 1299, "s": 948, "text": "The first option you have is to call matplotlib.pyplot.figure that is used to create a new figure or activate an existing one. The method accepts an argument called figsize that is used to specify the width and height of the figure (in inches). Additionally, you can even specify dpi that corresponds to the resolution of the figure in dots-per-inch." }, { "code": null, "e": 1441, "s": 1299, "text": "import matplotlib.pyplot as pltfrom matplotlib.pyplot import figurefigure(figsize=(3, 2), dpi=80)x = y = range(1, 10)plt.plot(x, y)plt.show()" }, { "code": null, "e": 1554, "s": 1441, "text": "The second option you have is matplotlib.figure.set_size_inches() that is used to set the figure size in inches." }, { "code": null, "e": 1661, "s": 1554, "text": "import matplotlib.pyplot as pltx = y = range(1, 10)plt.plot(x, y)plt.gcf().set_size_inches(3, 2)plt.show()" }, { "code": null, "e": 1860, "s": 1661, "text": "If you want to modify the size of a figure without using the figure environment, then you can also update matplotlib.rcParams which is an instance of RcParams for handling default Matplotlib values." }, { "code": null, "e": 1975, "s": 1860, "text": "import matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = (3, 2)x = y = range(1, 10)plt.plot(x, y)plt.show()" }, { "code": null, "e": 2222, "s": 1975, "text": "Note that the above will have effect on every figure generated unless you specify different size for a specific figure. If for any reason you want to set back the default values of this parameter, you can simply use rcParamsDefault as shown below" }, { "code": null, "e": 2291, "s": 2222, "text": "plt.rcParams['figure.figsize']=plt.rcParamsDefault['figure.figsize']" }, { "code": null, "e": 2440, "s": 2291, "text": "Now if you wish to resize a figure using a hardcoded factor or ratio in relation say to another figure, then you can do so using the commands below:" }, { "code": null, "e": 2541, "s": 2440, "text": "figure_size = plt.gcf().get_size_inches()factor = 0.8plt.gcf().set_size_inches(factor * figure_size)" }, { "code": null, "e": 2842, "s": 2541, "text": "In today’s short guide we discussed how to resize figures generated using matplotlib library. We explore a few possible options but you should make sure to use the one that suits your needs (e.g. depending on whether you want to specify the size for all the figures and plots, or just a specific on)." }, { "code": null, "e": 2959, "s": 2842, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read." } ]
Nth Fibonacci Number | Practice | GeeksforGeeks
Given a positive integer n, find the nth fibonacci number. Since the answer can be very large, return the answer modulo 1000000007. Example 1: Input: n = 2 Output: 1 Explanation: 1 is the 2nd number of fibonacci series. Example 2: Input: n = 5 Output: 5 Explanation: 5 is the 5th number of fibonacci series. Your Task: You dont need to read input or print anything. Complete the function nthFibonacci() which takes n as input parameter and returns nth fibonacci number. Expected Time Complexity: O(n) Expected Auxiliary Space: O(n) Constraints: 1<= n <=1000 0 hrithikjain98891 day ago Total Time Taken: 0.01/1.27 long long int nthFibonacci(long long int n){ // code here int first=0; int sec=1; long long int add=0; n--; while(n--) { add=(first+sec)%1000000007; first=sec; sec=add; } return add; } 0 devashishbakare2 weeks ago JAVA Using Tabulation(DP) static long nthFibonacci(long n){ long dp[] = new long[(int)n+1]; int pow = 1000000007; dp[0]=0; dp[1]=1; for(int i=2; i<=n ;i++) { dp[i]=((dp[i-1]%pow)+(dp[i-2]%pow))%pow; } return dp[(int)n]%pow; 0 moaslam8264 weeks ago SIMPLE C++ SOLN typedef long long int ll;const ll m=1e9+7;class Solution { public: long long int nthFibonacci(long long int n){ // code here vector<ll>v(n); v[0]=1; v[1]=1; for(int i=2;i<n;i++){ v[i]=v[i-1]%m+v[i-2]%m; v[i]%=m; } return v[n-1]; }}; 0 annanyamathur1 month ago ong long int nthFibonacci(long long int n){ long long int dp[n+1]; dp[0]=0; dp[1]=1; for(int i=2;i<=n;i++) { dp[i]=((dp[i-1]%1000000007)+(dp[i-2]%1000000007))%1000000007; } return dp[n]%1000000007; } +1 mashhadihossain1 month ago SIMPLE JAVA SOLUTION (0.1/1.1 SEC) class Solution { static long nthFibonacci(long n){ int N=(int)n; long dp[]=new long[N+1]; dp[0]=0; dp[1]=1; for(int i=2;i<=N;i++) { dp[i]=(dp[i-1]+dp[i-2])%1000000007; } return dp[N]; }} 0 madhukartemba1 month ago JAVA SOLUTION: class Solution { static long nthFibonacci(long n){ if(n<=2) return 1; long pp = 1, p = 1; long cur = 0; for(long i=3; i<=n; i++) { cur = pp + p; cur = (cur%1000000007); pp = p; p = cur; } return cur; } } 0 swastikp17111 month ago // 0 1 1 2 3 5 8 13 21 34 55 89 class Solution { static long nthFibonacci(long n){ int mod = 1000000007; long secondPrev = 0L; long firstPrev= 1L; long ans=0L; if(n<=firstPrev) return n; for(long i=2;i<=n;i++){ ans=(firstPrev+secondPrev)%mod; secondPrev=firstPrev; firstPrev=ans; } return ans; } } 0 programmerhere1 month ago why runtime error? class Solution { public: long long int nthFibonacci(long long int n){ long long int i=1; stack<int> temp; while(i<=n){ if(i==1) temp.push(1); if(i==2) temp.push(1); else{ long long int store=temp.top(); temp.pop(); long long int s=temp.top()+store; temp.push(store); temp.push(s); } i++; } return temp.top(); }}; 0 sahuop21211 month ago def nthFibonacci(self, n): # code here lst = [0,1] for i in range(n): lst.append(lst[i]+lst[i+1]) return lst[n]%1000000007 0 amiransarimy1 month ago Python Solutions without using Recursive def nthFibonacci(self, n): if n == 1 or n == 2: return 1 else: f1 = 1 f2 = 1 f3 = 0 for idx in range(n-2): f3 = f1 +f2 f1 = f2 f2 = f3 return f3%1000000007 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": 382, "s": 238, "text": "Given a positive integer n, find the nth fibonacci number. Since the answer can be very large, return the answer modulo 1000000007.\n\nExample 1:" }, { "code": null, "e": 461, "s": 382, "text": "Input: n = 2\nOutput: 1 \nExplanation: 1 is the 2nd number\nof fibonacci series.\n" }, { "code": null, "e": 472, "s": 461, "text": "Example 2:" }, { "code": null, "e": 550, "s": 472, "text": "Input: n = 5\nOutput: 5\nExplanation: 5 is the 5th number\nof fibonacci series.\n" }, { "code": null, "e": 805, "s": 550, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function nthFibonacci() which takes n as input parameter and returns nth fibonacci number.\n\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\n\nConstraints:\n1<= n <=1000" }, { "code": null, "e": 807, "s": 805, "text": "0" }, { "code": null, "e": 832, "s": 807, "text": "hrithikjain98891 day ago" }, { "code": null, "e": 850, "s": 832, "text": "Total Time Taken:" }, { "code": null, "e": 860, "s": 850, "text": "0.01/1.27" }, { "code": null, "e": 1132, "s": 860, "text": " long long int nthFibonacci(long long int n){ // code here int first=0; int sec=1; long long int add=0; n--; while(n--) { add=(first+sec)%1000000007; first=sec; sec=add; } return add; }" }, { "code": null, "e": 1134, "s": 1132, "text": "0" }, { "code": null, "e": 1161, "s": 1134, "text": "devashishbakare2 weeks ago" }, { "code": null, "e": 1187, "s": 1161, "text": "JAVA Using Tabulation(DP)" }, { "code": null, "e": 1474, "s": 1189, "text": " \n static long nthFibonacci(long n){\n \n long dp[] = new long[(int)n+1];\n int pow = 1000000007;\n \n dp[0]=0;\n dp[1]=1;\n \n for(int i=2; i<=n ;i++)\n {\n dp[i]=((dp[i-1]%pow)+(dp[i-2]%pow))%pow;\n }\n return dp[(int)n]%pow;" }, { "code": null, "e": 1476, "s": 1474, "text": "0" }, { "code": null, "e": 1498, "s": 1476, "text": "moaslam8264 weeks ago" }, { "code": null, "e": 1514, "s": 1498, "text": "SIMPLE C++ SOLN" }, { "code": null, "e": 1807, "s": 1514, "text": "typedef long long int ll;const ll m=1e9+7;class Solution { public: long long int nthFibonacci(long long int n){ // code here vector<ll>v(n); v[0]=1; v[1]=1; for(int i=2;i<n;i++){ v[i]=v[i-1]%m+v[i-2]%m; v[i]%=m; } return v[n-1]; }};" }, { "code": null, "e": 1809, "s": 1807, "text": "0" }, { "code": null, "e": 1834, "s": 1809, "text": "annanyamathur1 month ago" }, { "code": null, "e": 2079, "s": 1834, "text": "ong long int nthFibonacci(long long int n){ long long int dp[n+1]; dp[0]=0; dp[1]=1; for(int i=2;i<=n;i++) { dp[i]=((dp[i-1]%1000000007)+(dp[i-2]%1000000007))%1000000007; } return dp[n]%1000000007; }" }, { "code": null, "e": 2082, "s": 2079, "text": "+1" }, { "code": null, "e": 2109, "s": 2082, "text": "mashhadihossain1 month ago" }, { "code": null, "e": 2144, "s": 2109, "text": "SIMPLE JAVA SOLUTION (0.1/1.1 SEC)" }, { "code": null, "e": 2388, "s": 2144, "text": "class Solution { static long nthFibonacci(long n){ int N=(int)n; long dp[]=new long[N+1]; dp[0]=0; dp[1]=1; for(int i=2;i<=N;i++) { dp[i]=(dp[i-1]+dp[i-2])%1000000007; } return dp[N]; }}" }, { "code": null, "e": 2390, "s": 2388, "text": "0" }, { "code": null, "e": 2415, "s": 2390, "text": "madhukartemba1 month ago" }, { "code": null, "e": 2430, "s": 2415, "text": "JAVA SOLUTION:" }, { "code": null, "e": 2792, "s": 2430, "text": "class Solution {\n static long nthFibonacci(long n){\n \n if(n<=2) return 1;\n long pp = 1, p = 1;\n \n long cur = 0;\n \n for(long i=3; i<=n; i++)\n {\n cur = pp + p;\n cur = (cur%1000000007);\n pp = p;\n p = cur;\n }\n \n return cur;\n \n }\n}\n" }, { "code": null, "e": 2794, "s": 2792, "text": "0" }, { "code": null, "e": 2818, "s": 2794, "text": "swastikp17111 month ago" }, { "code": null, "e": 3258, "s": 2818, "text": "// 0 1 1 2 3 5 8 13 21 34 55 89\nclass Solution {\n static long nthFibonacci(long n){\n int mod = 1000000007;\n long secondPrev = 0L;\n long firstPrev= 1L;\n long ans=0L;\n \n if(n<=firstPrev)\n return n;\n for(long i=2;i<=n;i++){\n ans=(firstPrev+secondPrev)%mod;\n secondPrev=firstPrev;\n firstPrev=ans;\n }\n return ans;\n }\n}" }, { "code": null, "e": 3260, "s": 3258, "text": "0" }, { "code": null, "e": 3286, "s": 3260, "text": "programmerhere1 month ago" }, { "code": null, "e": 3305, "s": 3286, "text": "why runtime error?" }, { "code": null, "e": 3726, "s": 3309, "text": "class Solution { public: long long int nthFibonacci(long long int n){ long long int i=1; stack<int> temp; while(i<=n){ if(i==1) temp.push(1); if(i==2) temp.push(1); else{ long long int store=temp.top(); temp.pop(); long long int s=temp.top()+store; temp.push(store); temp.push(s); } i++; } return temp.top(); }};" }, { "code": null, "e": 3728, "s": 3726, "text": "0" }, { "code": null, "e": 3750, "s": 3728, "text": "sahuop21211 month ago" }, { "code": null, "e": 3926, "s": 3750, "text": "def nthFibonacci(self, n):\n # code here \n lst = [0,1]\n for i in range(n):\n lst.append(lst[i]+lst[i+1])\n \n return lst[n]%1000000007" }, { "code": null, "e": 3928, "s": 3926, "text": "0" }, { "code": null, "e": 3952, "s": 3928, "text": "amiransarimy1 month ago" }, { "code": null, "e": 3993, "s": 3952, "text": "Python Solutions without using Recursive" }, { "code": null, "e": 4308, "s": 3995, "text": "def nthFibonacci(self, n):\n \n if n == 1 or n == 2:\n return 1\n else:\n f1 = 1\n f2 = 1\n f3 = 0\n \n for idx in range(n-2):\n f3 = f1 +f2\n f1 = f2\n f2 = f3\n \n return f3%1000000007" }, { "code": null, "e": 4454, "s": 4308, "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": 4490, "s": 4454, "text": " Login to access your submissions. " }, { "code": null, "e": 4500, "s": 4490, "text": "\nProblem\n" }, { "code": null, "e": 4510, "s": 4500, "text": "\nContest\n" }, { "code": null, "e": 4573, "s": 4510, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4721, "s": 4573, "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": 4929, "s": 4721, "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": 5035, "s": 4929, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
spaCy - Train Command
As name implies, this command will train a model. The output will be in spaCy’s JSON format and on every epoch the model will be saved out to the directory. To package the model using spaCy package command, model details and accuracy scores will be added to meta.json file. The Train command is as follows: python -m spacy [lang] [output_path] [train_path] [dev_path] [--base-model] [--pipeline] [--vectors] [--n-iter] [--n-early-stopping][--n-examples] [--use-gpu] [--version] [--meta-path] [--init-tok2vec][--parser-multitasks] [--entity-multitasks] [--gold-preproc] [--noise-level][--orth-variant-level] [--learn-tokens] [--textcat-arch] [--textcat-multilabel][--textcat-positive-label] [--verbose] The table below explains its arguments − Print Add Notes Bookmark this page
[ { "code": null, "e": 2229, "s": 2072, "text": "As name implies, this command will train a model. The output will be in spaCy’s JSON format and on every epoch the model will be saved out to the directory." }, { "code": null, "e": 2346, "s": 2229, "text": "To package the model using spaCy package command, model details and accuracy scores will be added to meta.json file." }, { "code": null, "e": 2379, "s": 2346, "text": "The Train command is as follows:" }, { "code": null, "e": 2775, "s": 2379, "text": "python -m spacy [lang] [output_path] [train_path] [dev_path]\n[--base-model] [--pipeline] [--vectors] [--n-iter] [--n-early-stopping][--n-examples] [--use-gpu] [--version] [--meta-path] [--init-tok2vec][--parser-multitasks] [--entity-multitasks] [--gold-preproc] [--noise-level][--orth-variant-level] [--learn-tokens] [--textcat-arch] [--textcat-multilabel][--textcat-positive-label] [--verbose]\n" }, { "code": null, "e": 2816, "s": 2775, "text": "The table below explains its arguments −" }, { "code": null, "e": 2823, "s": 2816, "text": " Print" }, { "code": null, "e": 2834, "s": 2823, "text": " Add Notes" } ]
SortedSet Class in C#
The SortedSet class in C# represents a collection of objects that is maintained in sorted order. Following are the properties of the SortedSet class − Following are some of the methods of the SortedSet class − Let us now see some examples − To check if the SortedSet contains a specific element, the code is as follows − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main() { SortedSet<string> set1 = new SortedSet<string>(); set1.Add("CD"); set1.Add("CD"); set1.Add("CD"); set1.Add("CD"); Console.WriteLine("Elements in SortedSet1..."); foreach (string res in set1) { Console.WriteLine(res); } Console.WriteLine("Does the SortedSet1 contains the element DE? = "+set1.Contains("DE")); SortedSet<string> set2 = new SortedSet<string>(); set2.Add("BC"); set2.Add("CD"); set2.Add("DE"); set2.Add("EF"); set2.Add("AB"); set2.Add("HI"); set2.Add("JK"); Console.WriteLine("Elements in SortedSet2..."); foreach (string res in set2) { Console.WriteLine(res); } Console.WriteLine("SortedSet2 is a superset of SortedSet1? = "+set2.IsSupersetOf(set1)); } } This will produce the following output − Elements in SortedSet1... CD Does the SortedSet1 contains the element DE? = False Elements in SortedSet2... AB BC CD DE EF HI JK SortedSet2 is a superset of SortedSet1? = True To get an enumerator that iterates through the SortedSet, the code is as follows − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main(){ SortedSet<string> set1 = new SortedSet<string>(); set1.Add("AB"); set1.Add("BC"); set1.Add("CD"); set1.Add("EF"); Console.WriteLine("Elements in SortedSet1..."); foreach (string res in set1) { Console.WriteLine(res); } SortedSet<string> set2 = new SortedSet<string>(); set2.Add("BC"); set2.Add("CD"); set2.Add("DE"); set2.Add("EF"); set2.Add("AB"); set2.Add("HI"); set2.Add("JK"); Console.WriteLine("Elements in SortedSet2 (Enumerator for SortedSet)..."); SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator(); while (demoEnum.MoveNext()) { string res = demoEnum.Current; Console.WriteLine(res); } } } This will produce the following output − Elements in SortedSet1... AB BC CD EF Elements in SortedSet2 (Enumerator for SortedSet)... AB BC CD DE EF HI JK
[ { "code": null, "e": 1159, "s": 1062, "text": "The SortedSet class in C# represents a collection of objects that is maintained in sorted order." }, { "code": null, "e": 1213, "s": 1159, "text": "Following are the properties of the SortedSet class −" }, { "code": null, "e": 1272, "s": 1213, "text": "Following are some of the methods of the SortedSet class −" }, { "code": null, "e": 1303, "s": 1272, "text": "Let us now see some examples −" }, { "code": null, "e": 1383, "s": 1303, "text": "To check if the SortedSet contains a specific element, the code is as follows −" }, { "code": null, "e": 1394, "s": 1383, "text": " Live Demo" }, { "code": null, "e": 2309, "s": 1394, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n SortedSet<string> set1 = new SortedSet<string>();\n set1.Add(\"CD\");\n set1.Add(\"CD\");\n set1.Add(\"CD\");\n set1.Add(\"CD\");\n Console.WriteLine(\"Elements in SortedSet1...\");\n foreach (string res in set1) {\n Console.WriteLine(res);\n }\n Console.WriteLine(\"Does the SortedSet1 contains the element DE? = \"+set1.Contains(\"DE\"));\n SortedSet<string> set2 = new SortedSet<string>();\n set2.Add(\"BC\");\n set2.Add(\"CD\");\n set2.Add(\"DE\");\n set2.Add(\"EF\");\n set2.Add(\"AB\");\n set2.Add(\"HI\");\n set2.Add(\"JK\");\n Console.WriteLine(\"Elements in SortedSet2...\");\n foreach (string res in set2) {\n Console.WriteLine(res);\n }\n Console.WriteLine(\"SortedSet2 is a superset of SortedSet1? = \"+set2.IsSupersetOf(set1));\n }\n}" }, { "code": null, "e": 2350, "s": 2309, "text": "This will produce the following output −" }, { "code": null, "e": 2526, "s": 2350, "text": "Elements in SortedSet1...\nCD\nDoes the SortedSet1 contains the element DE? = False\nElements in SortedSet2...\nAB\nBC\nCD\nDE\nEF\nHI\nJK\nSortedSet2 is a superset of SortedSet1? = True" }, { "code": null, "e": 2609, "s": 2526, "text": "To get an enumerator that iterates through the SortedSet, the code is as follows −" }, { "code": null, "e": 2620, "s": 2609, "text": " Live Demo" }, { "code": null, "e": 3477, "s": 2620, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n SortedSet<string> set1 = new SortedSet<string>();\n set1.Add(\"AB\");\n set1.Add(\"BC\");\n set1.Add(\"CD\");\n set1.Add(\"EF\");\n Console.WriteLine(\"Elements in SortedSet1...\");\n foreach (string res in set1) {\n Console.WriteLine(res);\n }\n SortedSet<string> set2 = new SortedSet<string>();\n set2.Add(\"BC\");\n set2.Add(\"CD\");\n set2.Add(\"DE\");\n set2.Add(\"EF\");\n set2.Add(\"AB\");\n set2.Add(\"HI\");\n set2.Add(\"JK\");\n Console.WriteLine(\"Elements in SortedSet2 (Enumerator for SortedSet)...\");\n SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator();\n while (demoEnum.MoveNext()) {\n string res = demoEnum.Current;\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 3518, "s": 3477, "text": "This will produce the following output −" }, { "code": null, "e": 3630, "s": 3518, "text": "Elements in SortedSet1...\nAB\nBC\nCD\nEF\nElements in SortedSet2 (Enumerator for SortedSet)...\nAB\nBC\nCD\nDE\nEF\nHI\nJK" } ]
Tryit Editor v3.7
Tryit: HTML link to stylesheet
[]
WebGL - Geometry
After obtaining the WebGL context, you have to define the geometry for the primitive (object you want to draw) and store it. In WebGL, we define the details of a geometry – for example, vertices, indices, color of the primitive – using JavaScript arrays. To pass these details to the shader programs, we have to create the buffer objects and store (attach) the JavaScript arrays containing the data in the respective buffers. Note: Later, these buffer objects will be associated with the attributes of the shader program (vertex shader). A 2D or 3D model drawn using vertices is called a mesh. Each facet in a mesh is called a polygon and a polygon is made of 3 or more vertices. To draw models in the WebGL rendering context, you have to define the vertices and indices using JavaScript arrays. For example, if we want to create a triangle which lies on the coordinates {(5,5), (-5,5), (-5,-5)} as shown in the diagram, then you can create an array for the vertices as − var vertices = [ 0.5,0.5, //Vertex 1 0.5,-0.5, //Vertex 2 -0.5,-0.5, //Vertex 3 ]; Similarly, you can create an array for the indices. Indices for the above triangle indices will be [0, 1, 2] and can be defined as − var indices = [ 0,1,2 ] For a better understanding of indices, consider more complex models like square. We can represent a square as a set of two triangles. If (0,3,1) and (3,1,2) are the two triangles using which we intend to draw a square, then the indices will be defined as − var indices = [0,3,1,3,1,2]; Note − For drawing primitives, WebGL provides the following two methods − drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays. drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays. drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array. drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array. A buffer object is a mechanism provided by WebGL that indicates a memory area allocated in the system. In these buffer objects, you can store data of the model you want to draw, corresponding to vertices, indices, color, etc. Using these buffer objects, you can pass multiple data to the shader program (vertex shader) through one of its attribute variables. Since these buffer objects reside in the GPU memory, they can be rendered directly, which in turn improves the performance. To process geometry, there are two types of buffer objects. They are − Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates. Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates. Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered. Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered. After defining the required geometry and storing them in JavaScript arrays, you need to pass these arrays to the buffer objects, from where the data will be passed to the shader programs. The following steps are to be followed to store data in the buffers. Create an empty buffer. Create an empty buffer. Bind an appropriate array object to the empty buffer. Bind an appropriate array object to the empty buffer. Pass the data (vertices/indices) to the buffer using one of the typed arrays. Pass the data (vertices/indices) to the buffer using one of the typed arrays. Unbind the buffer (Optional). Unbind the buffer (Optional). To create an empty buffer object, WebGL provides a method called createBuffer(). This method returns a newly created buffer object, if the creation was successful; else it returns a null value in case of failure. WebGL operates as a state machine. Once a buffer is created, any subsequent buffer operation will be executed on the current buffer until we unbound it. Use the following code to create a buffer − var vertex_buffer = gl.createBuffer(); Note − gl is the reference variable to the current WebGL context. After creating an empty buffer object, you need to bind an appropriate array buffer (target) to it. WebGL provides a method called bindBuffer() for this purpose. The syntax of bindBuffer() method is as follows − void bindBuffer (enum target, Object buffer) This method accepts two parameters and they are discussed below. target − The first variable is an enum value representing the type of the buffer we want to bind to the empty buffer. You have two predefined enum values as options for this parameter. They are − ARRAY_BUFFER which represents vertex data. ARRAY_BUFFER which represents vertex data. ELEMENT_ARRAY_BUFFER which represents index data. ELEMENT_ARRAY_BUFFER which represents index data. Object buffer − The second one is the reference variable to the buffer object created in the previous step. The reference variable can be of a vertex buffer object or of an index buffer object. The following code snippet shows how to use the bindBuffer() method. //vertex buffer var vertex_buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); //Index buffer var Index_Buffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer); The next step is to pass the data (vertices/indices) to the buffer. Till now data is in the form of an array and before passing it to the buffer, we need to wrap it in one of the WebGL typed arrays. WebGL provides a method named bufferData() for this purpose. The syntax of bufferData() method is as follows − void bufferData (enum target, Object data, enum usage) This method accepts three parameters and they are discussed below − target − The first parameter is an enum value representing the type of the array buffer we used.The options for this parameter are − ARRAY_BUFFER which represents vertex data. ARRAY_BUFFER which represents vertex data. ELEMENT_ARRAY_BUFFER which represents index data. ELEMENT_ARRAY_BUFFER which represents index data. Object data − The second parameter is the object value that contains the data to be written to the buffer object. Here we have to pass the data using typed arrays. Usage − The third parameter of this method is an enum variable that specifies how to use the buffer object data (stored data) to draw shapes. There are three options for this parameter as listed below. gl.STATIC_DRAW − Data will be specified once and used many times. gl.STATIC_DRAW − Data will be specified once and used many times. gl.STREAM_DRAW − Data will be specified once and used a few times. gl.STREAM_DRAW − Data will be specified once and used a few times. gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times. gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times. The following code snippet shows how to use the bufferData() method. Assume vertices and indices are the arrays holding the vertex and index data respectively. //vertex buffer gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); //Index buffer gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); WebGL provides a special type of array called typed arrays to transfer the data elements such as index vertex and texture. These typed arrays store large quantities of data and process them in native binary format which results in better performance. The typed arrays used by WebGL are Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, UInt32Array, Float32Array, and Float64Array. Note Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array. Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array. You can create typed arrays just like JavaScript arrays using new keyword. You can create typed arrays just like JavaScript arrays using new keyword. It is recommended that you unbind the buffers after using them. It can be done by passing a null value in place of the buffer object, as shown below. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); WebGL provides the following methods to perform buffer operations − void bindBuffer (enum target, Object buffer) target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER void bufferData(enum target, long size, enum usage) target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER usage − STATIC_DRAW, STREAM_DRAW, DYNAMIC_DRAW void bufferData (enum target, Object data, enum usage) target and usage − Same as for bufferData above void bufferSubData(enum target, long offset, Object data) target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER any getBufferParameter(enum target, enum pname) target − ARRAY_BUFFER, ELEMENT_ ARRAY_BUFFER pname − BUFFER_SIZE, BUFFER_USAGE 10 Lectures 1 hours Frahaan Hussain 28 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2473, "s": 2047, "text": "After obtaining the WebGL context, you have to define the geometry for the primitive (object you want to draw) and store it. In WebGL, we define the details of a geometry – for example, vertices, indices, color of the primitive – using JavaScript arrays. To pass these details to the shader programs, we have to create the buffer objects and store (attach) the JavaScript arrays containing the data in the respective buffers." }, { "code": null, "e": 2585, "s": 2473, "text": "Note: Later, these buffer objects will be associated with the attributes of the shader program (vertex shader)." }, { "code": null, "e": 2727, "s": 2585, "text": "A 2D or 3D model drawn using vertices is called a mesh. Each facet in a mesh is called a polygon and a polygon is made of 3 or more vertices." }, { "code": null, "e": 3019, "s": 2727, "text": "To draw models in the WebGL rendering context, you have to define the vertices and indices using JavaScript arrays. For example, if we want to create a triangle which lies on the coordinates {(5,5), (-5,5), (-5,-5)} as shown in the diagram, then you can create an array for the vertices as −" }, { "code": null, "e": 3119, "s": 3019, "text": "var vertices = [\n 0.5,0.5, //Vertex 1\n 0.5,-0.5, //Vertex 2\n -0.5,-0.5, //Vertex 3\n]; \n" }, { "code": null, "e": 3252, "s": 3119, "text": "Similarly, you can create an array for the indices. Indices for the above triangle indices will be [0, 1, 2] and can be defined as −" }, { "code": null, "e": 3277, "s": 3252, "text": "var indices = [ 0,1,2 ]\n" }, { "code": null, "e": 3534, "s": 3277, "text": "For a better understanding of indices, consider more complex models like square. We can represent a square as a set of two triangles. If (0,3,1) and (3,1,2) are the two triangles using which we intend to draw a square, then the indices will be defined as −" }, { "code": null, "e": 3564, "s": 3534, "text": "var indices = [0,3,1,3,1,2];\n" }, { "code": null, "e": 3571, "s": 3564, "text": "Note −" }, { "code": null, "e": 3638, "s": 3571, "text": "For drawing primitives, WebGL provides the following two methods −" }, { "code": null, "e": 3741, "s": 3638, "text": "drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays." }, { "code": null, "e": 3844, "s": 3741, "text": "drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays." }, { "code": null, "e": 3961, "s": 3844, "text": "drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array." }, { "code": null, "e": 4078, "s": 3961, "text": "drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array." }, { "code": null, "e": 4304, "s": 4078, "text": "A buffer object is a mechanism provided by WebGL that indicates a memory area allocated in the system. In these buffer objects, you can store data of the model you want to draw, corresponding to vertices, indices, color, etc." }, { "code": null, "e": 4561, "s": 4304, "text": "Using these buffer objects, you can pass multiple data to the shader program (vertex shader) through one of its attribute variables. Since these buffer objects reside in the GPU memory, they can be rendered directly, which in turn improves the performance." }, { "code": null, "e": 4632, "s": 4561, "text": "To process geometry, there are two types of buffer objects. They are −" }, { "code": null, "e": 4900, "s": 4632, "text": "Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates." }, { "code": null, "e": 5168, "s": 4900, "text": "Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates." }, { "code": null, "e": 5284, "s": 5168, "text": "Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered." }, { "code": null, "e": 5400, "s": 5284, "text": "Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered." }, { "code": null, "e": 5657, "s": 5400, "text": "After defining the required geometry and storing them in JavaScript arrays, you need to pass these arrays to the buffer objects, from where the data will be passed to the shader programs. The following steps are to be followed to store data in the buffers." }, { "code": null, "e": 5681, "s": 5657, "text": "Create an empty buffer." }, { "code": null, "e": 5705, "s": 5681, "text": "Create an empty buffer." }, { "code": null, "e": 5759, "s": 5705, "text": "Bind an appropriate array object to the empty buffer." }, { "code": null, "e": 5813, "s": 5759, "text": "Bind an appropriate array object to the empty buffer." }, { "code": null, "e": 5891, "s": 5813, "text": "Pass the data (vertices/indices) to the buffer using one of the typed arrays." }, { "code": null, "e": 5969, "s": 5891, "text": "Pass the data (vertices/indices) to the buffer using one of the typed arrays." }, { "code": null, "e": 5999, "s": 5969, "text": "Unbind the buffer (Optional)." }, { "code": null, "e": 6029, "s": 5999, "text": "Unbind the buffer (Optional)." }, { "code": null, "e": 6242, "s": 6029, "text": "To create an empty buffer object, WebGL provides a method called createBuffer(). This method returns a newly created buffer object, if the creation was successful; else it returns a null value in case of failure." }, { "code": null, "e": 6439, "s": 6242, "text": "WebGL operates as a state machine. Once a buffer is created, any subsequent buffer operation will be executed on the current buffer until we unbound it. Use the following code to create a buffer −" }, { "code": null, "e": 6479, "s": 6439, "text": "var vertex_buffer = gl.createBuffer();\n" }, { "code": null, "e": 6545, "s": 6479, "text": "Note − gl is the reference variable to the current WebGL context." }, { "code": null, "e": 6707, "s": 6545, "text": "After creating an empty buffer object, you need to bind an appropriate array buffer (target) to it. WebGL provides a method called bindBuffer() for this purpose." }, { "code": null, "e": 6757, "s": 6707, "text": "The syntax of bindBuffer() method is as follows −" }, { "code": null, "e": 6803, "s": 6757, "text": "void bindBuffer (enum target, Object buffer)\n" }, { "code": null, "e": 6868, "s": 6803, "text": "This method accepts two parameters and they are discussed below." }, { "code": null, "e": 7064, "s": 6868, "text": "target − The first variable is an enum value representing the type of the buffer we want to bind to the empty buffer. You have two predefined enum values as options for this parameter. They are −" }, { "code": null, "e": 7107, "s": 7064, "text": "ARRAY_BUFFER which represents vertex data." }, { "code": null, "e": 7150, "s": 7107, "text": "ARRAY_BUFFER which represents vertex data." }, { "code": null, "e": 7200, "s": 7150, "text": "ELEMENT_ARRAY_BUFFER which represents index data." }, { "code": null, "e": 7250, "s": 7200, "text": "ELEMENT_ARRAY_BUFFER which represents index data." }, { "code": null, "e": 7444, "s": 7250, "text": "Object buffer − The second one is the reference variable to the buffer object created in the previous step. The reference variable can be of a vertex buffer object or of an index buffer object." }, { "code": null, "e": 7513, "s": 7444, "text": "The following code snippet shows how to use the bindBuffer() method." }, { "code": null, "e": 7724, "s": 7513, "text": "//vertex buffer\nvar vertex_buffer = gl.createBuffer();\ngl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n//Index buffer\nvar Index_Buffer = gl.createBuffer();\ngl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n" }, { "code": null, "e": 7985, "s": 7724, "text": "The next step is to pass the data (vertices/indices) to the buffer. Till now data is in the form of an array and before passing it to the buffer, we need to wrap it in one of the WebGL typed arrays. WebGL provides a method named bufferData() for this purpose." }, { "code": null, "e": 8035, "s": 7985, "text": "The syntax of bufferData() method is as follows −" }, { "code": null, "e": 8091, "s": 8035, "text": "void bufferData (enum target, Object data, enum usage)\n" }, { "code": null, "e": 8159, "s": 8091, "text": "This method accepts three parameters and they are discussed below −" }, { "code": null, "e": 8292, "s": 8159, "text": "target − The first parameter is an enum value representing the type of the array buffer we used.The options for this parameter are −" }, { "code": null, "e": 8335, "s": 8292, "text": "ARRAY_BUFFER which represents vertex data." }, { "code": null, "e": 8378, "s": 8335, "text": "ARRAY_BUFFER which represents vertex data." }, { "code": null, "e": 8428, "s": 8378, "text": "ELEMENT_ARRAY_BUFFER which represents index data." }, { "code": null, "e": 8478, "s": 8428, "text": "ELEMENT_ARRAY_BUFFER which represents index data." }, { "code": null, "e": 8642, "s": 8478, "text": "Object data − The second parameter is the object value that contains the data to be written to the buffer object. Here we have to pass the data using typed arrays." }, { "code": null, "e": 8844, "s": 8642, "text": "Usage − The third parameter of this method is an enum variable that specifies how to use the buffer object data (stored data) to draw shapes. There are three options for this parameter as listed below." }, { "code": null, "e": 8910, "s": 8844, "text": "gl.STATIC_DRAW − Data will be specified once and used many times." }, { "code": null, "e": 8976, "s": 8910, "text": "gl.STATIC_DRAW − Data will be specified once and used many times." }, { "code": null, "e": 9043, "s": 8976, "text": "gl.STREAM_DRAW − Data will be specified once and used a few times." }, { "code": null, "e": 9110, "s": 9043, "text": "gl.STREAM_DRAW − Data will be specified once and used a few times." }, { "code": null, "e": 9183, "s": 9110, "text": "gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times." }, { "code": null, "e": 9256, "s": 9183, "text": "gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times." }, { "code": null, "e": 9416, "s": 9256, "text": "The following code snippet shows how to use the bufferData() method. Assume vertices and indices are the arrays holding the vertex and index data respectively." }, { "code": null, "e": 9607, "s": 9416, "text": "//vertex buffer\ngl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n//Index buffer\ngl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n" }, { "code": null, "e": 9998, "s": 9607, "text": "WebGL provides a special type of array called typed arrays to transfer the data elements such as index vertex and texture. These typed arrays store large quantities of data and process them in native binary format which results in better performance. The typed arrays used by WebGL are Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, UInt32Array, Float32Array, and Float64Array." }, { "code": null, "e": 10003, "s": 9998, "text": "Note" }, { "code": null, "e": 10105, "s": 10003, "text": "Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array." }, { "code": null, "e": 10207, "s": 10105, "text": "Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array." }, { "code": null, "e": 10282, "s": 10207, "text": "You can create typed arrays just like JavaScript arrays using new keyword." }, { "code": null, "e": 10357, "s": 10282, "text": "You can create typed arrays just like JavaScript arrays using new keyword." }, { "code": null, "e": 10507, "s": 10357, "text": "It is recommended that you unbind the buffers after using them. It can be done by passing a null value in place of the buffer object, as shown below." }, { "code": null, "e": 10554, "s": 10507, "text": "gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n" }, { "code": null, "e": 10622, "s": 10554, "text": "WebGL provides the following methods to perform buffer operations −" }, { "code": null, "e": 10667, "s": 10622, "text": "void bindBuffer (enum target, Object buffer)" }, { "code": null, "e": 10711, "s": 10667, "text": "target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER" }, { "code": null, "e": 10763, "s": 10711, "text": "void bufferData(enum target, long size, enum usage)" }, { "code": null, "e": 10807, "s": 10763, "text": "target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER" }, { "code": null, "e": 10854, "s": 10807, "text": "usage − STATIC_DRAW, STREAM_DRAW, DYNAMIC_DRAW" }, { "code": null, "e": 10909, "s": 10854, "text": "void bufferData (enum target, Object data, enum usage)" }, { "code": null, "e": 10957, "s": 10909, "text": "target and usage − Same as for bufferData above" }, { "code": null, "e": 11015, "s": 10957, "text": "void bufferSubData(enum target, long offset, Object data)" }, { "code": null, "e": 11059, "s": 11015, "text": "target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER" }, { "code": null, "e": 11107, "s": 11059, "text": "any getBufferParameter(enum target, enum pname)" }, { "code": null, "e": 11152, "s": 11107, "text": "target − ARRAY_BUFFER, ELEMENT_ ARRAY_BUFFER" }, { "code": null, "e": 11186, "s": 11152, "text": "pname − BUFFER_SIZE, BUFFER_USAGE" }, { "code": null, "e": 11219, "s": 11186, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 11236, "s": 11219, "text": " Frahaan Hussain" }, { "code": null, "e": 11269, "s": 11236, "text": "\n 28 Lectures \n 4 hours \n" }, { "code": null, "e": 11286, "s": 11269, "text": " Frahaan Hussain" }, { "code": null, "e": 11293, "s": 11286, "text": " Print" }, { "code": null, "e": 11304, "s": 11293, "text": " Add Notes" } ]
Spotlighting Data in Simple Little Tables | by Michael Demastrie | Towards Data Science
When presenting tabular data, we often want to bring attention to a particular cell. This focus improves the visual support we want from our tables and keeps the audience from feeling overwhelmed by the breadth of the data contained in the whole set of values. Still, we want to present the key information in the context of the whole set. With tables, we can highlight the desired cells by making them different from others in size, weight, color, shape, spacing, or borders. This article expands on my earlier article, “Simple Little Tables with Matplotlib,” by providing a set of techniques we can use to highlight cells within a Matplotlib table. These techniques include ways to change the border width, background color, font weight, and font color of a cell. We will also see how to fade the cells not highlighted. Along the way, we’ll discover some related style techniques like changing the table grid line color and using open-source color palettes. I will annotate each step of the transformation to provide insight into pyplot.table behaviors that we might reuse to accomplish other tasks or for you to extend the discoveries I am sharing. I will present the full source code at the end of the article, so you don't need to piece it together, line by line. The starting point is the final code from the “Simple Little Tables with Matplotlib” article. These techniques should also work on any table derived from pyplot.table with a likely need for adjustments. The first thing we’ll do is change out the color palette from the colormap inherited from the pyplot.table example. I used a pleasant color palette called "Outcomes" by TaraLynn1221 on colourlovers.com. Using open sourced palettes from artistic communities is one way we design-challenged programmers can put together colors that at least match in some context. # colors from "Outcomes" palette by TaraLynn1221# https://www.colourlovers.com/palette/4751687/Outcomescl_outcomes = { 'white':'#FFFFFF', 'gray': '#AAA9AD', 'black':'#313639', 'purple':'#AD688E', 'orange':'#D18F77', 'yellow':'#E8E190', 'ltgreen':'#CCD9C7', 'dkgreen':'#96ABA0', }...# Get some lists of color specs for row and column headersrcolors = np.full(len(row_headers), cl_outcomes['ltgreen'])ccolors = np.full(len(column_headers), cl_outcomes['ltgreen']) I also created some color variables for the highlighted cells that we’ll create and for some other components in the drawing. grid_color = cl_outcomes['dkgreen']fig_background_color = cl_outcomes['white']fig_border = cl_outcomes['dkgreen']label_text_color = cl_outcomes['black']highlight_text_color = cl_outcomes['yellow']faded_text_color = cl_outcomes['gray']highlight_color = cl_outcomes['purple']highlight_border = cl_outcomes['dkgreen']title_text_color = cl_outcomes['black'] While I was at it, I updated and added some variables for text elements. In this example, we’ll be adding a text annotation and a subtitle to the figure. title_text = 'Loss by Disaster'subtitle_text = '(In millions of dollars)'annotation_text = 'The ten-year loss due to floods is $78.0M.'footer_text = 'July 28, 2020' Highlighting is accomplished by setting the fill and edge (border) colors of the cell. This procedure can be repeated for several cells, if you want. A Table object is made up of Cell objects. The cells are referenced using row, column indexing with (0,0) starting in the upper-left corner of the table. The column headers are within this matrix, so (0,0) refers to the first column header. Row headers are indeed part of this matrix, but are indexed as column -1. The following code will highlight the cell in the second row and third column. Remember that we have to consider that row 0 is the column header row. The column index of the row headers is -1. The top row header is (1,-1). To do the highlighting, we retrieve the cell from the table. Then we set the face color, edge color, and line width. To control the font styles, we get the Text object from the Cell. There are limitations on what Text attributes can be controlled. For example, setting the font size of a single cell has no effect. All cells in the data grid need to have the same font size, which is controlled at the Table level. Once we have made all the highlighting style changes we want, we call ax.add_patch() passing in a reference to the cell. You might think that simply changing the attributes would be enough to set the styles, but it does not seem to reposition the cell in the z-order and adjacent cell styles display on top of the highlighted cell. Adding the cell to the Axes object as a patch fixes that problem. If you find a more elegant way, let us know in the comments. # Highlight the cell to draw attention to itthe_cell = the_table[2,2]the_cell.set_facecolor(highlight_color)the_cell.set_edgecolor(highlight_border)the_cell.set_linewidth(2)the_text = the_cell.get_text()#the_text.set_weight('bold')the_text.set_fontstyle('italic')the_text.set_color(highlight_text_color)ax.add_patch(the_cell) Cell objects are subclasses of Matplotib Rectangles. Rectangles are subclasses of Patches. This inheritance means that you can reference the attributes and functions of Rectangle and Patches, giving you a lot of control over the formatting. To draw more attention to the highlighted cell, we can fade them. We’ll set them to a lighter color using a technique similar to highlighting. We can call get_children() to get a list of cells and loop through them. A table only contains cells, so there is no need to type-check the elements. For each cell, we get its text object. Excluding headers from the process is as simple as checking the cell text for its presence in the header label lists. Of course, if you have cells with values that match the labels, you'll need to come up with another way. This looping technique is also how we set table border color, so let's add cell.set_edgecolor(grid_color) here. There is no attribute on the Table object to set this color, so looping is how we do it. # Fade the cellsfor cell in the_table.get_children(): cell_text = cell.get_text().get_text() cell.set_edgecolor(grid_color) if cell_text not in row_headers\ and cell_text not in column_headers: cell.get_text().set_color(faded_text_color) else: cell.get_text().set_weight('bold') cell.get_text().set_color(label_text_color) We could have added code to exclude the highlighted cells. It’s easier just to fade them all before highlighting, though. So let’s just insert the fading code routine earlier in the flow. An alternative to get_children() is get_celld(). While get_children() returns a list of Artist objects that happen to only be Cells here, get_celld() will return a dictionary of Cells with keys that are row and column tuples. print(the_table.get_children())[<matplotlib.table.CustomCell object at 0x7fb7b430f150>, <matplotlib.table.CustomCell object at 0x7fb7b6bf2890>, <matplotlib.table.CustomCell object at 0x7fb7b6bf26d0>,...print(the_table.get_celld()){(1, 0): <matplotlib.table.CustomCell object at 0x7fb7b4313390>, (1, 1): <matplotlib.table.CustomCell object at 0x7fb7b4313e50>, (1, 2): <matplotlib.table.CustomCell object at 0x7fb7b4313150>,... Tip: get_celld() can be used to generate an index table of cell text to use in troubleshooting or manually referencing cells by index. for key, val in the_table.get_celld().items(): # call get_text() on Cell and again on returned Text print(f'{key}\t{val.get_text().get_text()}')(1, 0) 66.4(1, 1) 174.3(1, 2) 75.1... If we’re going to use our table image in a presentation or report, we may want to add a text annotation to it to help the reader to understand why we are calling out the cell value. A subtitle can help the reader understand the figure, too. In our case, we have not let the reader know what the units of measure are in our table, so that information might make a good subtitle. There are several ways to create annotations in Matplotlib. We have a good amount of whitespace surrounding the table, so let’s use a simple line of figure text below the chart. We’ll include some styling, too. # Add annotationplt.figtext(0.5, 0.2, annotation_text, horizontalalignment='center', size=9, weight='light', color=title_text_color ) Matplotlib does not give us a first-class subtitle function, so we’ll use figure text, too. Unfortunately, this means we may need to tweak it’s positioning if we change the title or overall figure structure later. We could go through heroics to calculate the subtitle position relative to the figure and title, but we’ll keep it simple and hard-code the subtitle position based on experimentation. # Add subtitleplt.figtext(0.5, 0.9, subtitle_text, horizontalalignment='center', size=9, style='italic', color=title_text_color ) Note: Remember that suptitle() is the function to set the title on the figure and not a subtitle. Unfortunate naming. Here is the final source code. I also added some explicit styling to the title and footer. I have a designer friend who taught me that the best black in graphic design is not pure black, so we’re using #313639 instead of #000000. Here is the final product, from which you can clip to your heart’s extent. import numpy as npimport matplotlib.pyplot as plt# colors from "Outcomes" palette by TaraLynn1221# https://www.colourlovers.com/palette/4751687/Outcomescl_outcomes = { 'white':'#FFFFFF', 'gray': '#AAA9AD', 'black':'#313639', 'purple':'#AD688E', 'orange':'#D18F77', 'yellow':'#E8E190', 'ltgreen':'#CCD9C7', 'dkgreen':'#96ABA0', }title_text = 'Loss by Disaster'subtitle_text = '(In millions of dollars)'annotation_text = 'The ten-year loss due to floods is $78.0M.'footer_text = 'July 28, 2020'grid_color = cl_outcomes['dkgreen']fig_background_color = cl_outcomes['white']fig_border = cl_outcomes['dkgreen']label_text_color = cl_outcomes['black']highlight_text_color = cl_outcomes['yellow']faded_text_color = cl_outcomes['gray']highlight_color = cl_outcomes['purple']highlight_border = cl_outcomes['dkgreen']title_text_color = cl_outcomes['black']data = [ [ 'Freeze', 'Wind', 'Flood', 'Quake', 'Hail'], [ '5 year', 66386, 174296, 75131, 577908, 32015], ['10 year', 58230, 381139, 78045, 99308, 160454], ['20 year', 89135, 80552, 152558, 497981, 603535], ['30 year', 78415, 81858, 150656, 193263, 69638], ['40 year', 139361, 331509, 343164, 781380, 52269], ]# Pop the headers from the data arraycolumn_headers = data.pop(0)row_headers = [x.pop(0) for x in data]# Table data needs to be non-numeric text. Format the data# while I'm at it.cell_text = []for row in data: cell_text.append([f'{x/1000:1.1f}' for x in row])# Get some lists of color specs for row and column headersrcolors = np.full(len(row_headers), cl_outcomes['ltgreen'])ccolors = np.full(len(column_headers), cl_outcomes['ltgreen'])# Create the figure. Setting a small pad on tight_layout# seems to better regulate white space. Sometimes experimenting# with an explicit figsize here can produce better outcome.plt.figure(linewidth=1, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1}, #figsize=(5,3) )# Add a table at the bottom of the axesthe_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, rowLoc='right', colColours=ccolors, colLabels=column_headers, loc='center')# Scaling is the only influence we have over top and bottom cell padding.# Make the rows taller (i.e., make cell y scale larger).the_table.scale(1, 1.5)# Hide axesax = plt.gca()ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)# Hide axes borderplt.box(on=None)# Add titleplt.suptitle(title_text, weight='bold', size=14, color=title_text_color)# Add subtitleplt.figtext(0.5, 0.9, subtitle_text, horizontalalignment='center', size=9, style='italic', color=title_text_color )# Add footerplt.figtext(0.95, 0.05, footer_text, horizontalalignment='right', size=6, weight='light', color=title_text_color )# Add annotationplt.figtext(0.5, 0.2, annotation_text, horizontalalignment='center', size=9, weight='light', color=title_text_color )# Fade the cellsfor cell in the_table.get_children(): cell_text = cell.get_text().get_text() cell.set_edgecolor(grid_color) if cell_text not in row_headers\ and cell_text not in column_headers: cell.get_text().set_color(faded_text_color) else: cell.get_text().set_weight('bold') cell.get_text().set_color(label_text_color)# Highlight the cell to draw attention to itthe_cell = the_table[2,2]the_cell.set_facecolor(highlight_color)the_cell.set_edgecolor(highlight_border)the_cell.set_linewidth(2)the_text = the_cell.get_text()#the_text.set_weight('bold')the_text.set_fontstyle('italic')the_text.set_color(highlight_text_color)ax.add_patch(the_cell)# Force the figure to update, so backends center objects correctly within the figure.# Without plt.draw() here, the title will center on the axes and not the figure.plt.draw()# Create image. plt.savefig ignores figure edge and face colors, so map them.fig = plt.gcf()plt.savefig('pyplot-table-highlight.png', bbox='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=300 ) We have taken our first little table and added some highlighting to a cell to make it more visible for our audiences. We learned how to harvest color palettes from open design sites. We saw highlighting techniques based on size, color, relative fading, and borders. We learned an easy way to add an annotation and subtitle. Matplotlib tables are a flexible and powerful tool for presenting your tabular summary data.
[ { "code": null, "e": 649, "s": 172, "text": "When presenting tabular data, we often want to bring attention to a particular cell. This focus improves the visual support we want from our tables and keeps the audience from feeling overwhelmed by the breadth of the data contained in the whole set of values. Still, we want to present the key information in the context of the whole set. With tables, we can highlight the desired cells by making them different from others in size, weight, color, shape, spacing, or borders." }, { "code": null, "e": 1441, "s": 649, "text": "This article expands on my earlier article, “Simple Little Tables with Matplotlib,” by providing a set of techniques we can use to highlight cells within a Matplotlib table. These techniques include ways to change the border width, background color, font weight, and font color of a cell. We will also see how to fade the cells not highlighted. Along the way, we’ll discover some related style techniques like changing the table grid line color and using open-source color palettes. I will annotate each step of the transformation to provide insight into pyplot.table behaviors that we might reuse to accomplish other tasks or for you to extend the discoveries I am sharing. I will present the full source code at the end of the article, so you don't need to piece it together, line by line." }, { "code": null, "e": 1644, "s": 1441, "text": "The starting point is the final code from the “Simple Little Tables with Matplotlib” article. These techniques should also work on any table derived from pyplot.table with a likely need for adjustments." }, { "code": null, "e": 2006, "s": 1644, "text": "The first thing we’ll do is change out the color palette from the colormap inherited from the pyplot.table example. I used a pleasant color palette called \"Outcomes\" by TaraLynn1221 on colourlovers.com. Using open sourced palettes from artistic communities is one way we design-challenged programmers can put together colors that at least match in some context." }, { "code": null, "e": 2495, "s": 2006, "text": "# colors from \"Outcomes\" palette by TaraLynn1221# https://www.colourlovers.com/palette/4751687/Outcomescl_outcomes = { 'white':'#FFFFFF', 'gray': '#AAA9AD', 'black':'#313639', 'purple':'#AD688E', 'orange':'#D18F77', 'yellow':'#E8E190', 'ltgreen':'#CCD9C7', 'dkgreen':'#96ABA0', }...# Get some lists of color specs for row and column headersrcolors = np.full(len(row_headers), cl_outcomes['ltgreen'])ccolors = np.full(len(column_headers), cl_outcomes['ltgreen'])" }, { "code": null, "e": 2621, "s": 2495, "text": "I also created some color variables for the highlighted cells that we’ll create and for some other components in the drawing." }, { "code": null, "e": 2975, "s": 2621, "text": "grid_color = cl_outcomes['dkgreen']fig_background_color = cl_outcomes['white']fig_border = cl_outcomes['dkgreen']label_text_color = cl_outcomes['black']highlight_text_color = cl_outcomes['yellow']faded_text_color = cl_outcomes['gray']highlight_color = cl_outcomes['purple']highlight_border = cl_outcomes['dkgreen']title_text_color = cl_outcomes['black']" }, { "code": null, "e": 3129, "s": 2975, "text": "While I was at it, I updated and added some variables for text elements. In this example, we’ll be adding a text annotation and a subtitle to the figure." }, { "code": null, "e": 3294, "s": 3129, "text": "title_text = 'Loss by Disaster'subtitle_text = '(In millions of dollars)'annotation_text = 'The ten-year loss due to floods is $78.0M.'footer_text = 'July 28, 2020'" }, { "code": null, "e": 3444, "s": 3294, "text": "Highlighting is accomplished by setting the fill and edge (border) colors of the cell. This procedure can be repeated for several cells, if you want." }, { "code": null, "e": 3759, "s": 3444, "text": "A Table object is made up of Cell objects. The cells are referenced using row, column indexing with (0,0) starting in the upper-left corner of the table. The column headers are within this matrix, so (0,0) refers to the first column header. Row headers are indeed part of this matrix, but are indexed as column -1." }, { "code": null, "e": 3982, "s": 3759, "text": "The following code will highlight the cell in the second row and third column. Remember that we have to consider that row 0 is the column header row. The column index of the row headers is -1. The top row header is (1,-1)." }, { "code": null, "e": 4397, "s": 3982, "text": "To do the highlighting, we retrieve the cell from the table. Then we set the face color, edge color, and line width. To control the font styles, we get the Text object from the Cell. There are limitations on what Text attributes can be controlled. For example, setting the font size of a single cell has no effect. All cells in the data grid need to have the same font size, which is controlled at the Table level." }, { "code": null, "e": 4856, "s": 4397, "text": "Once we have made all the highlighting style changes we want, we call ax.add_patch() passing in a reference to the cell. You might think that simply changing the attributes would be enough to set the styles, but it does not seem to reposition the cell in the z-order and adjacent cell styles display on top of the highlighted cell. Adding the cell to the Axes object as a patch fixes that problem. If you find a more elegant way, let us know in the comments." }, { "code": null, "e": 5182, "s": 4856, "text": "# Highlight the cell to draw attention to itthe_cell = the_table[2,2]the_cell.set_facecolor(highlight_color)the_cell.set_edgecolor(highlight_border)the_cell.set_linewidth(2)the_text = the_cell.get_text()#the_text.set_weight('bold')the_text.set_fontstyle('italic')the_text.set_color(highlight_text_color)ax.add_patch(the_cell)" }, { "code": null, "e": 5423, "s": 5182, "text": "Cell objects are subclasses of Matplotib Rectangles. Rectangles are subclasses of Patches. This inheritance means that you can reference the attributes and functions of Rectangle and Patches, giving you a lot of control over the formatting." }, { "code": null, "e": 6179, "s": 5423, "text": "To draw more attention to the highlighted cell, we can fade them. We’ll set them to a lighter color using a technique similar to highlighting. We can call get_children() to get a list of cells and loop through them. A table only contains cells, so there is no need to type-check the elements. For each cell, we get its text object. Excluding headers from the process is as simple as checking the cell text for its presence in the header label lists. Of course, if you have cells with values that match the labels, you'll need to come up with another way. This looping technique is also how we set table border color, so let's add cell.set_edgecolor(grid_color) here. There is no attribute on the Table object to set this color, so looping is how we do it." }, { "code": null, "e": 6541, "s": 6179, "text": "# Fade the cellsfor cell in the_table.get_children(): cell_text = cell.get_text().get_text() cell.set_edgecolor(grid_color) if cell_text not in row_headers\\ and cell_text not in column_headers: cell.get_text().set_color(faded_text_color) else: cell.get_text().set_weight('bold') cell.get_text().set_color(label_text_color)" }, { "code": null, "e": 6729, "s": 6541, "text": "We could have added code to exclude the highlighted cells. It’s easier just to fade them all before highlighting, though. So let’s just insert the fading code routine earlier in the flow." }, { "code": null, "e": 6955, "s": 6729, "text": "An alternative to get_children() is get_celld(). While get_children() returns a list of Artist objects that happen to only be Cells here, get_celld() will return a dictionary of Cells with keys that are row and column tuples." }, { "code": null, "e": 7381, "s": 6955, "text": "print(the_table.get_children())[<matplotlib.table.CustomCell object at 0x7fb7b430f150>, <matplotlib.table.CustomCell object at 0x7fb7b6bf2890>, <matplotlib.table.CustomCell object at 0x7fb7b6bf26d0>,...print(the_table.get_celld()){(1, 0): <matplotlib.table.CustomCell object at 0x7fb7b4313390>, (1, 1): <matplotlib.table.CustomCell object at 0x7fb7b4313e50>, (1, 2): <matplotlib.table.CustomCell object at 0x7fb7b4313150>,..." }, { "code": null, "e": 7516, "s": 7381, "text": "Tip: get_celld() can be used to generate an index table of cell text to use in troubleshooting or manually referencing cells by index." }, { "code": null, "e": 7701, "s": 7516, "text": "for key, val in the_table.get_celld().items():\t# call get_text() on Cell and again on returned Text print(f'{key}\\t{val.get_text().get_text()}')(1, 0)\t66.4(1, 1)\t174.3(1, 2)\t75.1..." }, { "code": null, "e": 8079, "s": 7701, "text": "If we’re going to use our table image in a presentation or report, we may want to add a text annotation to it to help the reader to understand why we are calling out the cell value. A subtitle can help the reader understand the figure, too. In our case, we have not let the reader know what the units of measure are in our table, so that information might make a good subtitle." }, { "code": null, "e": 8290, "s": 8079, "text": "There are several ways to create annotations in Matplotlib. We have a good amount of whitespace surrounding the table, so let’s use a simple line of figure text below the chart. We’ll include some styling, too." }, { "code": null, "e": 8478, "s": 8290, "text": "# Add annotationplt.figtext(0.5, 0.2, annotation_text, horizontalalignment='center', size=9, weight='light', color=title_text_color )" }, { "code": null, "e": 8876, "s": 8478, "text": "Matplotlib does not give us a first-class subtitle function, so we’ll use figure text, too. Unfortunately, this means we may need to tweak it’s positioning if we change the title or overall figure structure later. We could go through heroics to calculate the subtitle position relative to the figure and title, but we’ll keep it simple and hard-code the subtitle position based on experimentation." }, { "code": null, "e": 9060, "s": 8876, "text": "# Add subtitleplt.figtext(0.5, 0.9, subtitle_text, horizontalalignment='center', size=9, style='italic', color=title_text_color )" }, { "code": null, "e": 9178, "s": 9060, "text": "Note: Remember that suptitle() is the function to set the title on the figure and not a subtitle. Unfortunate naming." }, { "code": null, "e": 9408, "s": 9178, "text": "Here is the final source code. I also added some explicit styling to the title and footer. I have a designer friend who taught me that the best black in graphic design is not pure black, so we’re using #313639 instead of #000000." }, { "code": null, "e": 9483, "s": 9408, "text": "Here is the final product, from which you can clip to your heart’s extent." }, { "code": null, "e": 13962, "s": 9483, "text": "import numpy as npimport matplotlib.pyplot as plt# colors from \"Outcomes\" palette by TaraLynn1221# https://www.colourlovers.com/palette/4751687/Outcomescl_outcomes = { 'white':'#FFFFFF', 'gray': '#AAA9AD', 'black':'#313639', 'purple':'#AD688E', 'orange':'#D18F77', 'yellow':'#E8E190', 'ltgreen':'#CCD9C7', 'dkgreen':'#96ABA0', }title_text = 'Loss by Disaster'subtitle_text = '(In millions of dollars)'annotation_text = 'The ten-year loss due to floods is $78.0M.'footer_text = 'July 28, 2020'grid_color = cl_outcomes['dkgreen']fig_background_color = cl_outcomes['white']fig_border = cl_outcomes['dkgreen']label_text_color = cl_outcomes['black']highlight_text_color = cl_outcomes['yellow']faded_text_color = cl_outcomes['gray']highlight_color = cl_outcomes['purple']highlight_border = cl_outcomes['dkgreen']title_text_color = cl_outcomes['black']data = [ [ 'Freeze', 'Wind', 'Flood', 'Quake', 'Hail'], [ '5 year', 66386, 174296, 75131, 577908, 32015], ['10 year', 58230, 381139, 78045, 99308, 160454], ['20 year', 89135, 80552, 152558, 497981, 603535], ['30 year', 78415, 81858, 150656, 193263, 69638], ['40 year', 139361, 331509, 343164, 781380, 52269], ]# Pop the headers from the data arraycolumn_headers = data.pop(0)row_headers = [x.pop(0) for x in data]# Table data needs to be non-numeric text. Format the data# while I'm at it.cell_text = []for row in data: cell_text.append([f'{x/1000:1.1f}' for x in row])# Get some lists of color specs for row and column headersrcolors = np.full(len(row_headers), cl_outcomes['ltgreen'])ccolors = np.full(len(column_headers), cl_outcomes['ltgreen'])# Create the figure. Setting a small pad on tight_layout# seems to better regulate white space. Sometimes experimenting# with an explicit figsize here can produce better outcome.plt.figure(linewidth=1, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1}, #figsize=(5,3) )# Add a table at the bottom of the axesthe_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, rowLoc='right', colColours=ccolors, colLabels=column_headers, loc='center')# Scaling is the only influence we have over top and bottom cell padding.# Make the rows taller (i.e., make cell y scale larger).the_table.scale(1, 1.5)# Hide axesax = plt.gca()ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)# Hide axes borderplt.box(on=None)# Add titleplt.suptitle(title_text, weight='bold', size=14, color=title_text_color)# Add subtitleplt.figtext(0.5, 0.9, subtitle_text, horizontalalignment='center', size=9, style='italic', color=title_text_color )# Add footerplt.figtext(0.95, 0.05, footer_text, horizontalalignment='right', size=6, weight='light', color=title_text_color )# Add annotationplt.figtext(0.5, 0.2, annotation_text, horizontalalignment='center', size=9, weight='light', color=title_text_color )# Fade the cellsfor cell in the_table.get_children(): cell_text = cell.get_text().get_text() cell.set_edgecolor(grid_color) if cell_text not in row_headers\\ and cell_text not in column_headers: cell.get_text().set_color(faded_text_color) else: cell.get_text().set_weight('bold') cell.get_text().set_color(label_text_color)# Highlight the cell to draw attention to itthe_cell = the_table[2,2]the_cell.set_facecolor(highlight_color)the_cell.set_edgecolor(highlight_border)the_cell.set_linewidth(2)the_text = the_cell.get_text()#the_text.set_weight('bold')the_text.set_fontstyle('italic')the_text.set_color(highlight_text_color)ax.add_patch(the_cell)# Force the figure to update, so backends center objects correctly within the figure.# Without plt.draw() here, the title will center on the axes and not the figure.plt.draw()# Create image. plt.savefig ignores figure edge and face colors, so map them.fig = plt.gcf()plt.savefig('pyplot-table-highlight.png', bbox='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=300 )" } ]
time.Time.Date() Function in Golang with Examples - GeeksforGeeks
19 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Date() function in Go language is used to check the year, month, and day in which the stated “t” presents itself. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func (t Time) Date() (year int, month Month, day int) Here, “t” is the stated time. Return Value: It returns year, month and day of the stated “t”. Example 1: // Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 5, 6, 11, 45, 04, 0, time.UTC) // Calling Date method yyyy, mm, dd := t.Date() // Prints year fmt.Printf("The stated year is: %v\n", yyyy) // Prints month fmt.Printf("The stated month is: %v\n", mm) // Prints day fmt.Printf("The stated day is: %v\n", dd)} Output: The stated year is: 2020 The stated month is: May The stated day is: 6 Example 2: // Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 13, 34, 00, 00, 00, 0, time.UTC) // Calling Date method yyyy, mm, dd := t.Date() // Prints year fmt.Printf("The stated year is: %v\n", yyyy) // Prints month fmt.Printf("The stated month is: %v\n", mm) // Prints day fmt.Printf("The stated day is: %v\n", dd)} Output: The stated year is: 2021 The stated month is: February The stated day is: 3 Here, the stated month and day are out of usual range but they are normalized while conversion. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Parse JSON in Golang? Defer Keyword in Golang Rune in Golang Anonymous function in Go Language Class and Object in Golang Loops in Go Language Time Durations in Golang Structures in Golang Strings in Golang How to iterate over an Array using for loop in Golang?
[ { "code": null, "e": 24069, "s": 24041, "text": "\n19 Apr, 2020" }, { "code": null, "e": 24422, "s": 24069, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Date() function in Go language is used to check the year, month, and day in which the stated “t” presents itself. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 24430, "s": 24422, "text": "Syntax:" }, { "code": null, "e": 24485, "s": 24430, "text": "func (t Time) Date() (year int, month Month, day int)\n" }, { "code": null, "e": 24515, "s": 24485, "text": "Here, “t” is the stated time." }, { "code": null, "e": 24579, "s": 24515, "text": "Return Value: It returns year, month and day of the stated “t”." }, { "code": null, "e": 24590, "s": 24579, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 5, 6, 11, 45, 04, 0, time.UTC) // Calling Date method yyyy, mm, dd := t.Date() // Prints year fmt.Printf(\"The stated year is: %v\\n\", yyyy) // Prints month fmt.Printf(\"The stated month is: %v\\n\", mm) // Prints day fmt.Printf(\"The stated day is: %v\\n\", dd)}", "e": 25120, "s": 24590, "text": null }, { "code": null, "e": 25128, "s": 25120, "text": "Output:" }, { "code": null, "e": 25200, "s": 25128, "text": "The stated year is: 2020\nThe stated month is: May\nThe stated day is: 6\n" }, { "code": null, "e": 25211, "s": 25200, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t in UTC t := time.Date(2020, 13, 34, 00, 00, 00, 0, time.UTC) // Calling Date method yyyy, mm, dd := t.Date() // Prints year fmt.Printf(\"The stated year is: %v\\n\", yyyy) // Prints month fmt.Printf(\"The stated month is: %v\\n\", mm) // Prints day fmt.Printf(\"The stated day is: %v\\n\", dd)}", "e": 25743, "s": 25211, "text": null }, { "code": null, "e": 25751, "s": 25743, "text": "Output:" }, { "code": null, "e": 25828, "s": 25751, "text": "The stated year is: 2021\nThe stated month is: February\nThe stated day is: 3\n" }, { "code": null, "e": 25924, "s": 25828, "text": "Here, the stated month and day are out of usual range but they are normalized while conversion." }, { "code": null, "e": 25936, "s": 25924, "text": "GoLang-time" }, { "code": null, "e": 25948, "s": 25936, "text": "Go Language" }, { "code": null, "e": 26046, "s": 25948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26055, "s": 26046, "text": "Comments" }, { "code": null, "e": 26068, "s": 26055, "text": "Old Comments" }, { "code": null, "e": 26097, "s": 26068, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 26121, "s": 26097, "text": "Defer Keyword in Golang" }, { "code": null, "e": 26136, "s": 26121, "text": "Rune in Golang" }, { "code": null, "e": 26170, "s": 26136, "text": "Anonymous function in Go Language" }, { "code": null, "e": 26197, "s": 26170, "text": "Class and Object in Golang" }, { "code": null, "e": 26218, "s": 26197, "text": "Loops in Go Language" }, { "code": null, "e": 26243, "s": 26218, "text": "Time Durations in Golang" }, { "code": null, "e": 26264, "s": 26243, "text": "Structures in Golang" }, { "code": null, "e": 26282, "s": 26264, "text": "Strings in Golang" } ]
First time fine-tuning BERT framework | Towards Data Science
My interest in the field of NLP started when I decided to participate in one of the ongoing competition of identifying whether the given tweet is about any disaster or not. I was not having any experience in the field of language processing, and after a few internet searches, I came to know about some of the text preprocessing of data like tokenization and lemmatization, used TfidfTransformer and TfidfVectorizer for feature extraction then simply used Naive Bayes for classification (score = 0.77). I took a deep learning specialization course in the meantime and came to know about RNN and decided to use the LTSM model for this task and got better results(score = 0.79987, Top 40%). In that course, there was mention of transfer learning and how it could be a powerful tool for any task. I thought why not try this on a dataset I have right now. I searched about different frameworks in NLP and came to know about BERT. It is said to be one of the most powerful and influential models in the field of NLP by Google, trained on a large unlabelled dataset to achieve State-of-the-Art results on 11 individual NLP tasks. It can be fine-tuned according to your needs thus making it even more powerful. I decided to use this framework and fine-tune it according to my dataset. I was searching how to use this framework and came across the Hugging face transformers which provides general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural Language Understanding (NLU) and Natural Language Generation (NLG) with over 32+ pre-trained models in 100+ languages and deep interoperability between TensorFlow 2.0 and PyTorch. I was able to fine-tune this model after lot of experimentation and reading the documentation and hopeful this experience could also help you in some way. First, let’s see the data given data = pd.read('train.csv')data.head() data.describe(include = 'all') Similarly, there is a ‘test.csv’ whose tweets we have to predict. We can combine both datasets and do some necessary operations on them. We can drop the keyword and location column so we can make predictions from the given tweets only. df1 = pd.read_csv('content/drive/My Drive/disaster tweets/train.csv')df2 = pd.read_csv('content/drive/My Drive/disaster tweets/test.csv')combined = pd.concat([df1,df2], axis=0)combined = combined.drop(['keyword','location'], axis=1) I didn’t pre-process or clean the data (e.g- removing punctuations or removing HTML tags etc.) as I just wanted to see how to work with the framework. I am sure that cleaning and working with data will further give better results. from transformers import BertForSequenceClassification, AdamW #importing appropriate class for classificationimport numpy as npimport pandas as pdimport torchmodel = BertForSequenceClassification.from_pretrained('bert-base-uncased') #Importing the bert modelmodel.train() #tell model its in training mode so that somelayers(dropout,batchnorm) behave accordingly Tokenisation and encoding For using the BERT model we have to first tokenize and encode our text and BERT tokenizer is provided in hugging face transformer. from transformers import BertTokenizertokenizer = BertTokenizer.from_pretrained(‘bert-base-uncased’)encoded = tokenizer(combined.text.values.tolist(), padding=True, truncation=True, return_tensors='pt') The encoder gives three tensors for a single tweet in the form of a dictionary (‘input_ids’, ‘attention_mask’, ‘token_type_ids’) which is used by the model. Now, let’s separate the tensors into different variables(we only need ‘input_ids’ and ‘attention_mask’ )and break the combined data again in the test and train format. input_id = encoded['input_ids']attention_mask = encoded['attention_mask']train_id = input_id[:len(df1)]train_am = attention_mask[:len(df1)]test_id = input_id[len(df1):]test_am = attention_mask[len(df1):]train = combined.iloc[:len(df1)]test = combined.iloc[len(df1):] For training and testing purposes let’s split the train data into two parts for training and testing of the model. Xtrain = train.iloc[:6800]Xtest = train.iloc[6800:]Xtrain_id = train_id[:6800]Xtrain_am = train_am[:6800]Xtest_id = train_id[6800:]Xtest_am = train_am[6800:]labels = torch.tensor(Xtrain.target.values.tolist())labels = labels.type(torch.LongTensor)labels.shape Fine-tuning the model Now, let’s focus on the model. We will use PyTorch for training the model(TensorFlow could also be used). First, we will configure our optimizer (Adam) and then we will train our model in batch so that our machine( CPU, GPU) doesn’t crash. optimizer = AdamW(model.parameters(), lr=1e-5)n_epochs = 1 batch_size = 32 for epoch in range(n_epochs): permutation = torch.randperm(Xtrain_id.size()[0]) for i in range(0,Xtrain_id.size()[0], batch_size): optimizer.zero_grad() indices = permutation[i:i+batch_size] batch_x, batch_y,batch_am = Xtrain_id[indices], labels[indices], Xtrain_am[indices] outputs = model(batch_x, attention_mask=batch_am, labels=batch_y) loss = outputs[0] loss.backward() optimizer.step() Here outputs give us a tuple containing cross-entropy loss and final activation of the model. For example, here is the output of two tensors We can use these activations to classify the disaster tweets with the help of the softmax activation function. Now let’s test the model with the help of remaining data in the training set. First, we have to put the model in the test mode and then take outputs from the model. model.eval() #model in testing modebatch_size = 32permutation = torch.randperm(Xtest_id.size()[0])for i in range(0,Xtest_id.size()[0], batch_size): indices = permutation[i:i+batch_size] batch_x, batch_y, batch_am = Xtest_id[indices], labels[indices], Xtest_am[indices] outputs = model(batch_x, attention_mask=batch_am, labels=batch_y) loss = outputs[0] print('Loss:' ,loss) You can also get an accuracy metric by comparing output with the label and calculate (correct prediction)/(total tweets) * 100. Now, let’s predict our actual test data whose output we have to find. import torch.nn.functional as F #for softmax function batch_size = 32prediction = np.empty((0,2)) #empty numpy for appending our outputids = torch.tensor(range(original_test_id.size()[0]))for i in range(0,original_test_id.size()[0], batch_size): indices = ids[i:i+batch_size] batch_x1, batch_am1 = original_test_id[indices], original_test_am[indices] pred = model(batch_x1, batch_am1) #Here only activation is given as output pt_predictions = F.softmax(pred[0], dim=-1) #applying softmax activation function prediction = np.append(prediction, pt_predictions.detach().numpy(), axis=0) #appending the prediction As we can see prediction has two columns, prediction[:,0] gives the probability of having label 0 and prediction[:,1] gives the probability of having label 1. We can use the argmax function to find the proper label. sub = np.argmax(prediction, axis=1) Then by arranging these labels with the proper id we can get our predictions. submission = pd.DataFrame({'id': test.id.values, 'target':sub}) Using this model I got score 0.83695 and placed in the top 12% without even cleaning or processing the data. So we can see how powerful this framework is how it can be used for various purposes. You can also see code here. I hope my experience could help you in some way also let me know what more could be done to improve the performance (as I am also a newbie in NLP :P).
[ { "code": null, "e": 1024, "s": 172, "text": "My interest in the field of NLP started when I decided to participate in one of the ongoing competition of identifying whether the given tweet is about any disaster or not. I was not having any experience in the field of language processing, and after a few internet searches, I came to know about some of the text preprocessing of data like tokenization and lemmatization, used TfidfTransformer and TfidfVectorizer for feature extraction then simply used Naive Bayes for classification (score = 0.77). I took a deep learning specialization course in the meantime and came to know about RNN and decided to use the LTSM model for this task and got better results(score = 0.79987, Top 40%). In that course, there was mention of transfer learning and how it could be a powerful tool for any task. I thought why not try this on a dataset I have right now." }, { "code": null, "e": 1825, "s": 1024, "text": "I searched about different frameworks in NLP and came to know about BERT. It is said to be one of the most powerful and influential models in the field of NLP by Google, trained on a large unlabelled dataset to achieve State-of-the-Art results on 11 individual NLP tasks. It can be fine-tuned according to your needs thus making it even more powerful. I decided to use this framework and fine-tune it according to my dataset. I was searching how to use this framework and came across the Hugging face transformers which provides general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural Language Understanding (NLU) and Natural Language Generation (NLG) with over 32+ pre-trained models in 100+ languages and deep interoperability between TensorFlow 2.0 and PyTorch." }, { "code": null, "e": 1980, "s": 1825, "text": "I was able to fine-tune this model after lot of experimentation and reading the documentation and hopeful this experience could also help you in some way." }, { "code": null, "e": 2012, "s": 1980, "text": "First, let’s see the data given" }, { "code": null, "e": 2051, "s": 2012, "text": "data = pd.read('train.csv')data.head()" }, { "code": null, "e": 2082, "s": 2051, "text": "data.describe(include = 'all')" }, { "code": null, "e": 2318, "s": 2082, "text": "Similarly, there is a ‘test.csv’ whose tweets we have to predict. We can combine both datasets and do some necessary operations on them. We can drop the keyword and location column so we can make predictions from the given tweets only." }, { "code": null, "e": 2551, "s": 2318, "text": "df1 = pd.read_csv('content/drive/My Drive/disaster tweets/train.csv')df2 = pd.read_csv('content/drive/My Drive/disaster tweets/test.csv')combined = pd.concat([df1,df2], axis=0)combined = combined.drop(['keyword','location'], axis=1)" }, { "code": null, "e": 2782, "s": 2551, "text": "I didn’t pre-process or clean the data (e.g- removing punctuations or removing HTML tags etc.) as I just wanted to see how to work with the framework. I am sure that cleaning and working with data will further give better results." }, { "code": null, "e": 3153, "s": 2782, "text": "from transformers import BertForSequenceClassification, AdamW #importing appropriate class for classificationimport numpy as npimport pandas as pdimport torchmodel = BertForSequenceClassification.from_pretrained('bert-base-uncased') #Importing the bert modelmodel.train() #tell model its in training mode so that somelayers(dropout,batchnorm) behave accordingly" }, { "code": null, "e": 3179, "s": 3153, "text": "Tokenisation and encoding" }, { "code": null, "e": 3310, "s": 3179, "text": "For using the BERT model we have to first tokenize and encode our text and BERT tokenizer is provided in hugging face transformer." }, { "code": null, "e": 3513, "s": 3310, "text": "from transformers import BertTokenizertokenizer = BertTokenizer.from_pretrained(‘bert-base-uncased’)encoded = tokenizer(combined.text.values.tolist(), padding=True, truncation=True, return_tensors='pt')" }, { "code": null, "e": 3670, "s": 3513, "text": "The encoder gives three tensors for a single tweet in the form of a dictionary (‘input_ids’, ‘attention_mask’, ‘token_type_ids’) which is used by the model." }, { "code": null, "e": 3838, "s": 3670, "text": "Now, let’s separate the tensors into different variables(we only need ‘input_ids’ and ‘attention_mask’ )and break the combined data again in the test and train format." }, { "code": null, "e": 4105, "s": 3838, "text": "input_id = encoded['input_ids']attention_mask = encoded['attention_mask']train_id = input_id[:len(df1)]train_am = attention_mask[:len(df1)]test_id = input_id[len(df1):]test_am = attention_mask[len(df1):]train = combined.iloc[:len(df1)]test = combined.iloc[len(df1):]" }, { "code": null, "e": 4220, "s": 4105, "text": "For training and testing purposes let’s split the train data into two parts for training and testing of the model." }, { "code": null, "e": 4481, "s": 4220, "text": "Xtrain = train.iloc[:6800]Xtest = train.iloc[6800:]Xtrain_id = train_id[:6800]Xtrain_am = train_am[:6800]Xtest_id = train_id[6800:]Xtest_am = train_am[6800:]labels = torch.tensor(Xtrain.target.values.tolist())labels = labels.type(torch.LongTensor)labels.shape" }, { "code": null, "e": 4503, "s": 4481, "text": "Fine-tuning the model" }, { "code": null, "e": 4743, "s": 4503, "text": "Now, let’s focus on the model. We will use PyTorch for training the model(TensorFlow could also be used). First, we will configure our optimizer (Adam) and then we will train our model in batch so that our machine( CPU, GPU) doesn’t crash." }, { "code": null, "e": 5267, "s": 4743, "text": "optimizer = AdamW(model.parameters(), lr=1e-5)n_epochs = 1 batch_size = 32 for epoch in range(n_epochs): permutation = torch.randperm(Xtrain_id.size()[0]) for i in range(0,Xtrain_id.size()[0], batch_size): optimizer.zero_grad() indices = permutation[i:i+batch_size] batch_x, batch_y,batch_am = Xtrain_id[indices], labels[indices], Xtrain_am[indices] outputs = model(batch_x, attention_mask=batch_am, labels=batch_y) loss = outputs[0] loss.backward() optimizer.step()" }, { "code": null, "e": 5408, "s": 5267, "text": "Here outputs give us a tuple containing cross-entropy loss and final activation of the model. For example, here is the output of two tensors" }, { "code": null, "e": 5519, "s": 5408, "text": "We can use these activations to classify the disaster tweets with the help of the softmax activation function." }, { "code": null, "e": 5684, "s": 5519, "text": "Now let’s test the model with the help of remaining data in the training set. First, we have to put the model in the test mode and then take outputs from the model." }, { "code": null, "e": 6075, "s": 5684, "text": "model.eval() #model in testing modebatch_size = 32permutation = torch.randperm(Xtest_id.size()[0])for i in range(0,Xtest_id.size()[0], batch_size): indices = permutation[i:i+batch_size] batch_x, batch_y, batch_am = Xtest_id[indices], labels[indices], Xtest_am[indices] outputs = model(batch_x, attention_mask=batch_am, labels=batch_y) loss = outputs[0] print('Loss:' ,loss)" }, { "code": null, "e": 6203, "s": 6075, "text": "You can also get an accuracy metric by comparing output with the label and calculate (correct prediction)/(total tweets) * 100." }, { "code": null, "e": 6273, "s": 6203, "text": "Now, let’s predict our actual test data whose output we have to find." }, { "code": null, "e": 6893, "s": 6273, "text": "import torch.nn.functional as F #for softmax function batch_size = 32prediction = np.empty((0,2)) #empty numpy for appending our outputids = torch.tensor(range(original_test_id.size()[0]))for i in range(0,original_test_id.size()[0], batch_size): indices = ids[i:i+batch_size] batch_x1, batch_am1 = original_test_id[indices], original_test_am[indices] pred = model(batch_x1, batch_am1) #Here only activation is given as output pt_predictions = F.softmax(pred[0], dim=-1) #applying softmax activation function prediction = np.append(prediction, pt_predictions.detach().numpy(), axis=0) #appending the prediction" }, { "code": null, "e": 7109, "s": 6893, "text": "As we can see prediction has two columns, prediction[:,0] gives the probability of having label 0 and prediction[:,1] gives the probability of having label 1. We can use the argmax function to find the proper label." }, { "code": null, "e": 7145, "s": 7109, "text": "sub = np.argmax(prediction, axis=1)" }, { "code": null, "e": 7223, "s": 7145, "text": "Then by arranging these labels with the proper id we can get our predictions." }, { "code": null, "e": 7287, "s": 7223, "text": "submission = pd.DataFrame({'id': test.id.values, 'target':sub})" }, { "code": null, "e": 7510, "s": 7287, "text": "Using this model I got score 0.83695 and placed in the top 12% without even cleaning or processing the data. So we can see how powerful this framework is how it can be used for various purposes. You can also see code here." } ]
Sum of squares of binomial coefficients in C++
The binomial coefficient is a quotation found in a binary theorem which can be arranged in a form of pascal triangle it is a combination of numbers which is equal to nCr where r is selected from a set of n items which shows the following formula nCr=n! / r!(n-r)! or nCr=n(n-1)(n-2).....(n-r+1) / r! The sum of the square of Binomial Coefficient i.e (nC0)2 + (nC1)2 + (nC2)2 + (nC3)2 + ......... + (nCn-2)2 + (nCn-1)2 + (nCn)2 Input :n=5 Output:252 In this program first we have to find the binomial coefficient of r which is selected from n set then we have to square each coefficient and sum them we can derive a formula from the above equation or use of factorial function of each digit to get a sum so we will fall or factorial function in which we will pass and r for a given equation and then add it then we get the solution Live Demo #include <iostream> using namespace std; int fact(int n){ int fact = 1, i; for (i = 2; i <= n; i++){ fact *= i; } return fact; } int main(){ int n=5; int sum = 0; int temp=0; for (int r = 0; r <= n; r++){ temp = fact(n)/(fact(r)*fact(n-r)); sum +=(temp*temp); } cout<<sum; return 0; } 252
[ { "code": null, "e": 1308, "s": 1062, "text": "The binomial coefficient is a quotation found in a binary theorem which can be arranged in a form of pascal triangle it is a combination of numbers which is equal to nCr where r is selected from a set of n items which shows the following formula" }, { "code": null, "e": 1362, "s": 1308, "text": "nCr=n! / r!(n-r)!\nor\nnCr=n(n-1)(n-2).....(n-r+1) / r!" }, { "code": null, "e": 1489, "s": 1362, "text": "The sum of the square of Binomial Coefficient i.e\n(nC0)2 + (nC1)2 + (nC2)2 + (nC3)2 + ......... + (nCn-2)2 + (nCn-1)2 + (nCn)2" }, { "code": null, "e": 1511, "s": 1489, "text": "Input :n=5\nOutput:252" }, { "code": null, "e": 1893, "s": 1511, "text": "In this program first we have to find the binomial coefficient of r which is selected from n set then we have to square each coefficient and sum them we can derive a formula from the above equation or use of factorial function of each digit to get a sum so we will fall or factorial function in which we will pass and r for a given equation and then add it then we get the solution" }, { "code": null, "e": 1904, "s": 1893, "text": " Live Demo" }, { "code": null, "e": 2240, "s": 1904, "text": "#include <iostream>\nusing namespace std;\nint fact(int n){\n int fact = 1, i;\n for (i = 2; i <= n; i++){\n fact *= i;\n }\n return fact;\n}\nint main(){\n int n=5;\n int sum = 0;\n int temp=0;\n for (int r = 0; r <= n; r++){\n temp = fact(n)/(fact(r)*fact(n-r));\n sum +=(temp*temp);\n }\n cout<<sum;\n return 0;\n}" }, { "code": null, "e": 2244, "s": 2240, "text": "252" } ]
How to catch IndexError Exception in Python?
An IndexError is raised when a sequence reference is out of range. The given code is rewritten as follows to catch the exception and find its type import sys try: my_list = [3,7, 9, 4, 6] print my_list[6] except IndexError as e: print e print sys.exc_type C:/Users/TutorialsPoint1~.py list index out of range <type 'exceptions.IndexError'>
[ { "code": null, "e": 1129, "s": 1062, "text": "An IndexError is raised when a sequence reference is out of range." }, { "code": null, "e": 1209, "s": 1129, "text": "The given code is rewritten as follows to catch the exception and find its type" }, { "code": null, "e": 1318, "s": 1209, "text": "import sys\ntry:\nmy_list = [3,7, 9, 4, 6]\nprint my_list[6]\nexcept IndexError as e:\nprint e\nprint sys.exc_type" }, { "code": null, "e": 1404, "s": 1318, "text": "C:/Users/TutorialsPoint1~.py\nlist index out of range\n<type 'exceptions.IndexError'>\n\n" } ]
MongoDB query to search for string like “@email” in the field values
Search for email string using MongoDB find(). Let us create a collection with documents − > db.demo727.insertOne({UserId:"[email protected]"}); { "acknowledged" : true, "insertedId" : ObjectId("5eab375f43417811278f5898") } > db.demo727.insertOne({UserId:"[email protected]"}); { "acknowledged" : true, "insertedId" : ObjectId("5eab376043417811278f5899") } > db.demo727.insertOne({UserId:"[email protected]"}); { "acknowledged" : true, "insertedId" : ObjectId("5eab376143417811278f589a") } Display all documents from a collection with the help of find() method − > db.demo727.find(); This will produce the following output − { "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "[email protected]" } { "_id" : ObjectId("5eab376043417811278f5899"), "UserId" : "[email protected]" } { "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "[email protected]" } Following is the query to search for @email like string − > db.demo727.find({"UserId":/@email/i}); This will produce the following output − { "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "[email protected]" } { "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "[email protected]" }
[ { "code": null, "e": 1152, "s": 1062, "text": "Search for email string using MongoDB find(). Let us create a collection with documents −" }, { "code": null, "e": 1561, "s": 1152, "text": "> db.demo727.insertOne({UserId:\"[email protected]\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eab375f43417811278f5898\")\n}\n> db.demo727.insertOne({UserId:\"[email protected]\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eab376043417811278f5899\")\n}\n> db.demo727.insertOne({UserId:\"[email protected]\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eab376143417811278f589a\")\n}" }, { "code": null, "e": 1634, "s": 1561, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1655, "s": 1634, "text": "> db.demo727.find();" }, { "code": null, "e": 1696, "s": 1655, "text": "This will produce the following output −" }, { "code": null, "e": 1931, "s": 1696, "text": "{ \"_id\" : ObjectId(\"5eab375f43417811278f5898\"), \"UserId\" : \"[email protected]\" }\n{ \"_id\" : ObjectId(\"5eab376043417811278f5899\"), \"UserId\" : \"[email protected]\" }\n{ \"_id\" : ObjectId(\"5eab376143417811278f589a\"), \"UserId\" : \"[email protected]\" }" }, { "code": null, "e": 1989, "s": 1931, "text": "Following is the query to search for @email like string −" }, { "code": null, "e": 2030, "s": 1989, "text": "> db.demo727.find({\"UserId\":/@email/i});" }, { "code": null, "e": 2071, "s": 2030, "text": "This will produce the following output −" }, { "code": null, "e": 2228, "s": 2071, "text": "{ \"_id\" : ObjectId(\"5eab375f43417811278f5898\"), \"UserId\" : \"[email protected]\" }\n{ \"_id\" : ObjectId(\"5eab376143417811278f589a\"), \"UserId\" : \"[email protected]\" }" } ]
Requests - Handling Timeouts
Timeouts can be easily added to the URL you are requesting. It so happens that, you are using a third-party URL and waiting for a response. It is always a good practice to give a timeout on the URL, as we might want the URL to respond within a timespan with a response or an error. Not doing so, can cause to wait on that request indefinitely. We can give timeout to the URL by using the timeout param and value is passed in seconds as shown in the example below − import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001) print(getdata.text) raise ConnectTimeout(e, request=request) requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='jsonplaceholder.typicode.com', port=443): Max retries exceeded with url: /users (Caused by Connect TimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000000B02AD E76A0>, 'Connection to jsonplaceholder.typicode.com timed out. (connect timeout = 0.001)')) The timeout given is as follows − getdata = requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001) The execution throws connection timeout error as shown in the output. The timeout given is 0.001, which is not possible for the request to get back the response and throws an error. Now, we will increase the timeout and check. import requests getdata = requests.get('https://jsonplaceholder.typicode.com/users',timeout=1.000) print(getdata.text) E:\prequests>python makeRequest.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ] With a timeout of 1 second, we can get the response for the URL requested. Print Add Notes Bookmark this page
[ { "code": null, "e": 2532, "s": 2188, "text": "Timeouts can be easily added to the URL you are requesting. It so happens that, you are using a third-party URL and waiting for a response. It is always a good practice to give a timeout on the URL, as we might want the URL to respond within a timespan with a response or an error. Not doing so, can cause to wait on that request indefinitely." }, { "code": null, "e": 2653, "s": 2532, "text": "We can give timeout to the URL by using the timeout param and value is passed in seconds as shown in the example below −" }, { "code": null, "e": 2777, "s": 2653, "text": "import requests\ngetdata = \nrequests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)\nprint(getdata.text) " }, { "code": null, "e": 3157, "s": 2777, "text": "raise ConnectTimeout(e, request=request)\nrequests.exceptions.ConnectTimeout:\nHTTPSConnectionPool(host='jsonplaceholder.typicode.com', \nport=443): Max retries exceeded with url: /users (Caused \nby Connect\nTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at \n0x000000B02AD\nE76A0>, 'Connection to jsonplaceholder.typicode.com timed out. (connect \ntimeout = 0.001)'))\n" }, { "code": null, "e": 3191, "s": 3157, "text": "The timeout given is as follows −" }, { "code": null, "e": 3276, "s": 3191, "text": "getdata = \nrequests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)\n" }, { "code": null, "e": 3503, "s": 3276, "text": "The execution throws connection timeout error as shown in the output. The timeout given is 0.001, which is not possible for the request to get back the response and throws an error. Now, we will increase the timeout and check." }, { "code": null, "e": 3623, "s": 3503, "text": "import requests\ngetdata = \nrequests.get('https://jsonplaceholder.typicode.com/users',timeout=1.000)\nprint(getdata.text)" }, { "code": null, "e": 4277, "s": 3623, "text": "E:\\prequests>python makeRequest.py\n[\n {\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\",\n \"email\": \"[email protected]\",\n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n }\n] \n" }, { "code": null, "e": 4352, "s": 4277, "text": "With a timeout of 1 second, we can get the response for the URL requested." }, { "code": null, "e": 4359, "s": 4352, "text": " Print" }, { "code": null, "e": 4370, "s": 4359, "text": " Add Notes" } ]
Python | Raising an Exception to Another Exception - GeeksforGeeks
12 Jun, 2019 Let’s consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: int('N/A') except ValueError as e: raise RuntimeError('A parsing error occurred') from e... example() Output : Traceback (most recent call last): File "", line 3, in example ValueError: invalid literal for int() with base 10: 'N/A' This exception is the direct cause of the following exception – Traceback (most recent call last): File "", line 1, in File "", line 5, in example RuntimeError: A parsing error occurred Both exceptions are captured in the traceback. A normal except statement is used to catch such an exception. However, __cause__ attribute of the exception object can be looked to follow the exception chain as explained in the code given below. Code #2 : try: example()except RuntimeError as e: print("It didn't work:", e) if e.__cause__: print('Cause:', e.__cause__) An implicit form of chained exceptions occurs when another exception gets raised inside an except block. Code #3 : def example2(): try: int('N/A') except ValueError as e: print("Couldn't parse:", err) example2() Traceback (most recent call last): File "", line 3, in example2 ValueError: invalid literal for int() with base 10: 'N / A' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "", line 5, in example2 NameError: global name 'err' is not defined In the code below, the NameError exception is raised as the result of a programming error, not in direct response to the parsing error. For this case, the __cause__ attribute of an exception is not set. Instead, a __context__ attribute is set to the prior exception. Code #4 : To suppress chaining, use raise from None def example3(): try: int('N / A') except ValueError: raise RuntimeError('A parsing error occurred') from None... example3() Output : Traceback (most recent call last): File "", line 1, in File "", line 5, in example3 RuntimeError: A parsing error occurred Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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 sum() function in Python *args and **kwargs in Python
[ { "code": null, "e": 24368, "s": 24340, "text": "\n12 Jun, 2019" }, { "code": null, "e": 24549, "s": 24368, "text": "Let’s consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback." }, { "code": null, "e": 24686, "s": 24549, "text": "To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors." }, { "code": null, "e": 24696, "s": 24686, "text": "Code #1 :" }, { "code": "def example(): try: int('N/A') except ValueError as e: raise RuntimeError('A parsing error occurred') from e... example()", "e": 24839, "s": 24696, "text": null }, { "code": null, "e": 24848, "s": 24839, "text": "Output :" }, { "code": null, "e": 24972, "s": 24848, "text": "Traceback (most recent call last):\n File \"\", line 3, in example\nValueError: invalid literal for int() with base 10: 'N/A'\n" }, { "code": null, "e": 25036, "s": 24972, "text": "This exception is the direct cause of the following exception –" }, { "code": null, "e": 25164, "s": 25036, "text": "Traceback (most recent call last):\n File \"\", line 1, in \n File \"\", line 5, in example\nRuntimeError: A parsing error occurred\n" }, { "code": null, "e": 25408, "s": 25164, "text": "Both exceptions are captured in the traceback. A normal except statement is used to catch such an exception. However, __cause__ attribute of the exception object can be looked to follow the exception chain as explained in the code given below." }, { "code": null, "e": 25418, "s": 25408, "text": "Code #2 :" }, { "code": "try: example()except RuntimeError as e: print(\"It didn't work:\", e) if e.__cause__: print('Cause:', e.__cause__)", "e": 25547, "s": 25418, "text": null }, { "code": null, "e": 25652, "s": 25547, "text": "An implicit form of chained exceptions occurs when another exception gets raised inside an except block." }, { "code": null, "e": 25662, "s": 25652, "text": "Code #3 :" }, { "code": "def example2(): try: int('N/A') except ValueError as e: print(\"Couldn't parse:\", err) example2()", "e": 25780, "s": 25662, "text": null }, { "code": null, "e": 25909, "s": 25780, "text": "Traceback (most recent call last):\n File \"\", line 3, in example2\nValueError: invalid literal for int() with base 10: 'N / A'\n" }, { "code": null, "e": 25977, "s": 25909, "text": "During handling of the above exception, another exception occurred:" }, { "code": null, "e": 26115, "s": 25977, "text": "Traceback (most recent call last):\n File \"\", line 1, in \n File \"\", line 5, in example2\nNameError: global name 'err' is not defined\n" }, { "code": null, "e": 26382, "s": 26115, "text": "In the code below, the NameError exception is raised as the result of a programming error, not in direct response to the parsing error. For this case, the __cause__ attribute of an exception is not set. Instead, a __context__ attribute is set to the prior exception." }, { "code": null, "e": 26434, "s": 26382, "text": "Code #4 : To suppress chaining, use raise from None" }, { "code": "def example3(): try: int('N / A') except ValueError: raise RuntimeError('A parsing error occurred') from None... example3()", "e": 26579, "s": 26434, "text": null }, { "code": null, "e": 26588, "s": 26579, "text": "Output :" }, { "code": null, "e": 26721, "s": 26588, "text": "Traceback (most recent call last):\n File \"\", line 1, in \n File \"\", line 5, in example3\nRuntimeError: A parsing error occurred\n" }, { "code": null, "e": 26739, "s": 26721, "text": "Python-exceptions" }, { "code": null, "e": 26746, "s": 26739, "text": "Python" }, { "code": null, "e": 26844, "s": 26746, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26862, "s": 26844, "text": "Python Dictionary" }, { "code": null, "e": 26884, "s": 26862, "text": "Enumerate() in Python" }, { "code": null, "e": 26916, "s": 26884, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26946, "s": 26916, "text": "Iterate over a list in Python" }, { "code": null, "e": 26988, "s": 26946, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27014, "s": 26988, "text": "Python String | replace()" }, { "code": null, "e": 27051, "s": 27014, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27094, "s": 27051, "text": "Python program to convert a list to string" }, { "code": null, "e": 27119, "s": 27094, "text": "sum() function in Python" } ]
MySQL query to create user and grant permission
To create a user and grant permission, the syntax is as follows − create database yourDatabaseName DEFAULT CHARACTER SET utf8; create user `yourUserName` identified by yourPassword; GRANT SELECT ON yourDatabaseName .* TO `yourUserName`; GRANT INSERT ON yourDatabaseName .* TO `yourUserName`; GRANT UPDATE ON yourDatabaseName .* TO `yourUserName`; GRANT DELETE ON yourDatabaseName .* TO `yourUserName`; GRANT EXECUTE ON yourDatabaseName .* TO `yourUserName`; Here is the query to create user and grant permission − mysql> create database demo_app DEFAULT CHARACTER SET utf8; Query OK, 1 row affected, 1 warning (0.00 sec) mysql> create user `John_123` identified by '123456'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT SELECT ON demo.* TO `John_123`; Query OK, 0 rows affected (0.00 sec) mysql> GRANT INSERT ON demo.* TO `John_123`; Query OK, 0 rows affected (0.00 sec) mysql> GRANT UPDATE ON demo.* TO `John_123`; Query OK, 0 rows affected (0.00 sec) mysql> GRANT DELETE ON demo.* TO `John_123`; Query OK, 0 rows affected (0.00 sec) mysql> GRANT EXECUTE ON demo.* TO `John_123`; Query OK, 0 rows affected (0.00 sec) Let us display all the grants of the above user: mysql> show grants for `John_123`; This will produce the following output − +-----------------------------------------------------------------------------+ | Grants for John_123@% | +-----------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO `John_123`@`%` | | GRANT SELECT, INSERT, UPDATE, DELETE, EXECUTE ON `demo`.* TO `John_123`@`%` | +-----------------------------------------------------------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1128, "s": 1062, "text": "To create a user and grant permission, the syntax is as follows −" }, { "code": null, "e": 1521, "s": 1128, "text": "create database yourDatabaseName DEFAULT CHARACTER SET utf8;\ncreate user `yourUserName` identified by yourPassword;\nGRANT SELECT ON yourDatabaseName .* TO `yourUserName`;\nGRANT INSERT ON yourDatabaseName .* TO `yourUserName`;\nGRANT UPDATE ON yourDatabaseName .* TO `yourUserName`;\nGRANT DELETE ON yourDatabaseName .* TO `yourUserName`;\nGRANT EXECUTE ON yourDatabaseName .* TO `yourUserName`;" }, { "code": null, "e": 1577, "s": 1521, "text": "Here is the query to create user and grant permission −" }, { "code": null, "e": 2187, "s": 1577, "text": "mysql> create database demo_app DEFAULT CHARACTER SET utf8;\nQuery OK, 1 row affected, 1 warning (0.00 sec)\nmysql> create user `John_123` identified by '123456';\nQuery OK, 0 rows affected (0.00 sec)\nmysql> GRANT SELECT ON demo.* TO `John_123`;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> GRANT INSERT ON demo.* TO `John_123`;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> GRANT UPDATE ON demo.* TO `John_123`;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> GRANT DELETE ON demo.* TO `John_123`;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> GRANT EXECUTE ON demo.* TO `John_123`;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2236, "s": 2187, "text": "Let us display all the grants of the above user:" }, { "code": null, "e": 2271, "s": 2236, "text": "mysql> show grants for `John_123`;" }, { "code": null, "e": 2312, "s": 2271, "text": "This will produce the following output −" }, { "code": null, "e": 2817, "s": 2312, "text": "+-----------------------------------------------------------------------------+\n| Grants for John_123@% |\n+-----------------------------------------------------------------------------+\n| GRANT USAGE ON *.* TO `John_123`@`%` |\n| GRANT SELECT, INSERT, UPDATE, DELETE, EXECUTE ON `demo`.* TO `John_123`@`%` |\n+-----------------------------------------------------------------------------+\n2 rows in set (0.00 sec)" } ]
How to work with JSON in Python for Data Analysis | Towards Data Science
In this blog post, we are going to learn about JSON. We are going to learn what JSON is, why it exists, why people use it and finally how to utilise the power of python to help us process it. As a data scientist, programmer or simply an avid learner of technology, it is important that you understand what JSON is and how to use it. I am certain that you will find numerous applications for it once you understand it. JSON stands for JavaScript Object notation and it is essentially a way to represent data. JSON follows a format that humans can naturally understand, and its true power comes from its ability to capture complex data relationships. You can see this in the following example: { "usersName": "Costas", "website": { "host": "www.medium.com", "account": "costasandreou", "blogpost": [ { "type": "title", "description": { "main" : "Working with JSON in Python", "sub" : "the info you need" } } ] }} Notice how JSON is structured in key-value pairs, while also holding array objects (notice that “blogpost” has several types underneath it). This is very important to note if you’re coming from a flat data structure background (think Excel or Pandas dataFrames). JSON was created at the beginning of the millennial to save us from Flash and Java applets. If you happen to not remember those in-browser plugins, consider yourself extremely lucky, as they were the stuff that nightmares are made of! But I digress. JSON was built to provide a protocol for stateless real-time server to browser communication1. If you are already familiar with XML, you can think of JSON as a lightweight, easier to use, faster alternative. It is believed that the first major company to begin offering services and therefore popularising the adoption of JSON, was Yahoo in 20051. It is now believed that JSON is the most used data format. The top 3 reasons people use JSON are: Very easy to read, write and manipulateIt’s very fast to transfer over the networkSupported by all major browsers, backend tech stacks Very easy to read, write and manipulate It’s very fast to transfer over the network Supported by all major browsers, backend tech stacks The very first thing you’d want to do when you have to work with JSON is to read it into your Python application. The json library in Python expects JSON to come through as string. Assuming your data JSON data is already a string: obj = '{ "usersName": "Costas", "website": { "host": "www.medium.com", "account": "costasandreou", "blogpost": [ { "type": "title", "description": { "main" : "Working with JSON in Python", "sub" : "the info you need" } } ] } }'import jsonjson_obj = json.loads(obj)print('obj: ',type(obj))print('obj.usersName: ', json_obj['usersName']) which returns: obj: <class 'str'>obj.usersName: Costas If on the other hand, if you hold the JSON in a Python Object (like a dictionary), the json library allows you to convert it back to string for further processing. obj1 = { "usersName": "Costas", "website": { "host": "www.medium.com", "account": "costasandreou", "blogpost": [ { "type": "title", "description": { "main" : "Working with JSON in Python", "sub" : "the info you need" } } ] } }print('obj1: ',type(obj1))json_obj1str = json.dumps(obj1)print('json_obj1str: ', type(json_obj1str))json_obj1 = json.loads(json_obj1str)print('obj1.usersName: ', json_obj1['usersName']) which returns: obj1: <class 'dict'>json_obj1str: <class 'str'>obj1.usersName: Costas Now that we have seen how to load our JSON data into our Python application, let us look at the options we have to work with JSON. Extracting information from the JSON is as simple as defining the path we are after and provide the name of the key-value pair. Let’s look at a few examples. >>> print(json_obj['usersName'])Costas>>> print(json_obj['website']){'host': 'www.medium.com', 'account': 'costasandreou', 'blogpost': [{'type': 'title', 'description': {'main': 'Working with JSON in Python', 'sub': 'the info you need'}}]}>>> print(json_obj['website']['host'])www.medium.com>>> print(json_obj['website']['blogpost'])[{'type': 'title', 'description': {'main': 'Working with JSON in Python', 'sub': 'the info you need'}}]>>> print(json_obj['website']['blogpost'][0]['description']['sub'])the info you need Once we can extract the data as above, we can easily store them in lists or databases for further processing. If you are already comfortable in Pandas and you’d like to work with flat data, there is a quick way to get your data into data frames. First up, you can take the first level of your data and add it to a dataFrame. df = pd.read_json(obj) As you can see, read_json takes in a string data type and only allows us to see top-level information. In other words, it doesn’t flatten any of the structures. We need a way to navigate through the lower levels of the data. We can flatten the data by a further level by using the json_normalise pandas method. obj = json.loads(obj)df1 = pd.json_normalize(obj) There are certain cases where you simply want to flatten out the data. It certainly can make data analysis quicker at times and can allow for the visual inspection of a large number of records (think Excel type data filtering). You can do that using a third-party library. First up, install the library: pip install json-flatten Then, run the following commands: >>> import json>>> obj = json.loads(obj)>>> import json_flatten>>> print(json_flatten.flatten(obj)){'usersName': 'Costas', 'website.host': 'www.medium.com', 'website.account': 'costasandreou', 'website.blogpost.0.type': 'title', 'website.blogpost.0.description.main': 'Working with JSON in Python', 'website.blogpost.0.description.sub': 'the info you need'} All the items we have explored so far focused on processing a single JSON record. However, in the real world, you are likely required to process many JSON documents and be required to aggregate across records. You can consider any of the following methods for enabling your analysis: MongoDB to store the data and then run aggregations on top Flatten the data and use pandas for operations Flatten the data and export to Excel for further operations Choose the attributes you are after and load them in a SQL DB for further analysis There you have it. In exactly 5 minutes you know everything you need to know to get you started working with JSON. I encourage you to spend some time and get intimately familiar with it. It is widely used and it is certainly a must-have on your CV! { "References" : [ { "1" : "https://en.wikipedia.org/wiki/JSON#History" }, { "2" : "guru99.com/json-vs-xml-difference.html" }, { "3" : "https://pypi.org/project/json-flatten/#description" }, ]}
[ { "code": null, "e": 239, "s": 47, "text": "In this blog post, we are going to learn about JSON. We are going to learn what JSON is, why it exists, why people use it and finally how to utilise the power of python to help us process it." }, { "code": null, "e": 465, "s": 239, "text": "As a data scientist, programmer or simply an avid learner of technology, it is important that you understand what JSON is and how to use it. I am certain that you will find numerous applications for it once you understand it." }, { "code": null, "e": 696, "s": 465, "text": "JSON stands for JavaScript Object notation and it is essentially a way to represent data. JSON follows a format that humans can naturally understand, and its true power comes from its ability to capture complex data relationships." }, { "code": null, "e": 739, "s": 696, "text": "You can see this in the following example:" }, { "code": null, "e": 1048, "s": 739, "text": "{ \"usersName\": \"Costas\", \"website\": { \"host\": \"www.medium.com\", \"account\": \"costasandreou\", \"blogpost\": [ { \"type\": \"title\", \"description\": { \"main\" : \"Working with JSON in Python\", \"sub\" : \"the info you need\" } } ] }}" }, { "code": null, "e": 1311, "s": 1048, "text": "Notice how JSON is structured in key-value pairs, while also holding array objects (notice that “blogpost” has several types underneath it). This is very important to note if you’re coming from a flat data structure background (think Excel or Pandas dataFrames)." }, { "code": null, "e": 1656, "s": 1311, "text": "JSON was created at the beginning of the millennial to save us from Flash and Java applets. If you happen to not remember those in-browser plugins, consider yourself extremely lucky, as they were the stuff that nightmares are made of! But I digress. JSON was built to provide a protocol for stateless real-time server to browser communication1." }, { "code": null, "e": 1769, "s": 1656, "text": "If you are already familiar with XML, you can think of JSON as a lightweight, easier to use, faster alternative." }, { "code": null, "e": 1968, "s": 1769, "text": "It is believed that the first major company to begin offering services and therefore popularising the adoption of JSON, was Yahoo in 20051. It is now believed that JSON is the most used data format." }, { "code": null, "e": 2007, "s": 1968, "text": "The top 3 reasons people use JSON are:" }, { "code": null, "e": 2142, "s": 2007, "text": "Very easy to read, write and manipulateIt’s very fast to transfer over the networkSupported by all major browsers, backend tech stacks" }, { "code": null, "e": 2182, "s": 2142, "text": "Very easy to read, write and manipulate" }, { "code": null, "e": 2226, "s": 2182, "text": "It’s very fast to transfer over the network" }, { "code": null, "e": 2279, "s": 2226, "text": "Supported by all major browsers, backend tech stacks" }, { "code": null, "e": 2460, "s": 2279, "text": "The very first thing you’d want to do when you have to work with JSON is to read it into your Python application. The json library in Python expects JSON to come through as string." }, { "code": null, "e": 2510, "s": 2460, "text": "Assuming your data JSON data is already a string:" }, { "code": null, "e": 2847, "s": 2510, "text": "obj = '{ \"usersName\": \"Costas\", \"website\": { \"host\": \"www.medium.com\", \"account\": \"costasandreou\", \"blogpost\": [ { \"type\": \"title\", \"description\": { \"main\" : \"Working with JSON in Python\", \"sub\" : \"the info you need\" } } ] } }'import jsonjson_obj = json.loads(obj)print('obj: ',type(obj))print('obj.usersName: ', json_obj['usersName'])" }, { "code": null, "e": 2862, "s": 2847, "text": "which returns:" }, { "code": null, "e": 2904, "s": 2862, "text": "obj: <class 'str'>obj.usersName: Costas" }, { "code": null, "e": 3068, "s": 2904, "text": "If on the other hand, if you hold the JSON in a Python Object (like a dictionary), the json library allows you to convert it back to string for further processing." }, { "code": null, "e": 3481, "s": 3068, "text": "obj1 = { \"usersName\": \"Costas\", \"website\": { \"host\": \"www.medium.com\", \"account\": \"costasandreou\", \"blogpost\": [ { \"type\": \"title\", \"description\": { \"main\" : \"Working with JSON in Python\", \"sub\" : \"the info you need\" } } ] } }print('obj1: ',type(obj1))json_obj1str = json.dumps(obj1)print('json_obj1str: ', type(json_obj1str))json_obj1 = json.loads(json_obj1str)print('obj1.usersName: ', json_obj1['usersName'])" }, { "code": null, "e": 3496, "s": 3481, "text": "which returns:" }, { "code": null, "e": 3569, "s": 3496, "text": "obj1: <class 'dict'>json_obj1str: <class 'str'>obj1.usersName: Costas" }, { "code": null, "e": 3700, "s": 3569, "text": "Now that we have seen how to load our JSON data into our Python application, let us look at the options we have to work with JSON." }, { "code": null, "e": 3858, "s": 3700, "text": "Extracting information from the JSON is as simple as defining the path we are after and provide the name of the key-value pair. Let’s look at a few examples." }, { "code": null, "e": 4379, "s": 3858, "text": ">>> print(json_obj['usersName'])Costas>>> print(json_obj['website']){'host': 'www.medium.com', 'account': 'costasandreou', 'blogpost': [{'type': 'title', 'description': {'main': 'Working with JSON in Python', 'sub': 'the info you need'}}]}>>> print(json_obj['website']['host'])www.medium.com>>> print(json_obj['website']['blogpost'])[{'type': 'title', 'description': {'main': 'Working with JSON in Python', 'sub': 'the info you need'}}]>>> print(json_obj['website']['blogpost'][0]['description']['sub'])the info you need" }, { "code": null, "e": 4489, "s": 4379, "text": "Once we can extract the data as above, we can easily store them in lists or databases for further processing." }, { "code": null, "e": 4704, "s": 4489, "text": "If you are already comfortable in Pandas and you’d like to work with flat data, there is a quick way to get your data into data frames. First up, you can take the first level of your data and add it to a dataFrame." }, { "code": null, "e": 4727, "s": 4704, "text": "df = pd.read_json(obj)" }, { "code": null, "e": 4952, "s": 4727, "text": "As you can see, read_json takes in a string data type and only allows us to see top-level information. In other words, it doesn’t flatten any of the structures. We need a way to navigate through the lower levels of the data." }, { "code": null, "e": 5038, "s": 4952, "text": "We can flatten the data by a further level by using the json_normalise pandas method." }, { "code": null, "e": 5088, "s": 5038, "text": "obj = json.loads(obj)df1 = pd.json_normalize(obj)" }, { "code": null, "e": 5316, "s": 5088, "text": "There are certain cases where you simply want to flatten out the data. It certainly can make data analysis quicker at times and can allow for the visual inspection of a large number of records (think Excel type data filtering)." }, { "code": null, "e": 5392, "s": 5316, "text": "You can do that using a third-party library. First up, install the library:" }, { "code": null, "e": 5417, "s": 5392, "text": "pip install json-flatten" }, { "code": null, "e": 5451, "s": 5417, "text": "Then, run the following commands:" }, { "code": null, "e": 5809, "s": 5451, "text": ">>> import json>>> obj = json.loads(obj)>>> import json_flatten>>> print(json_flatten.flatten(obj)){'usersName': 'Costas', 'website.host': 'www.medium.com', 'website.account': 'costasandreou', 'website.blogpost.0.type': 'title', 'website.blogpost.0.description.main': 'Working with JSON in Python', 'website.blogpost.0.description.sub': 'the info you need'}" }, { "code": null, "e": 6019, "s": 5809, "text": "All the items we have explored so far focused on processing a single JSON record. However, in the real world, you are likely required to process many JSON documents and be required to aggregate across records." }, { "code": null, "e": 6093, "s": 6019, "text": "You can consider any of the following methods for enabling your analysis:" }, { "code": null, "e": 6152, "s": 6093, "text": "MongoDB to store the data and then run aggregations on top" }, { "code": null, "e": 6199, "s": 6152, "text": "Flatten the data and use pandas for operations" }, { "code": null, "e": 6259, "s": 6199, "text": "Flatten the data and export to Excel for further operations" }, { "code": null, "e": 6342, "s": 6259, "text": "Choose the attributes you are after and load them in a SQL DB for further analysis" }, { "code": null, "e": 6591, "s": 6342, "text": "There you have it. In exactly 5 minutes you know everything you need to know to get you started working with JSON. I encourage you to spend some time and get intimately familiar with it. It is widely used and it is certainly a must-have on your CV!" } ]
Applying Custom Functions to Groups of Data in Pandas | by Casey Whorton | Towards Data Science
Here, I will share with you two different methods for applying custom functions to groups of data in pandas. There are many out-of-the-box aggregate and filtering functions available for us to use already, but those don’t always do everything we want. Sometimes, when I want to know “what was the second most recent observation per month” or “what is the difference between two weighted averages by product type”, I know I need to define a custom function to do the job. Usually, I try not to use this toy dataset because it has been done so many times, but it has a nice categorical column from which to create groups of data, so I’m going with it. For each classification, there are 4 features with numerical data in each column that measure aspects of a flowers petals and sepals. Typically, a first round analysis might include examining descriptive statistics of your dataset. If you have one table that you are looking at in particular, something like the “describe” method can reveal some key information about your columns such as the number of non-NULL values and the distribution of numerical features. A slightly deeper question to ask is “what are some of these descriptive statistics per group?”. Grouping the data together based on the similar values in a single column and taking the maximum value over all rows in each group looks like this: The maximum sepal length (in centimeters) is 5.8 for the “setosa” group. This is great but if all we cared about were descriptive statistics at group levels then we could probably program a computer to crank through all the possibilities and return some intersesting findings. What I find comes up more often is the need to apply a custom function to each group in a dataframe. Next, I’ll create a custom function that can’t be easily duplicated with a groupby aggregate function. This could be just about anything. Here, I am interested in the ratio of the range of sepal lengths to petal lengths. Why? Maybe I’m interested in seeing which type of flower has greater sepal variation to petal variation. Who knows. The point is that this is a specific question you want answered, and normally you might do a groupby with the max aggregate, then the mins, save those results, and get the ratios. It’s possible, but why not execute a custom function over the groups? We’re not limited to aggregates, you could find the 2nd value in a dataframe’s column if you wanted. Notice that the function explicitly names columns from the dataframe using the bracket notation. You can also create custom functions that apply to all columns in the dataframe and use it on groups in the same manner we’ll see in a moment. Notice that every element in the groupby is a tuple, with the first element containing whatever you grouped the data by (this can be more than one column, in which case another tuple) and the grouped data (a pandas dataframe). This means that whatever function you use on the groupby elements needs to take both the groups and dataframes. Simply use the apply method to each dataframe in the groupby object. This is the most straightforward way and the easiest to understand. Notice that the function takes a dataframe as its only argument, so any code within the custom function needs to work on a pandas dataframe. data.groupby([‘target’]).apply(find_ratio) It is also possible to accomplish this with a lambda function, executed over each dataframe: data.groupby([‘target’]).apply(lambda x: find_ratio(x)) Save the groupby element and execute the function for every element in the groupby object. This second option takes a little more work, but could be what you are looking for in terms of customization. While we applied our custom function to each dataframe directly before, we will need to rewrite the function slightly to accept the groupby element as the argument. But first, create a groupby object for the column(s) you want to groupby and assign it a variable name. Next, rewrite the function to work on each groupby in the groupby element. Note: a groupby object is iterable (meaning python can loop through it) and contains both the levels of the grouping and the resulting dataframe. grouping = data.groupby([‘target’]) Execute the function over the groupby element in a loop or using a list comprehension. I’m choosing to update a dictionary in the first example and to append to a list in the second example. Each method has its advantages: These are two ways to apply custom function to groups of data in pandas. Please, check out the full notebook here.
[ { "code": null, "e": 642, "s": 171, "text": "Here, I will share with you two different methods for applying custom functions to groups of data in pandas. There are many out-of-the-box aggregate and filtering functions available for us to use already, but those don’t always do everything we want. Sometimes, when I want to know “what was the second most recent observation per month” or “what is the difference between two weighted averages by product type”, I know I need to define a custom function to do the job." }, { "code": null, "e": 955, "s": 642, "text": "Usually, I try not to use this toy dataset because it has been done so many times, but it has a nice categorical column from which to create groups of data, so I’m going with it. For each classification, there are 4 features with numerical data in each column that measure aspects of a flowers petals and sepals." }, { "code": null, "e": 1529, "s": 955, "text": "Typically, a first round analysis might include examining descriptive statistics of your dataset. If you have one table that you are looking at in particular, something like the “describe” method can reveal some key information about your columns such as the number of non-NULL values and the distribution of numerical features. A slightly deeper question to ask is “what are some of these descriptive statistics per group?”. Grouping the data together based on the similar values in a single column and taking the maximum value over all rows in each group looks like this:" }, { "code": null, "e": 2010, "s": 1529, "text": "The maximum sepal length (in centimeters) is 5.8 for the “setosa” group. This is great but if all we cared about were descriptive statistics at group levels then we could probably program a computer to crank through all the possibilities and return some intersesting findings. What I find comes up more often is the need to apply a custom function to each group in a dataframe. Next, I’ll create a custom function that can’t be easily duplicated with a groupby aggregate function." }, { "code": null, "e": 2595, "s": 2010, "text": "This could be just about anything. Here, I am interested in the ratio of the range of sepal lengths to petal lengths. Why? Maybe I’m interested in seeing which type of flower has greater sepal variation to petal variation. Who knows. The point is that this is a specific question you want answered, and normally you might do a groupby with the max aggregate, then the mins, save those results, and get the ratios. It’s possible, but why not execute a custom function over the groups? We’re not limited to aggregates, you could find the 2nd value in a dataframe’s column if you wanted." }, { "code": null, "e": 2835, "s": 2595, "text": "Notice that the function explicitly names columns from the dataframe using the bracket notation. You can also create custom functions that apply to all columns in the dataframe and use it on groups in the same manner we’ll see in a moment." }, { "code": null, "e": 3174, "s": 2835, "text": "Notice that every element in the groupby is a tuple, with the first element containing whatever you grouped the data by (this can be more than one column, in which case another tuple) and the grouped data (a pandas dataframe). This means that whatever function you use on the groupby elements needs to take both the groups and dataframes." }, { "code": null, "e": 3452, "s": 3174, "text": "Simply use the apply method to each dataframe in the groupby object. This is the most straightforward way and the easiest to understand. Notice that the function takes a dataframe as its only argument, so any code within the custom function needs to work on a pandas dataframe." }, { "code": null, "e": 3495, "s": 3452, "text": "data.groupby([‘target’]).apply(find_ratio)" }, { "code": null, "e": 3588, "s": 3495, "text": "It is also possible to accomplish this with a lambda function, executed over each dataframe:" }, { "code": null, "e": 3644, "s": 3588, "text": "data.groupby([‘target’]).apply(lambda x: find_ratio(x))" }, { "code": null, "e": 4335, "s": 3644, "text": "Save the groupby element and execute the function for every element in the groupby object. This second option takes a little more work, but could be what you are looking for in terms of customization. While we applied our custom function to each dataframe directly before, we will need to rewrite the function slightly to accept the groupby element as the argument. But first, create a groupby object for the column(s) you want to groupby and assign it a variable name. Next, rewrite the function to work on each groupby in the groupby element. Note: a groupby object is iterable (meaning python can loop through it) and contains both the levels of the grouping and the resulting dataframe." }, { "code": null, "e": 4371, "s": 4335, "text": "grouping = data.groupby([‘target’])" }, { "code": null, "e": 4594, "s": 4371, "text": "Execute the function over the groupby element in a loop or using a list comprehension. I’m choosing to update a dictionary in the first example and to append to a list in the second example. Each method has its advantages:" } ]
Difference between Cost Performance Index (CPI) and Schedule Performance Index (SPI) - GeeksforGeeks
16 May, 2019 Cost Performance Index (CPI):Cost Performance Index (CPI) is the measure of the cost efficiency of project. It is expressed as a ratio of earned value to actual cost. Schedule Performance Index (SPI):Schedule Performance Index (SPI) is the measure of schedule efficiency of the project. It is expressed as the ratio of earned value to planned value. Example:A project is going to be completed in 6 months and the budget for the project is 50, 000 dollar. After the 3 months it is found that only 40% of the total work has been done to date and 30, 000 dollar has been spent. Then the Cost Performance Index (CPI) and the Schedule Performance Index (SPI) is calculated as below: Actual Cost, = 30, 000 dollar Planned Value, = 50% of 50, 000 dollar = 25, 000 dollar Earned Value, = 40% of 50, 000 dollar = 20, 000 dollar Cost Performance Index, = Earned Value / Actual Cost = 20, 000 / 30, 000 = 0.67 Schedule Performance Index (SPI), = Earned Value / Planned Value = 20, 000 / 25, 000 = 0.8 Conclusion: It can be concluded that the project is over budget and behind schedule. Difference between Cost Performance Index (CPI) and Schedule Performance Index (SPI): CPI = Earned Value / Actual Cost SPI = Earned Value / Planned Value Difference Between Software Engineering 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 Process and Thread Stack vs Heap Memory Allocation Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Types of Software Testing Software Engineering | COCOMO Model Functional vs Non Functional Requirements Software Engineering | Spiral Model Software Engineering | Coupling and Cohesion
[ { "code": null, "e": 24798, "s": 24770, "text": "\n16 May, 2019" }, { "code": null, "e": 24965, "s": 24798, "text": "Cost Performance Index (CPI):Cost Performance Index (CPI) is the measure of the cost efficiency of project. It is expressed as a ratio of earned value to actual cost." }, { "code": null, "e": 25148, "s": 24965, "text": "Schedule Performance Index (SPI):Schedule Performance Index (SPI) is the measure of schedule efficiency of the project. It is expressed as the ratio of earned value to planned value." }, { "code": null, "e": 25476, "s": 25148, "text": "Example:A project is going to be completed in 6 months and the budget for the project is 50, 000 dollar. After the 3 months it is found that only 40% of the total work has been done to date and 30, 000 dollar has been spent. Then the Cost Performance Index (CPI) and the Schedule Performance Index (SPI) is calculated as below:" }, { "code": null, "e": 25804, "s": 25476, "text": "Actual Cost, \n= 30, 000 dollar\n\nPlanned Value, \n= 50% of 50, 000 dollar \n= 25, 000 dollar\n\nEarned Value, \n= 40% of 50, 000 dollar \n= 20, 000 dollar\n\nCost Performance Index, \n= Earned Value / Actual Cost \n= 20, 000 / 30, 000 \n= 0.67\n\nSchedule Performance Index (SPI), \n= Earned Value / Planned Value \n= 20, 000 / 25, 000 \n= 0.8 " }, { "code": null, "e": 25889, "s": 25804, "text": "Conclusion: It can be concluded that the project is over budget and behind schedule." }, { "code": null, "e": 25975, "s": 25889, "text": "Difference between Cost Performance Index (CPI) and Schedule Performance Index (SPI):" }, { "code": null, "e": 26008, "s": 25975, "text": "CPI = Earned Value / Actual Cost" }, { "code": null, "e": 26043, "s": 26008, "text": "SPI = Earned Value / Planned Value" }, { "code": null, "e": 26062, "s": 26043, "text": "Difference Between" }, { "code": null, "e": 26083, "s": 26062, "text": "Software Engineering" }, { "code": null, "e": 26181, "s": 26083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26242, "s": 26181, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26280, "s": 26242, "text": "Difference between Process and Thread" }, { "code": null, "e": 26312, "s": 26280, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 26380, "s": 26312, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 26417, "s": 26380, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 26443, "s": 26417, "text": "Types of Software Testing" }, { "code": null, "e": 26479, "s": 26443, "text": "Software Engineering | COCOMO Model" }, { "code": null, "e": 26521, "s": 26479, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 26557, "s": 26521, "text": "Software Engineering | Spiral Model" } ]
How to check if a string starts with a substring using regex in Python? - GeeksforGeeks
29 Dec, 2020 Prerequisite: Regular Expression in Python Given a string str, the task is to check if a string starts with a given substring or not using regular expression. Examples: Input: String: "geeks for geeks makes learning fun" Substring: "geeks" Output: True Input: String: "geeks for geeks makes learning fun" Substring: "makes" Output: False Approach 1:Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “^”. This metacharacter checks for a given string starts with substring provided or not. Below is the implementation of the above approach: Python3 # import libraryimport re # define a function def find(string, sample) : # check substring present # in a string or not if (sample in string): y = "^" + sample # check if string starts # with the substring x = re.search(y, string) if x : print("string starts with the given substring") else : print("string doesn't start with the given substring") else : print("entered string isn't a substring") # Driver codestring = "geeks for geeks makes learning fun" sample = "geeks" # function callfind(string, sample) sample = "makes" # function callfind(string, sample) Output: string starts with the given substring string doesn't start with the given substring Approach 2:Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “\A”. This metacharacter checks for a given string starts with substring provided or not. Below is the implementation of the above approach: Python3 # import libraryimport re # define a function def find(string, sample) : # check substring present # in a string or not if (sample in string): y = "\A" + sample # check if string starts # with the substring x = re.search(y, string) if x : print("string starts with the given substring") else : print("string doesn't start with the given substring") else : print("entered string isn't a substring") # Driver codestring = "geeks for geeks makes learning fun" sample = "geeks" # function callfind(string, sample) sample = "makes" # function callfind(string, sample) Output: string starts with the given substring string doesn't start with the given substring Python Regex-programs python-regex 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() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24888, "s": 24860, "text": "\n29 Dec, 2020" }, { "code": null, "e": 24931, "s": 24888, "text": "Prerequisite: Regular Expression in Python" }, { "code": null, "e": 25047, "s": 24931, "text": "Given a string str, the task is to check if a string starts with a given substring or not using regular expression." }, { "code": null, "e": 25057, "s": 25047, "text": "Examples:" }, { "code": null, "e": 25245, "s": 25057, "text": "Input: String: \"geeks for geeks makes learning fun\" \n Substring: \"geeks\" \nOutput: True \nInput: String: \"geeks for geeks makes learning fun\" \n Substring: \"makes\" \nOutput: False" }, { "code": null, "e": 25488, "s": 25245, "text": "Approach 1:Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “^”. This metacharacter checks for a given string starts with substring provided or not. " }, { "code": null, "e": 25539, "s": 25488, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25547, "s": 25539, "text": "Python3" }, { "code": "# import libraryimport re # define a function def find(string, sample) : # check substring present # in a string or not if (sample in string): y = \"^\" + sample # check if string starts # with the substring x = re.search(y, string) if x : print(\"string starts with the given substring\") else : print(\"string doesn't start with the given substring\") else : print(\"entered string isn't a substring\") # Driver codestring = \"geeks for geeks makes learning fun\" sample = \"geeks\" # function callfind(string, sample) sample = \"makes\" # function callfind(string, sample)", "e": 26190, "s": 25547, "text": null }, { "code": null, "e": 26198, "s": 26190, "text": "Output:" }, { "code": null, "e": 26283, "s": 26198, "text": "string starts with the given substring\nstring doesn't start with the given substring" }, { "code": null, "e": 26526, "s": 26283, "text": "Approach 2:Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “\\A”. This metacharacter checks for a given string starts with substring provided or not." }, { "code": null, "e": 26578, "s": 26526, "text": " Below is the implementation of the above approach:" }, { "code": null, "e": 26586, "s": 26578, "text": "Python3" }, { "code": "# import libraryimport re # define a function def find(string, sample) : # check substring present # in a string or not if (sample in string): y = \"\\A\" + sample # check if string starts # with the substring x = re.search(y, string) if x : print(\"string starts with the given substring\") else : print(\"string doesn't start with the given substring\") else : print(\"entered string isn't a substring\") # Driver codestring = \"geeks for geeks makes learning fun\" sample = \"geeks\" # function callfind(string, sample) sample = \"makes\" # function callfind(string, sample)", "e": 27230, "s": 26586, "text": null }, { "code": null, "e": 27238, "s": 27230, "text": "Output:" }, { "code": null, "e": 27323, "s": 27238, "text": "string starts with the given substring\nstring doesn't start with the given substring" }, { "code": null, "e": 27345, "s": 27323, "text": "Python Regex-programs" }, { "code": null, "e": 27358, "s": 27345, "text": "python-regex" }, { "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": 27481, "s": 27463, "text": "Python Dictionary" }, { "code": null, "e": 27516, "s": 27481, "text": "Read a file line by line in Python" }, { "code": null, "e": 27538, "s": 27516, "text": "Enumerate() in Python" }, { "code": null, "e": 27570, "s": 27538, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27600, "s": 27570, "text": "Iterate over a list in Python" }, { "code": null, "e": 27642, "s": 27600, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27668, "s": 27642, "text": "Python String | replace()" }, { "code": null, "e": 27711, "s": 27668, "text": "Python program to convert a list to string" }, { "code": null, "e": 27748, "s": 27711, "text": "Create a Pandas DataFrame from Lists" } ]
SLF4J - Environment Setup
In this chapter, we will explain how to set SLF4J environment in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse. For more information on Eclipse, please refer our Eclipse Tutorial Open the official homepage of the SLF4J website and go to the download page. Now, download the latest stable version of slf4j-X.X.tar.gz or slf4j-X.X.zip, according to your operating system (if windows .zip file or if Linux tar.gz file). Within the downloaded folder, you will find slf4j-api-X.X.jar. This is the required Jar file. Open eclipse and create a sample project. Right-click on the project, select the option Build Path → Configure Build Path... as shown below. In the Java Build Path frame in the Libraries tab, click Add External JARs... Select the slf4j-api.x.x.jar file downloaded and click Apply and Close. In addition to slf4j-api.x.x.jar file, SLF4J provides several other Jar files as shown below. These are called SLF4J bindings. Where each binding is for its respective logging framework. The following table lists the SLF4J bindings and their corresponding frameworks. slf4j-nop-x.x.jar No operation, discards all loggings. slf4j-simple-x.x.jar Simple implementation where messages for info and higher are printed and, remaining all outputs to System.err. slf4j-jcl-x.x.jar Jakarta Commons Logging framework. slf4j-jdk14-x.x.jar Java.util.logging framework (JUL). slf4j-log4j12-x.x.jar Log4J frame work. In addition, you need to have log4j.jar. To make SLF4J work along with slf4l-api-x.x.jar, you need to add the respective Jar file (binding) of the desired logger framework in the classpath of the project (set build path). To switch from one framework to other, you need to replace the respective binding. If no bounding is found, it defaults to no-operation mode. If you are creating the maven project, open the pom.xml and paste the following content in it and refresh the project. <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>Sample</groupId> <artifactId>Sample</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> </dependencies> </project> Print Add Notes Bookmark this page
[ { "code": null, "e": 2008, "s": 1785, "text": "In this chapter, we will explain how to set SLF4J environment in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse." }, { "code": null, "e": 2075, "s": 2008, "text": "For more information on Eclipse, please refer our Eclipse Tutorial" }, { "code": null, "e": 2152, "s": 2075, "text": "Open the official homepage of the SLF4J website and go to the download page." }, { "code": null, "e": 2313, "s": 2152, "text": "Now, download the latest stable version of slf4j-X.X.tar.gz or slf4j-X.X.zip, according to your operating system (if windows .zip file or if Linux tar.gz file)." }, { "code": null, "e": 2407, "s": 2313, "text": "Within the downloaded folder, you will find slf4j-api-X.X.jar. This is the required Jar file." }, { "code": null, "e": 2548, "s": 2407, "text": "Open eclipse and create a sample project. Right-click on the project, select the option Build Path → Configure Build Path... as shown below." }, { "code": null, "e": 2626, "s": 2548, "text": "In the Java Build Path frame in the Libraries tab, click Add External JARs..." }, { "code": null, "e": 2698, "s": 2626, "text": "Select the slf4j-api.x.x.jar file downloaded and click Apply and Close." }, { "code": null, "e": 2825, "s": 2698, "text": "In addition to slf4j-api.x.x.jar file, SLF4J provides several other Jar files as shown below. These are called SLF4J bindings." }, { "code": null, "e": 2885, "s": 2825, "text": "Where each binding is for its respective logging framework." }, { "code": null, "e": 2966, "s": 2885, "text": "The following table lists the SLF4J bindings and their corresponding frameworks." }, { "code": null, "e": 2984, "s": 2966, "text": "slf4j-nop-x.x.jar" }, { "code": null, "e": 3021, "s": 2984, "text": "No operation, discards all loggings." }, { "code": null, "e": 3042, "s": 3021, "text": "slf4j-simple-x.x.jar" }, { "code": null, "e": 3153, "s": 3042, "text": "Simple implementation where messages for info and higher are printed and, remaining all outputs to System.err." }, { "code": null, "e": 3171, "s": 3153, "text": "slf4j-jcl-x.x.jar" }, { "code": null, "e": 3206, "s": 3171, "text": "Jakarta Commons Logging framework." }, { "code": null, "e": 3226, "s": 3206, "text": "slf4j-jdk14-x.x.jar" }, { "code": null, "e": 3261, "s": 3226, "text": "Java.util.logging framework (JUL)." }, { "code": null, "e": 3283, "s": 3261, "text": "slf4j-log4j12-x.x.jar" }, { "code": null, "e": 3342, "s": 3283, "text": "Log4J frame work. In addition, you need to have log4j.jar." }, { "code": null, "e": 3523, "s": 3342, "text": "To make SLF4J work along with slf4l-api-x.x.jar, you need to add the respective Jar file (binding) of the desired logger framework in the classpath of the project (set build path)." }, { "code": null, "e": 3665, "s": 3523, "text": "To switch from one framework to other, you need to replace the respective binding. If no bounding is found, it defaults to no-operation mode." }, { "code": null, "e": 3784, "s": 3665, "text": "If you are creating the maven project, open the pom.xml and paste the following content in it and refresh the project." }, { "code": null, "e": 4714, "s": 3784, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>Sample</groupId>\n <artifactId>Sample</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <build>\n <sourceDirectory>src</sourceDirectory>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.7.0</version>\n <configuration>\n <source>1.8</source>\n <target>1.8</target>\n </configuration>\n </plugin>\n </plugins>\n </build>\n <dependencies>\n <dependency>\n <groupId>org.slf4j</groupId>\n <artifactId>slf4j-api</artifactId>\n <version>1.7.25</version>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 4721, "s": 4714, "text": " Print" }, { "code": null, "e": 4732, "s": 4721, "text": " Add Notes" } ]
How to get the data attributes of an element using JavaScript ? - GeeksforGeeks
08 Dec, 2021 In this article, we will learn to get the element’s data attribute in Javascript. Given an HTML document and the task is to select the data attributes of an element using JavaScript. There are a few methods to solve this problem which are given below: Using the dataset property Using .getAttribute() method We will discuss both the ways to get the data attribute of an element. Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the .getAttribute() method to select them by specifically typing their names. Here, in the below examples, we will use the getElementById() method that will return the elements havingthe given ID which is passed to the function. The parseInt() function is used that will accept the string ,radix parameter and convert them into an integer. The JSON.stringify() method is used to create a JSON string out of it. This method is helpful for the conversion of an object to a string. Example 1: This example uses dataset property to get the data attributes of an element. HTML <!DOCTYPE HTML><html> <head> <title> How to get the data attributes of an element using JavaScript ? </title></head> <body align="center"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <span data-typeId="123" data-name="name" data-points="10" data-important="true" id="span">This is the Element. <br> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var input = document.getElementById('span'); el_up.innerHTML = "Click on the button to get " + "the data attributes of element."; function GFG_Fun() { var jsonData = JSON.stringify({ id: parseInt(input.dataset.typeid), points: parseInt(input.dataset.points), important: input.dataset.important, dataName: input.dataset.name }); el_down.innerHTML = jsonData; } </script></body> </html> Output: dataset Property Example 2: This example uses the .getAttribute() method to get the data attributes of an element. HTML <!DOCTYPE HTML><html> <head> <title> How to get the data attributes of an element using JavaScript ? </title></head> <body align="center"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <span data-typeId="123" data-name="name" data-points="10" data-important="true" id="span">This is the Element. <br> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var input = document.getElementById('span'); el_up.innerHTML = "Click on the button to get " + "the data attributes of element."; function GFG_Fun() { var jsonData = JSON.stringify({ id: parseInt(input.getAttribute('data-typeId')), points: parseInt(input.getAttribute('data-points')), important: input.getAttribute('data-important'), dataName: input.getAttribute('data-name') }); el_down.innerHTML = jsonData; } </script></body> </html> Output: .getAttribute() Method bhaskargeeksforgeeks sweetyty JavaScript-Questions JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25159, "s": 25131, "text": "\n08 Dec, 2021" }, { "code": null, "e": 25411, "s": 25159, "text": "In this article, we will learn to get the element’s data attribute in Javascript. Given an HTML document and the task is to select the data attributes of an element using JavaScript. There are a few methods to solve this problem which are given below:" }, { "code": null, "e": 25438, "s": 25411, "text": "Using the dataset property" }, { "code": null, "e": 25467, "s": 25438, "text": "Using .getAttribute() method" }, { "code": null, "e": 25538, "s": 25467, "text": "We will discuss both the ways to get the data attribute of an element." }, { "code": null, "e": 25548, "s": 25538, "text": "Approach:" }, { "code": null, "e": 25607, "s": 25548, "text": "First, select the element which is having data attributes." }, { "code": null, "e": 25768, "s": 25607, "text": "We can either use the dataset property to get access to the data attributes or use the .getAttribute() method to select them by specifically typing their names." }, { "code": null, "e": 26169, "s": 25768, "text": "Here, in the below examples, we will use the getElementById() method that will return the elements havingthe given ID which is passed to the function. The parseInt() function is used that will accept the string ,radix parameter and convert them into an integer. The JSON.stringify() method is used to create a JSON string out of it. This method is helpful for the conversion of an object to a string." }, { "code": null, "e": 26257, "s": 26169, "text": "Example 1: This example uses dataset property to get the data attributes of an element." }, { "code": null, "e": 26262, "s": 26257, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get the data attributes of an element using JavaScript ? </title></head> <body align=\"center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <span data-typeId=\"123\" data-name=\"name\" data-points=\"10\" data-important=\"true\" id=\"span\">This is the Element. <br> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var input = document.getElementById('span'); el_up.innerHTML = \"Click on the button to get \" + \"the data attributes of element.\"; function GFG_Fun() { var jsonData = JSON.stringify({ id: parseInt(input.dataset.typeid), points: parseInt(input.dataset.points), important: input.dataset.important, dataName: input.dataset.name }); el_down.innerHTML = jsonData; } </script></body> </html>", "e": 27506, "s": 26262, "text": null }, { "code": null, "e": 27514, "s": 27506, "text": "Output:" }, { "code": null, "e": 27531, "s": 27514, "text": "dataset Property" }, { "code": null, "e": 27629, "s": 27531, "text": "Example 2: This example uses the .getAttribute() method to get the data attributes of an element." }, { "code": null, "e": 27634, "s": 27629, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to get the data attributes of an element using JavaScript ? </title></head> <body align=\"center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <span data-typeId=\"123\" data-name=\"name\" data-points=\"10\" data-important=\"true\" id=\"span\">This is the Element. <br> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var input = document.getElementById('span'); el_up.innerHTML = \"Click on the button to get \" + \"the data attributes of element.\"; function GFG_Fun() { var jsonData = JSON.stringify({ id: parseInt(input.getAttribute('data-typeId')), points: parseInt(input.getAttribute('data-points')), important: input.getAttribute('data-important'), dataName: input.getAttribute('data-name') }); el_down.innerHTML = jsonData; } </script></body> </html>", "e": 28936, "s": 27634, "text": null }, { "code": null, "e": 28944, "s": 28936, "text": "Output:" }, { "code": null, "e": 28967, "s": 28944, "text": ".getAttribute() Method" }, { "code": null, "e": 28988, "s": 28967, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 28997, "s": 28988, "text": "sweetyty" }, { "code": null, "e": 29018, "s": 28997, "text": "JavaScript-Questions" }, { "code": null, "e": 29029, "s": 29018, "text": "JavaScript" }, { "code": null, "e": 29046, "s": 29029, "text": "Web Technologies" }, { "code": null, "e": 29073, "s": 29046, "text": "Web technologies Questions" }, { "code": null, "e": 29171, "s": 29073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29211, "s": 29171, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29256, "s": 29211, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29317, "s": 29256, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29389, "s": 29317, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29435, "s": 29389, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29475, "s": 29435, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29508, "s": 29475, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29553, "s": 29508, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29596, "s": 29553, "text": "How to fetch data from an API in ReactJS ?" } ]
Area of a n-sided regular polygon with given Radius?
Here we will see how to get the area of an n-sided regular polygon whose radius is given. Here the radius is the distance from the center of any vertex. To solve this problem, we have drawn one perpendicular from the center to one side. Let each side is of length ‘a’. The perpendicular is dividing the side into two parts. The length of each part is a/2. The perpendicular and one radius is making an angle x. Let the length of the radius is h. Here we can see that the polygon is divided into N equal triangles. So for any polygon with N sides, will be divided into N triangles. So the angle at the center is 360. That is divided into 360°/N different angles (Here 360°/6 = 60°). So the angle x is 180°/N. Now we can easily get the h and a using trigonometric equations. Now the area of whole polygon is N*A. #include <iostream> #include <cmath> using namespace std; float polygonArea(float r, int n){ return ((r * r * n) * sin((360 / n) * 3.1415 / 180)) / 2; //convert angle to rad then calculate } int main() { float rad = 9.0f; int sides = 6; cout << "Polygon Area: " << polygonArea(rad, sides); } Polygon Area: 210.44
[ { "code": null, "e": 1508, "s": 1062, "text": "Here we will see how to get the area of an n-sided regular polygon whose radius is given. Here the radius is the distance from the center of any vertex. To solve this problem, we have drawn one perpendicular from the center to one side. Let each side is of length ‘a’. The perpendicular is dividing the side into two parts. The length of each part is a/2. The perpendicular and one radius is making an angle x. Let the length of the radius is h." }, { "code": null, "e": 1835, "s": 1508, "text": "Here we can see that the polygon is divided into N equal triangles. So for any polygon with N sides, will be divided into N triangles. So the angle at the center is 360. That is divided into 360°/N different angles (Here 360°/6 = 60°). So the angle x is 180°/N. Now we can easily get the h and a using trigonometric equations." }, { "code": null, "e": 1873, "s": 1835, "text": "Now the area of whole polygon is N*A." }, { "code": null, "e": 2180, "s": 1873, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nfloat polygonArea(float r, int n){\n return ((r * r * n) * sin((360 / n) * 3.1415 / 180)) / 2; //convert\n angle to rad then calculate\n}\nint main() {\n float rad = 9.0f;\n int sides = 6;\n cout << \"Polygon Area: \" << polygonArea(rad, sides);\n}" }, { "code": null, "e": 2201, "s": 2180, "text": "Polygon Area: 210.44" } ]
How to Customize Toast in Android? - GeeksforGeeks
08 Oct, 2021 A Toast is a feedback message. It takes very little space for displaying and it is displayed on top of the main content of an activity, and only remains visible for a short time period. In this article, we will learn how to customize Toast in android. So, we will understand this by making a simple app to display a Toast. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.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"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Here we will bind the views and write the logic of the app. Kotlin import android.graphics.Colorimport android.os.Bundleimport android.view.Gravityimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var btn: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn = findViewById(R.id.button1) val text = "GeeksForGeeks" btn.setOnClickListener { showToast(text) } } private fun showToast(text: String) { val toast = Toast.makeText(this, text, Toast.LENGTH_SHORT) // Set the position of the toast toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0) val viewGroup = toast.view as ViewGroup? // Get the TextView of the toast val textView = viewGroup!!.getChildAt(0) as TextView // Set the text size textView.textSize = 20f // Set the background color of toast viewGroup!!.setBackgroundColor(Color.parseColor("#079A0F")) // Display the Toast toast.show() }} So our app is ready. Output: Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters Kotlin when expression
[ { "code": null, "e": 26491, "s": 26463, "text": "\n08 Oct, 2021" }, { "code": null, "e": 26814, "s": 26491, "text": "A Toast is a feedback message. It takes very little space for displaying and it is displayed on top of the main content of an activity, and only remains visible for a short time period. In this article, we will learn how to customize Toast in android. So, we will understand this by making a simple app to display a Toast." }, { "code": null, "e": 26843, "s": 26814, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27005, "s": 26843, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 27053, "s": 27005, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 27196, "s": 27053, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 27200, "s": 27196, "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\"> <Button android:id=\"@+id/button1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Show Toast\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 27999, "s": 27200, "text": null }, { "code": null, "e": 28045, "s": 27999, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 28291, "s": 28045, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Here we will bind the views and write the logic of the app." }, { "code": null, "e": 28298, "s": 28291, "text": "Kotlin" }, { "code": "import android.graphics.Colorimport android.os.Bundleimport android.view.Gravityimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var btn: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn = findViewById(R.id.button1) val text = \"GeeksForGeeks\" btn.setOnClickListener { showToast(text) } } private fun showToast(text: String) { val toast = Toast.makeText(this, text, Toast.LENGTH_SHORT) // Set the position of the toast toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0) val viewGroup = toast.view as ViewGroup? // Get the TextView of the toast val textView = viewGroup!!.getChildAt(0) as TextView // Set the text size textView.textSize = 20f // Set the background color of toast viewGroup!!.setBackgroundColor(Color.parseColor(\"#079A0F\")) // Display the Toast toast.show() }}", "e": 29528, "s": 28298, "text": null }, { "code": null, "e": 29549, "s": 29528, "text": "So our app is ready." }, { "code": null, "e": 29557, "s": 29549, "text": "Output:" }, { "code": null, "e": 29565, "s": 29557, "text": "Android" }, { "code": null, "e": 29572, "s": 29565, "text": "Kotlin" }, { "code": null, "e": 29580, "s": 29572, "text": "Android" }, { "code": null, "e": 29678, "s": 29580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29716, "s": 29678, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29755, "s": 29716, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29805, "s": 29755, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29831, "s": 29805, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 29882, "s": 29831, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 29901, "s": 29882, "text": "Android UI Layouts" }, { "code": null, "e": 29914, "s": 29901, "text": "Kotlin Array" }, { "code": null, "e": 29956, "s": 29914, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29983, "s": 29956, "text": "Kotlin Setters and Getters" } ]
Production Planning and Resource Management of Manufacturing Systems in Python | by Will Keefe | Towards Data Science
It’s no secret that supply chain management is one of the biggest areas of focus for improvement in today’s global economy. Getting goods from destination A to destination B is challenging enough, but manufacturing enough materials is equivocally arduous, with shortages in silicon chips and pharmaceutical assemblies catching headlines as well. Modeling these manufacturing processes requires a well-developed understanding of the constraints and dependencies inherent to the production line. Some mixed-integer programming models such as CPLEX or Google’s OR framework derive solutions optimizing an objective function, such as minimizing costs or assigning resources to fixed shifts with delineated constraints and priorities. These models struggle however to model continuous systems and require scaling to make sure the inputs are mathematically even possible to implement. We can develop a rudimentary production plan with resource balancing in a forward-facing heuristic with relative ease within Python using well-known packages such as Pandas, and can graphically illustrate an interactive Gantt chart using Plotly to show our plan for cascading vertically to management and the shop floor. First, let's flush out the case study we will be using for this exercise. In this application, we will be discussing biologics manufacturing within pharmaceuticals. Many vaccines such as those for COVID manufactured today are derived from microorganisms modified to produce the bulk material eliciting an immune response necessary to prevent disease transmission and illness. The details of these processes are often proprietary and very complicated, but for our exercise today let’s assume we are manufacturing a product grown from a microorganism in a fermentation process, purified thoroughly using filters and centrifuges, and then sterilized before adding adjuvants and filling in vials. This process illustrated below is generic and can be found at many different organizations at lab-scale and industrial-scale. True manufacturing processes would have hundreds of tasks with interlinked constraints and dependencies. For our model, we will have progressive dependencies of one or two preceding tasks, and constraints of technician operator labor and equipment available. We will model these tasks and constraints within a JSON file in the following formats. Tasks: "Items": [ { "ID":1, "Name":"Seed", "Description":"Start fermentation from vial of seed material.", "Process":"Fermentation", "ResourcesRequired": { "Operator":2, "SafetyCabinet":1 }, "Dependencies":[0], "Duration":2 }, { "ID":2, "Name":"Flasks", "Description":"Ferment seed material in flasks.", "Process":"Fermentation", "ResourcesRequired": { "Operator":2, "SafetyCabinet":1 }, "Dependencies":[1], "Duration":3 }, { "ID":3, "Name":"Small Fermentor", "Description":"Ferment in small fermentation vessel.", "Process":"Fermentation", "ResourcesRequired": { "Operator":2, "SmallFermentor":1 }, "Dependencies":[2], "Duration":3 }, { "ID":4, "Name":"Large Fermentor", "Description":"Ferment and inactivare in large fermentation vessel.", "Process":"Fermentation", "ResourcesRequired": { "Operator":2, "LargeFermentor":1 }, "Dependencies":[3], "Duration":4 }, { "ID":5, "Name":"Prepare Filters", "Description":"Prep purification filters for next step.", "Process":"Purification", "ResourcesRequired": { "Operator":1, "PurificationTank":1 }, "Dependencies":[3], "Duration":1 }, { "ID":6, "Name":"Purification Filters", "Description":"Start purification in first purification assembly.", "Process":"Purification", "ResourcesRequired": { "Operator":3, "PurificationTank":1 }, "Dependencies":[4,5], "Duration":4 }, { "ID":7, "Name":"Centrifuge", "Description":"Separate material in centrifuges.", "Process":"Purification", "ResourcesRequired": { "Operator":2, "Centrifuge":2 }, "Dependencies":[6], "Duration":4 }, { "ID":8, "Name":"Sterile Filter", "Description":"Start sterilization of material.", "Process":"Sterile Boundary", "ResourcesRequired": { "Operator":3, "SterileAssembly":1 }, "Dependencies":[7], "Duration":2 }, { "ID":9, "Name":"Adjuvants", "Description":"Add adjuvants to bulk material.", "Process":"Sterile Boundary", "ResourcesRequired": { "Operator":2, "SterileAssembly":1 }, "Dependencies":[8], "Duration":2 }, { "ID":10, "Name":"Prepare Vials", "Description":"Sterilize bulk vials.", "Process":"Sterile Boundary", "ResourcesRequired": { "Operator":2, "VialFiller":1 }, "Dependencies":[8], "Duration":1 }, { "ID":11, "Name":"Fill", "Description":"Fill vials with bulk material.", "Process":"Sterile Boundary", "ResourcesRequired": { "Operator":2, "VialFiller":1 }, "Dependencies":[9,10], "Duration":3 } ], Notice every step of our batch includes: ID — integer value Name — string short description Description — string long description Process — string (one of three categories of step) Resources Required — dictionary of resources required and integer count Dependencies — list of ID integers reliant upon Duration — integer of hours required (does not have to be an integer) Constraints: "ResourceCapacities":{ "Operator":3, "SafetyCabinet":1, "SmallFermentor":1, "LargeFermentor":1, "PurificationTank":1, "Centrifuge":3, "SterileAssembly":1, "VialFiller":1 } Notice our constraints are a dictionary of the resources from tasks and what our case study model team has available. Our manufacturing suite has 3 operators, 1 safety cabinet, 1 small fermentor, etc, available for use at any given time. Each one of our batches we think will take approximately two days if we add up all of the durations of our tasks, however, we notice that some tasks are reliant on two predecessors. These can be done in tandem if we have enough resources available! The goal of our program will be to schedule the batch with the shortest runtime. In theory, this production plan could be used to schedule a series of runs and give management a stronger idea of what is achievable given limited resources within a period. To start developing our model within Python, we first have to import the libraries we will be using. import pandas as pdimport datetimeimport numpy as npimport plotly.figure_factory as ffimport jsonimport randomimport plotly.express as px Pandas will be the main library being used for multiple data frames and manipulations. Plotly will be our main library for visualization later on. Importing our data JSON file is straightforward. with open('tasks.json') as json_file: data = json.load(json_file) We can then initialize our tasks data frame with this loaded data. TasksDF = pd.DataFrame.from_dict(data['Items'])CapacitiesDict = data['ResourceCapacities'] Our data frame looks very similar to that you would see in excel or another table-based tool, however, our ResourcesRequired column contains dictionaries and our Dependencies column contains lists of either one or two elements. The capacities dictionary we want to initialize directly as that object. Next, we want to initialize a list of time intervals spanning the entire range we can expect our process to reach. The total of our duration columns summed together is 29 hours, so let’s round up to two days. start_date = datetime.datetime(2021, 1, 1,0,0,0)number_of_days = 2intervals = []for minute in range(number_of_days*96): interval = (start_date + datetime.timedelta(minutes = 15*minute)).isoformat() intervals.append(interval) Our granularity in our intervals is fifteen-minute chunks, and there are 96 fifteen-minute chunks in one day. Therefore our entire list will be 192 of these fifteen-minute intervals. We could also either scale up to thirty-minute or one-hour intervals to save processing time or could get more precise timelines at lower scales of five or ten-minute intervals; a deciding factor in determining granularity is the specificity of the duration column. Next, we need to make a matrix of all of our times and the resources we will need to load. Note below that our columns are all of the resource names and the keys from the capacities dictionary. headings = list(CapacitiesDict.keys())loading = pd.DataFrame(columns = headings)loading['index']=intervalsloading = loading.fillna(0) We will then do the same for a maximum loading matrix, but this time, our contents will be the maximum number of resources we can load during that interval. If any task is attempted to be scheduled and resources are not available during that interval, it should be postponed to the next interval with available resources. For the sake of simplicity within this exercise we will keep our values constant (three operators available 24/7), but in reality, these values are expected to change with shifts and equipment availability. Our later algorithms will function the same regardless of the scenario. loadingMax = pd.DataFrame(columns = headings)loadingMax['index']=intervalsfor item in headings: loadingMax[item] = CapacitiesDict[item] Our tasks now need to have some additional data appended. We need to know how many minutes still need to be scheduled and have their resources accounted for, and then initialize some start and end times within our interval indices as well. jobsToAdd = TasksDF.copy()jobsToAdd['TimeAddedToSchedule']=jobsToAdd['Duration']*60jobsToAdd['Start'] = start_datejobsToAdd['End'] = start_date We have now prepared all of our data to be processed. Now comes the challenging part: processing our various constraints in resources and dependencies and scheduling our tasks. Our algorithm will operate in this order: Load row by row of loading matrix Load task by task of jobs to add tasks Check if the current job needs to be added still; if it does, proceed Check if resources are available in the current time interval of the loading matrix; if they are, proceed Check if the dependencies have been scheduled yet and do not end in the next interval; if they are complete, proceed If this is the first interval being scheduled, take the timestamp of the start time Deduct time remaining to be scheduled and allocate resources If there is no more time remaining to be scheduled, take the timestamp of the end time That’s essentially it. To dive into the code, please copy the block and paste it within a development environment such as Atom or Visual Studio to see all of the semantics highlighted. for i in range(len(loading.index)): # Go through loading schedule time by time print(str(round(i/len(loading.index)*100,2))+'%') for j in range(len(jobsToAdd.index)): # Go through list of jobs, job by job if jobsToAdd['TimeAddedToSchedule'][j]>0: # Continue if job needs to be scheduled still available = True for resource in list(jobsToAdd['ResourcesRequired'][j].keys()): # Continue if all required resources are available if loading[resource][i] + jobsToAdd['ResourcesRequired'][j][resource] > loadingMax[resource][i]: available=False if available: dependenciesSatisfied = True if jobsToAdd['Dependencies'][j][0] == 0: #Skip checking dependencies if there are none pass else: for dependency in jobsToAdd['Dependencies'][j]: # Check if a task's dependencies have been fully scheduled if jobsToAdd.loc[jobsToAdd['ID'] == dependency]['TimeAddedToSchedule'].item() > 0: dependenciesSatisfied = False # Check if fully scheduled if jobsToAdd.loc[jobsToAdd['ID'] == dependency]['End'].item() == datetime.datetime.strptime(loading['index'][i],'%Y-%m-%dT%H:%M:%S')+ datetime.timedelta(minutes = 15): dependenciesSatisfied = False # Check that dependent end time isnt after the start of this time if dependenciesSatisfied: if jobsToAdd['TimeAddedToSchedule'][j]==jobsToAdd['Duration'][j]*60: # Set the start time jobsToAdd['Start'][j]=datetime.datetime.strptime(loading['index'][i],'%Y-%m-%dT%H:%M:%S') for resource in list(jobsToAdd['ResourcesRequired'][j].keys()): # Allocate Resources loading[resource][i] = loading[resource][i] + jobsToAdd['ResourcesRequired'][j][resource] jobsToAdd['TimeAddedToSchedule'][j] = jobsToAdd['TimeAddedToSchedule'][j]-15 # Reduce needed time if jobsToAdd['TimeAddedToSchedule'][j] == 0: # Set the end time jobsToAdd['End'][j]=datetime.datetime.strptime(loading['index'][i],'%Y-%m-%dT%H:%M:%S')+ datetime.timedelta(minutes = 15) Running our algorithm should only take a second or two with our limited number of tasks to schedule. As we can imagine, it could take significantly longer with more tasks to schedule, or over a larger period of intervals. Following completion of our algorithm run, we can see that our jobs to add data frame is now completed and the placeholder timestamps are replaced. No time is remaining in need of scheduling. Upon examination of our loading data frame, we can also see that our resources have been allocated at or below the capacities of the maximum loading data frame. While our schedule is now complete, the data is hardly in a form easily presentable to audiences whether on the shop floor or to upper management. To better illustrate our timelines, let’s build a Gantt chart with Plotly. To start, we need to configure our data into a form readable by plotly figure factory. x = jobsToAdd[['Name','Start','End','Process']].copy()x = x.rename(columns={'Name':'Task','Process':'Resource','End':'Finish'}) # Configure data for data frame formattingdf = []for r in range(len(x.index)): df.append(dict(Task=x['Task'][r],Start=x['Start'][r],Finish=x['Finish'][r],Resource=x['Resource'][r]))# Assign color pallete randomly for dynamic number of resource categoriesr = lambda: random.randint(0,255)colors = ['#%02X%02X%02X' % (r(),r(),r())]for i in range(len(x.Resource.unique().tolist())): colors.append('#%02X%02X%02X' % (r(),r(),r()))fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True, group_tasks=True)fig.show() We can see our interactive Gantt chart rendered below. This production schedule can be exported wherever we need it to be, and we can select on-screen areas we want to dive deeper into. We can also note now visually that we can batch ferment in our large fermentor and prepare filters for purification at the same time because we have enough operators available and purification requires both of those tasks to be complete to proceed, however preparing vials and adding adjuvants cannot proceed at the same time due to a shortage of operator resources available. What if we want to gather some statistics for our data, such as resource utilization? All of this data is captured in our loading data frame and is available for reporting. loading.describe() Using the Pandas describe() function, we can see the maximum resource utilization available. This is extremely useful for determining the answer the right amount of resources needed to get the job done. We see we have maxed out at least for a short period our number of operators available. If we had four available, we’d be able to complete our adding adjuvants and prepare vials at the same time and complete our process earlier. fig = px.line(loading, x="index", y="Operator")fig.show() The case study we worked together on here is relatively small in scope compared to the real-manufacturing-floor batches which can contain hundreds of tasks and dozens of resources to load. This data can add up quickly and can vary from industry to industry. However, our code is scalable and can handle these dependencies albeit at the cost of more extensive processing time. Some areas for improvement to our algorithm also include capabilities seen in other project management suites such as delayed starts, inventory tracking and batching, and adding/tracking delays. We can also supplement our data at a later point and add further requirements or even bills of materials or costs to our work, to develop secondary objective functions and for further visualization. Because we developed our visuals within Plotly, we can also use enterprise data hosting or make our own Dash dashboards. Please let me know what you think, and feel free to reach out to me on LinkedIn with feedback, to ask questions, or to see how we can bring these tools and mindsets to your organization! Check out some of my other articles here on data analysis and visualization!
[ { "code": null, "e": 518, "s": 172, "text": "It’s no secret that supply chain management is one of the biggest areas of focus for improvement in today’s global economy. Getting goods from destination A to destination B is challenging enough, but manufacturing enough materials is equivocally arduous, with shortages in silicon chips and pharmaceutical assemblies catching headlines as well." }, { "code": null, "e": 1051, "s": 518, "text": "Modeling these manufacturing processes requires a well-developed understanding of the constraints and dependencies inherent to the production line. Some mixed-integer programming models such as CPLEX or Google’s OR framework derive solutions optimizing an objective function, such as minimizing costs or assigning resources to fixed shifts with delineated constraints and priorities. These models struggle however to model continuous systems and require scaling to make sure the inputs are mathematically even possible to implement." }, { "code": null, "e": 1372, "s": 1051, "text": "We can develop a rudimentary production plan with resource balancing in a forward-facing heuristic with relative ease within Python using well-known packages such as Pandas, and can graphically illustrate an interactive Gantt chart using Plotly to show our plan for cascading vertically to management and the shop floor." }, { "code": null, "e": 2191, "s": 1372, "text": "First, let's flush out the case study we will be using for this exercise. In this application, we will be discussing biologics manufacturing within pharmaceuticals. Many vaccines such as those for COVID manufactured today are derived from microorganisms modified to produce the bulk material eliciting an immune response necessary to prevent disease transmission and illness. The details of these processes are often proprietary and very complicated, but for our exercise today let’s assume we are manufacturing a product grown from a microorganism in a fermentation process, purified thoroughly using filters and centrifuges, and then sterilized before adding adjuvants and filling in vials. This process illustrated below is generic and can be found at many different organizations at lab-scale and industrial-scale." }, { "code": null, "e": 2537, "s": 2191, "text": "True manufacturing processes would have hundreds of tasks with interlinked constraints and dependencies. For our model, we will have progressive dependencies of one or two preceding tasks, and constraints of technician operator labor and equipment available. We will model these tasks and constraints within a JSON file in the following formats." }, { "code": null, "e": 2544, "s": 2537, "text": "Tasks:" }, { "code": null, "e": 5577, "s": 2544, "text": "\"Items\": [ { \"ID\":1, \"Name\":\"Seed\", \"Description\":\"Start fermentation from vial of seed material.\", \"Process\":\"Fermentation\", \"ResourcesRequired\": { \"Operator\":2, \"SafetyCabinet\":1 }, \"Dependencies\":[0], \"Duration\":2 }, { \"ID\":2, \"Name\":\"Flasks\", \"Description\":\"Ferment seed material in flasks.\", \"Process\":\"Fermentation\", \"ResourcesRequired\": { \"Operator\":2, \"SafetyCabinet\":1 }, \"Dependencies\":[1], \"Duration\":3 }, { \"ID\":3, \"Name\":\"Small Fermentor\", \"Description\":\"Ferment in small fermentation vessel.\", \"Process\":\"Fermentation\", \"ResourcesRequired\": { \"Operator\":2, \"SmallFermentor\":1 }, \"Dependencies\":[2], \"Duration\":3 }, { \"ID\":4, \"Name\":\"Large Fermentor\", \"Description\":\"Ferment and inactivare in large fermentation vessel.\", \"Process\":\"Fermentation\", \"ResourcesRequired\": { \"Operator\":2, \"LargeFermentor\":1 }, \"Dependencies\":[3], \"Duration\":4 }, { \"ID\":5, \"Name\":\"Prepare Filters\", \"Description\":\"Prep purification filters for next step.\", \"Process\":\"Purification\", \"ResourcesRequired\": { \"Operator\":1, \"PurificationTank\":1 }, \"Dependencies\":[3], \"Duration\":1 }, { \"ID\":6, \"Name\":\"Purification Filters\", \"Description\":\"Start purification in first purification assembly.\", \"Process\":\"Purification\", \"ResourcesRequired\": { \"Operator\":3, \"PurificationTank\":1 }, \"Dependencies\":[4,5], \"Duration\":4 }, { \"ID\":7, \"Name\":\"Centrifuge\", \"Description\":\"Separate material in centrifuges.\", \"Process\":\"Purification\", \"ResourcesRequired\": { \"Operator\":2, \"Centrifuge\":2 }, \"Dependencies\":[6], \"Duration\":4 }, { \"ID\":8, \"Name\":\"Sterile Filter\", \"Description\":\"Start sterilization of material.\", \"Process\":\"Sterile Boundary\", \"ResourcesRequired\": { \"Operator\":3, \"SterileAssembly\":1 }, \"Dependencies\":[7], \"Duration\":2 }, { \"ID\":9, \"Name\":\"Adjuvants\", \"Description\":\"Add adjuvants to bulk material.\", \"Process\":\"Sterile Boundary\", \"ResourcesRequired\": { \"Operator\":2, \"SterileAssembly\":1 }, \"Dependencies\":[8], \"Duration\":2 }, { \"ID\":10, \"Name\":\"Prepare Vials\", \"Description\":\"Sterilize bulk vials.\", \"Process\":\"Sterile Boundary\", \"ResourcesRequired\": { \"Operator\":2, \"VialFiller\":1 }, \"Dependencies\":[8], \"Duration\":1 }, { \"ID\":11, \"Name\":\"Fill\", \"Description\":\"Fill vials with bulk material.\", \"Process\":\"Sterile Boundary\", \"ResourcesRequired\": { \"Operator\":2, \"VialFiller\":1 }, \"Dependencies\":[9,10], \"Duration\":3 } ]," }, { "code": null, "e": 5618, "s": 5577, "text": "Notice every step of our batch includes:" }, { "code": null, "e": 5637, "s": 5618, "text": "ID — integer value" }, { "code": null, "e": 5669, "s": 5637, "text": "Name — string short description" }, { "code": null, "e": 5707, "s": 5669, "text": "Description — string long description" }, { "code": null, "e": 5758, "s": 5707, "text": "Process — string (one of three categories of step)" }, { "code": null, "e": 5830, "s": 5758, "text": "Resources Required — dictionary of resources required and integer count" }, { "code": null, "e": 5878, "s": 5830, "text": "Dependencies — list of ID integers reliant upon" }, { "code": null, "e": 5948, "s": 5878, "text": "Duration — integer of hours required (does not have to be an integer)" }, { "code": null, "e": 5961, "s": 5948, "text": "Constraints:" }, { "code": null, "e": 6174, "s": 5961, "text": "\"ResourceCapacities\":{ \"Operator\":3, \"SafetyCabinet\":1, \"SmallFermentor\":1, \"LargeFermentor\":1, \"PurificationTank\":1, \"Centrifuge\":3, \"SterileAssembly\":1, \"VialFiller\":1 }" }, { "code": null, "e": 6412, "s": 6174, "text": "Notice our constraints are a dictionary of the resources from tasks and what our case study model team has available. Our manufacturing suite has 3 operators, 1 safety cabinet, 1 small fermentor, etc, available for use at any given time." }, { "code": null, "e": 6916, "s": 6412, "text": "Each one of our batches we think will take approximately two days if we add up all of the durations of our tasks, however, we notice that some tasks are reliant on two predecessors. These can be done in tandem if we have enough resources available! The goal of our program will be to schedule the batch with the shortest runtime. In theory, this production plan could be used to schedule a series of runs and give management a stronger idea of what is achievable given limited resources within a period." }, { "code": null, "e": 7017, "s": 6916, "text": "To start developing our model within Python, we first have to import the libraries we will be using." }, { "code": null, "e": 7155, "s": 7017, "text": "import pandas as pdimport datetimeimport numpy as npimport plotly.figure_factory as ffimport jsonimport randomimport plotly.express as px" }, { "code": null, "e": 7351, "s": 7155, "text": "Pandas will be the main library being used for multiple data frames and manipulations. Plotly will be our main library for visualization later on. Importing our data JSON file is straightforward." }, { "code": null, "e": 7420, "s": 7351, "text": "with open('tasks.json') as json_file: data = json.load(json_file)" }, { "code": null, "e": 7487, "s": 7420, "text": "We can then initialize our tasks data frame with this loaded data." }, { "code": null, "e": 7578, "s": 7487, "text": "TasksDF = pd.DataFrame.from_dict(data['Items'])CapacitiesDict = data['ResourceCapacities']" }, { "code": null, "e": 7879, "s": 7578, "text": "Our data frame looks very similar to that you would see in excel or another table-based tool, however, our ResourcesRequired column contains dictionaries and our Dependencies column contains lists of either one or two elements. The capacities dictionary we want to initialize directly as that object." }, { "code": null, "e": 8088, "s": 7879, "text": "Next, we want to initialize a list of time intervals spanning the entire range we can expect our process to reach. The total of our duration columns summed together is 29 hours, so let’s round up to two days." }, { "code": null, "e": 8319, "s": 8088, "text": "start_date = datetime.datetime(2021, 1, 1,0,0,0)number_of_days = 2intervals = []for minute in range(number_of_days*96): interval = (start_date + datetime.timedelta(minutes = 15*minute)).isoformat() intervals.append(interval)" }, { "code": null, "e": 8768, "s": 8319, "text": "Our granularity in our intervals is fifteen-minute chunks, and there are 96 fifteen-minute chunks in one day. Therefore our entire list will be 192 of these fifteen-minute intervals. We could also either scale up to thirty-minute or one-hour intervals to save processing time or could get more precise timelines at lower scales of five or ten-minute intervals; a deciding factor in determining granularity is the specificity of the duration column." }, { "code": null, "e": 8962, "s": 8768, "text": "Next, we need to make a matrix of all of our times and the resources we will need to load. Note below that our columns are all of the resource names and the keys from the capacities dictionary." }, { "code": null, "e": 9096, "s": 8962, "text": "headings = list(CapacitiesDict.keys())loading = pd.DataFrame(columns = headings)loading['index']=intervalsloading = loading.fillna(0)" }, { "code": null, "e": 9697, "s": 9096, "text": "We will then do the same for a maximum loading matrix, but this time, our contents will be the maximum number of resources we can load during that interval. If any task is attempted to be scheduled and resources are not available during that interval, it should be postponed to the next interval with available resources. For the sake of simplicity within this exercise we will keep our values constant (three operators available 24/7), but in reality, these values are expected to change with shifts and equipment availability. Our later algorithms will function the same regardless of the scenario." }, { "code": null, "e": 9836, "s": 9697, "text": "loadingMax = pd.DataFrame(columns = headings)loadingMax['index']=intervalsfor item in headings: loadingMax[item] = CapacitiesDict[item]" }, { "code": null, "e": 10076, "s": 9836, "text": "Our tasks now need to have some additional data appended. We need to know how many minutes still need to be scheduled and have their resources accounted for, and then initialize some start and end times within our interval indices as well." }, { "code": null, "e": 10220, "s": 10076, "text": "jobsToAdd = TasksDF.copy()jobsToAdd['TimeAddedToSchedule']=jobsToAdd['Duration']*60jobsToAdd['Start'] = start_datejobsToAdd['End'] = start_date" }, { "code": null, "e": 10397, "s": 10220, "text": "We have now prepared all of our data to be processed. Now comes the challenging part: processing our various constraints in resources and dependencies and scheduling our tasks." }, { "code": null, "e": 10439, "s": 10397, "text": "Our algorithm will operate in this order:" }, { "code": null, "e": 10473, "s": 10439, "text": "Load row by row of loading matrix" }, { "code": null, "e": 10512, "s": 10473, "text": "Load task by task of jobs to add tasks" }, { "code": null, "e": 10582, "s": 10512, "text": "Check if the current job needs to be added still; if it does, proceed" }, { "code": null, "e": 10688, "s": 10582, "text": "Check if resources are available in the current time interval of the loading matrix; if they are, proceed" }, { "code": null, "e": 10805, "s": 10688, "text": "Check if the dependencies have been scheduled yet and do not end in the next interval; if they are complete, proceed" }, { "code": null, "e": 10889, "s": 10805, "text": "If this is the first interval being scheduled, take the timestamp of the start time" }, { "code": null, "e": 10950, "s": 10889, "text": "Deduct time remaining to be scheduled and allocate resources" }, { "code": null, "e": 11037, "s": 10950, "text": "If there is no more time remaining to be scheduled, take the timestamp of the end time" }, { "code": null, "e": 11222, "s": 11037, "text": "That’s essentially it. To dive into the code, please copy the block and paste it within a development environment such as Atom or Visual Studio to see all of the semantics highlighted." }, { "code": null, "e": 13500, "s": 11222, "text": "for i in range(len(loading.index)): # Go through loading schedule time by time print(str(round(i/len(loading.index)*100,2))+'%') for j in range(len(jobsToAdd.index)): # Go through list of jobs, job by job if jobsToAdd['TimeAddedToSchedule'][j]>0: # Continue if job needs to be scheduled still available = True for resource in list(jobsToAdd['ResourcesRequired'][j].keys()): # Continue if all required resources are available if loading[resource][i] + jobsToAdd['ResourcesRequired'][j][resource] > loadingMax[resource][i]: available=False if available: dependenciesSatisfied = True if jobsToAdd['Dependencies'][j][0] == 0: #Skip checking dependencies if there are none pass else: for dependency in jobsToAdd['Dependencies'][j]: # Check if a task's dependencies have been fully scheduled if jobsToAdd.loc[jobsToAdd['ID'] == dependency]['TimeAddedToSchedule'].item() > 0: dependenciesSatisfied = False # Check if fully scheduled if jobsToAdd.loc[jobsToAdd['ID'] == dependency]['End'].item() == datetime.datetime.strptime(loading['index'][i],'%Y-%m-%dT%H:%M:%S')+ datetime.timedelta(minutes = 15): dependenciesSatisfied = False # Check that dependent end time isnt after the start of this time if dependenciesSatisfied: if jobsToAdd['TimeAddedToSchedule'][j]==jobsToAdd['Duration'][j]*60: # Set the start time jobsToAdd['Start'][j]=datetime.datetime.strptime(loading['index'][i],'%Y-%m-%dT%H:%M:%S') for resource in list(jobsToAdd['ResourcesRequired'][j].keys()): # Allocate Resources loading[resource][i] = loading[resource][i] + jobsToAdd['ResourcesRequired'][j][resource] jobsToAdd['TimeAddedToSchedule'][j] = jobsToAdd['TimeAddedToSchedule'][j]-15 # Reduce needed time if jobsToAdd['TimeAddedToSchedule'][j] == 0: # Set the end time jobsToAdd['End'][j]=datetime.datetime.strptime(loading['index'][i],'%Y-%m-%dT%H:%M:%S')+ datetime.timedelta(minutes = 15)" }, { "code": null, "e": 13722, "s": 13500, "text": "Running our algorithm should only take a second or two with our limited number of tasks to schedule. As we can imagine, it could take significantly longer with more tasks to schedule, or over a larger period of intervals." }, { "code": null, "e": 13914, "s": 13722, "text": "Following completion of our algorithm run, we can see that our jobs to add data frame is now completed and the placeholder timestamps are replaced. No time is remaining in need of scheduling." }, { "code": null, "e": 14075, "s": 13914, "text": "Upon examination of our loading data frame, we can also see that our resources have been allocated at or below the capacities of the maximum loading data frame." }, { "code": null, "e": 14297, "s": 14075, "text": "While our schedule is now complete, the data is hardly in a form easily presentable to audiences whether on the shop floor or to upper management. To better illustrate our timelines, let’s build a Gantt chart with Plotly." }, { "code": null, "e": 14384, "s": 14297, "text": "To start, we need to configure our data into a form readable by plotly figure factory." }, { "code": null, "e": 14512, "s": 14384, "text": "x = jobsToAdd[['Name','Start','End','Process']].copy()x = x.rename(columns={'Name':'Task','Process':'Resource','End':'Finish'})" }, { "code": null, "e": 15069, "s": 14512, "text": "# Configure data for data frame formattingdf = []for r in range(len(x.index)): df.append(dict(Task=x['Task'][r],Start=x['Start'][r],Finish=x['Finish'][r],Resource=x['Resource'][r]))# Assign color pallete randomly for dynamic number of resource categoriesr = lambda: random.randint(0,255)colors = ['#%02X%02X%02X' % (r(),r(),r())]for i in range(len(x.Resource.unique().tolist())): colors.append('#%02X%02X%02X' % (r(),r(),r()))fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True, group_tasks=True)fig.show()" }, { "code": null, "e": 15124, "s": 15069, "text": "We can see our interactive Gantt chart rendered below." }, { "code": null, "e": 15632, "s": 15124, "text": "This production schedule can be exported wherever we need it to be, and we can select on-screen areas we want to dive deeper into. We can also note now visually that we can batch ferment in our large fermentor and prepare filters for purification at the same time because we have enough operators available and purification requires both of those tasks to be complete to proceed, however preparing vials and adding adjuvants cannot proceed at the same time due to a shortage of operator resources available." }, { "code": null, "e": 15805, "s": 15632, "text": "What if we want to gather some statistics for our data, such as resource utilization? All of this data is captured in our loading data frame and is available for reporting." }, { "code": null, "e": 15824, "s": 15805, "text": "loading.describe()" }, { "code": null, "e": 16256, "s": 15824, "text": "Using the Pandas describe() function, we can see the maximum resource utilization available. This is extremely useful for determining the answer the right amount of resources needed to get the job done. We see we have maxed out at least for a short period our number of operators available. If we had four available, we’d be able to complete our adding adjuvants and prepare vials at the same time and complete our process earlier." }, { "code": null, "e": 16314, "s": 16256, "text": "fig = px.line(loading, x=\"index\", y=\"Operator\")fig.show()" }, { "code": null, "e": 17205, "s": 16314, "text": "The case study we worked together on here is relatively small in scope compared to the real-manufacturing-floor batches which can contain hundreds of tasks and dozens of resources to load. This data can add up quickly and can vary from industry to industry. However, our code is scalable and can handle these dependencies albeit at the cost of more extensive processing time. Some areas for improvement to our algorithm also include capabilities seen in other project management suites such as delayed starts, inventory tracking and batching, and adding/tracking delays. We can also supplement our data at a later point and add further requirements or even bills of materials or costs to our work, to develop secondary objective functions and for further visualization. Because we developed our visuals within Plotly, we can also use enterprise data hosting or make our own Dash dashboards." } ]
How To Change The Column Names Of PySpark DataFrames | Towards Data Science
In today’s short guide we will discuss 4 ways for changing the name of columns in a Spark DataFrame. Specifically, we are going to explore how to do so using: selectExpr() method withColumnRenamed() method toDF() method alias Spark Session and Spark SQL and rename one or more columns at a time. First, let’s create an example PySpark DataFrame that we’ll reference throughout this guide to demonstrate a few concepts. >>> from pyspark.sql import SparkSession# Create an instance of spark session>>> spark_session = SparkSession.builder \ .master('local[1]') \ .appName('Example') \ .getOrCreate()>>> df = spark_session.createDataFrame( [ (1, 'a', True, 1.0), (2, 'b', False, 2.0), (3, 'c', False, 3.0), (4, 'd', True, 4.0), ], ['colA', 'colB', 'colC', 'colD'])>>> df.show()+----+----+-----+----+ |colA|colB| colC|colD|+----+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+----+----+-----+----+>>> df.printSchema()root |-- colA: long (nullable = true) |-- colB: string (nullable = true) |-- colC: boolean (nullable = true) |-- colD: double (nullable = true) The first option you have is pyspark.sql.DataFrame.selectExpr() method which is a variant of select() method that accepts SQL expressions. >>> df = df.selectExpr( 'colA AS A', 'colB AS B', 'colC AS C', 'colD AS D',)>>> df.show()+---+---+-----+---+| A| B| C| D|+---+---+-----+---+| 1| a| true|1.0|| 2| b|false|2.0|| 3| c|false|3.0|| 4| d| true|4.0|+---+---+-----+---+ Note however that this approach is mostly suitable when you need to rename most of the columns and when you also have to deal with a relatively small number of columns. At this point, you may also want to recall the difference between select() and selectExpr() in Spark: towardsdatascience.com The second option you have when it comes to rename columns of PySpark DataFrames is the pyspark.sql.DataFrame.withColumnRenamed(). This method returns a new DataFrame by renaming an existing column. >>> df = df.withColumnRenamed('colA', 'A')>>> df.show()+---+----+-----+----+| A|colB| colC|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+ This method is mostly suitable when you need to rename one column at a time. If you need to rename multiple columns in one go then other methods discussed in this article will be more helpful. pyspark.sql.DataFrame.toDF() method returns a new DataFrame with the new specified column names. >>> df = df.toDF('A', 'colB', 'C', 'colD')>>> df.show()+---+----+-----+----+| A|colB| C|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+ This method is useful when you need to rename more than one columns at the same time. Note that if you have a list containing the new column names then the following should do the trick as well: >>> new_col_names = ['A', 'colB', 'C', 'colD']>>> df = df.toDF(*new_col_names) Another option we have is the use of alias method that returns a new DataFrame with an alias set. >>> from pyspark.sql.functions import col>>> df = df.select( col('colA').alias('A'), col('colB'), col('colC').alias('C'), col('colD'))>>> df.show()+---+----+-----+----+| A|colB| C|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+ Again this method should be used when multiple columns need to be renamed and when you don’t have to deal with numerous columns, otherwise this could get really verbose. Finally, you can rename columns using Spark SQL using the traditional SQL syntax for DataFrames that were stored as tables. For example, >>> df.createOrReplaceTempView('test_table')>>> df = spark_session.sql( 'SELECT colA AS A, colB, colC AS C, colD FROM test_table')>>> df.show()+---+----+-----+----+| A|colB| C|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+ In today’s short guide we discussed how to rename columns of PySpark DataFrames in many different ways. Depending on whether you need to rename one or multiple columns, you have to choose the method which is most suitable for your specific use case. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read.
[ { "code": null, "e": 331, "s": 172, "text": "In today’s short guide we will discuss 4 ways for changing the name of columns in a Spark DataFrame. Specifically, we are going to explore how to do so using:" }, { "code": null, "e": 351, "s": 331, "text": "selectExpr() method" }, { "code": null, "e": 378, "s": 351, "text": "withColumnRenamed() method" }, { "code": null, "e": 392, "s": 378, "text": "toDF() method" }, { "code": null, "e": 398, "s": 392, "text": "alias" }, { "code": null, "e": 426, "s": 398, "text": "Spark Session and Spark SQL" }, { "code": null, "e": 468, "s": 426, "text": "and rename one or more columns at a time." }, { "code": null, "e": 591, "s": 468, "text": "First, let’s create an example PySpark DataFrame that we’ll reference throughout this guide to demonstrate a few concepts." }, { "code": null, "e": 1386, "s": 591, "text": ">>> from pyspark.sql import SparkSession# Create an instance of spark session>>> spark_session = SparkSession.builder \\ .master('local[1]') \\ .appName('Example') \\ .getOrCreate()>>> df = spark_session.createDataFrame( [ (1, 'a', True, 1.0), (2, 'b', False, 2.0), (3, 'c', False, 3.0), (4, 'd', True, 4.0), ], ['colA', 'colB', 'colC', 'colD'])>>> df.show()+----+----+-----+----+ |colA|colB| colC|colD|+----+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+----+----+-----+----+>>> df.printSchema()root |-- colA: long (nullable = true) |-- colB: string (nullable = true) |-- colC: boolean (nullable = true) |-- colD: double (nullable = true)" }, { "code": null, "e": 1525, "s": 1386, "text": "The first option you have is pyspark.sql.DataFrame.selectExpr() method which is a variant of select() method that accepts SQL expressions." }, { "code": null, "e": 1780, "s": 1525, "text": ">>> df = df.selectExpr( 'colA AS A', 'colB AS B', 'colC AS C', 'colD AS D',)>>> df.show()+---+---+-----+---+| A| B| C| D|+---+---+-----+---+| 1| a| true|1.0|| 2| b|false|2.0|| 3| c|false|3.0|| 4| d| true|4.0|+---+---+-----+---+" }, { "code": null, "e": 1949, "s": 1780, "text": "Note however that this approach is mostly suitable when you need to rename most of the columns and when you also have to deal with a relatively small number of columns." }, { "code": null, "e": 2051, "s": 1949, "text": "At this point, you may also want to recall the difference between select() and selectExpr() in Spark:" }, { "code": null, "e": 2074, "s": 2051, "text": "towardsdatascience.com" }, { "code": null, "e": 2273, "s": 2074, "text": "The second option you have when it comes to rename columns of PySpark DataFrames is the pyspark.sql.DataFrame.withColumnRenamed(). This method returns a new DataFrame by renaming an existing column." }, { "code": null, "e": 2497, "s": 2273, "text": ">>> df = df.withColumnRenamed('colA', 'A')>>> df.show()+---+----+-----+----+| A|colB| colC|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+" }, { "code": null, "e": 2690, "s": 2497, "text": "This method is mostly suitable when you need to rename one column at a time. If you need to rename multiple columns in one go then other methods discussed in this article will be more helpful." }, { "code": null, "e": 2787, "s": 2690, "text": "pyspark.sql.DataFrame.toDF() method returns a new DataFrame with the new specified column names." }, { "code": null, "e": 3011, "s": 2787, "text": ">>> df = df.toDF('A', 'colB', 'C', 'colD')>>> df.show()+---+----+-----+----+| A|colB| C|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+" }, { "code": null, "e": 3097, "s": 3011, "text": "This method is useful when you need to rename more than one columns at the same time." }, { "code": null, "e": 3206, "s": 3097, "text": "Note that if you have a list containing the new column names then the following should do the trick as well:" }, { "code": null, "e": 3285, "s": 3206, "text": ">>> new_col_names = ['A', 'colB', 'C', 'colD']>>> df = df.toDF(*new_col_names)" }, { "code": null, "e": 3383, "s": 3285, "text": "Another option we have is the use of alias method that returns a new DataFrame with an alias set." }, { "code": null, "e": 3712, "s": 3383, "text": ">>> from pyspark.sql.functions import col>>> df = df.select( col('colA').alias('A'), col('colB'), col('colC').alias('C'), col('colD'))>>> df.show()+---+----+-----+----+| A|colB| C|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+" }, { "code": null, "e": 3882, "s": 3712, "text": "Again this method should be used when multiple columns need to be renamed and when you don’t have to deal with numerous columns, otherwise this could get really verbose." }, { "code": null, "e": 4019, "s": 3882, "text": "Finally, you can rename columns using Spark SQL using the traditional SQL syntax for DataFrames that were stored as tables. For example," }, { "code": null, "e": 4334, "s": 4019, "text": ">>> df.createOrReplaceTempView('test_table')>>> df = spark_session.sql( 'SELECT colA AS A, colB, colC AS C, colD FROM test_table')>>> df.show()+---+----+-----+----+| A|colB| C|colD|+---+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+---+----+-----+----+" }, { "code": null, "e": 4584, "s": 4334, "text": "In today’s short guide we discussed how to rename columns of PySpark DataFrames in many different ways. Depending on whether you need to rename one or multiple columns, you have to choose the method which is most suitable for your specific use case." } ]