title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
C qsort() vs C++ sort() - GeeksforGeeks | 14 Aug, 2018
Standard C library provides qsort function that can be used for sorting an array. Following is the prototype of qsort() function.
// Sort an array of any type. The parameters are, base
// address of array, size of array and pointer to
// comparator function
void qsort (void* base, size_t num, size_t size,
int (*comparator)(const void*, const void*));
It requires a pointer to the array, the number of elements in the array, the size of each element and a comparator function. We have discussed qsort comparator in detail here.
C++ Standard Library provides a similar function sort() that originated in the STL. We have discussed C++ sort here. Following are prototypes of C++ sort() function.
// To sort in default or ascending order.
template
void sort(T first, T last);
// To sort according to the order specified
// by comp.
template
void sort(T first, T last, Compare comp);
The order of equal elements is not guaranteed to be preserved. C++ provides std::stable_sort that can be used to preserve order.
Comparison to qsort and sort()1. Implementation details:As the name suggests, qsort function uses QuickSort algorithm to sort the given array, although the C standard does not require it to implement quicksort.
C++ sort function uses introsort which is a hybrid algorithm. Different implementations use different algorithms. The GNU Standard C++ library, for example, uses a 3-part hybrid sorting algorithm: introsort is performed first (introsort itself being a hybrid of quicksort and heap sort) followed by an insertion sort on the result.
2. Complexity :The C standard doesn’t talk about its complexity of qsort. The new C++11 standard requires that the complexity of sort to be O(Nlog(N)) in the worst case. Previous versions of C++ such as C++03 allow possible worst case scenario of O(N^2). Only average complexity was required to be O(N log N).
3. Running time:STL’s sort ran faster than C’s qsort, because C++’s templates generate optimized code for a particular data type and a particular comparison function.
STL’s sort runs 20% to 50% faster than the hand-coded quicksort and 250% to 1000% faster than the C qsort library function. C might be the fastest language but qsort is very slow.
When we tried to sort one million integers on C++14, Time taken by C qsort() was 0.247883 sec and time taken by C++ sort() was only 0.086125 sec
// C++ program to demonstrate performance of// C qsort and C++ sort() algorithm#include <bits/stdc++.h>using namespace std; // Number of elements to be sorted#define N 1000000 // A comparator function used by qsortint compare(const void * a, const void * b){ return ( *(int*)a - *(int*)b );} // Driver program to test above functionsint main(){ int arr[N], dupArr[N]; // seed for random input srand(time(NULL)); // to measure time taken by qsort and sort clock_t begin, end; double time_spent; // generate random input for (int i = 0; i < N; i++) dupArr[i] = arr[i] = rand()%100000; begin = clock(); qsort(arr, N, sizeof(int), compare); end = clock(); // calculate time taken by C qsort function time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout << "Time taken by C qsort() - " << time_spent << endl; time_spent = 0.0; begin = clock(); sort(dupArr, dupArr + N); end = clock(); // calculate time taken by C++ sort time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout << "Time taken by C++ sort() - " << time_spent << endl; return 0;}
Output :
Time taken by C qsort() - 0.247883
Time taken by C++ sort() - 0.086125
C++ sort() is blazingly faster than qsort() on equivalent data due to inlining. sort() on a container of integers will be compiled to use std::less::operator() by default, which will be inlined and sort() will be comparing the integers directly. On the other hand, qsort() will be making an indirect call through a function pointer for every comparison which compilers fails to optimize.
4. Flexibility:STL’s sort works for all data types and for different data containers like C arrays, C++ vectors, C++ deques, etc and other containers that can be written by the user. This kind of flexibility is rather difficult to achieve in C.
5. Safety:Compared to qsort, the templated sort is more type-safe since it does not require access to data items through unsafe void pointers, as qsort does.
References:http://theory.stanford.edu/~amitp/rants/c++-vs-chttps://en.wikipedia.org/wiki/Sort_(C%2B%2B)
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
CPP-Library
Quick Sort
C Language
C++
Competitive Programming
Sorting
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25557,
"s": 25529,
"text": "\n14 Aug, 2018"
},
{
"code": null,
"e": 25687,
"s": 25557,
"text": "Standard C library provides qsort function that can be used for sorting an array. Following is the prototype of qsort() function."
},
{
"code": null,
"e": 25923,
"s": 25687,
"text": "// Sort an array of any type. The parameters are, base\n// address of array, size of array and pointer to\n// comparator function\nvoid qsort (void* base, size_t num, size_t size, \n int (*comparator)(const void*, const void*));"
},
{
"code": null,
"e": 26099,
"s": 25923,
"text": "It requires a pointer to the array, the number of elements in the array, the size of each element and a comparator function. We have discussed qsort comparator in detail here."
},
{
"code": null,
"e": 26265,
"s": 26099,
"text": "C++ Standard Library provides a similar function sort() that originated in the STL. We have discussed C++ sort here. Following are prototypes of C++ sort() function."
},
{
"code": null,
"e": 26454,
"s": 26265,
"text": "// To sort in default or ascending order.\ntemplate \nvoid sort(T first, T last);\n\n// To sort according to the order specified\n// by comp.\ntemplate\nvoid sort(T first, T last, Compare comp);\n"
},
{
"code": null,
"e": 26583,
"s": 26454,
"text": "The order of equal elements is not guaranteed to be preserved. C++ provides std::stable_sort that can be used to preserve order."
},
{
"code": null,
"e": 26794,
"s": 26583,
"text": "Comparison to qsort and sort()1. Implementation details:As the name suggests, qsort function uses QuickSort algorithm to sort the given array, although the C standard does not require it to implement quicksort."
},
{
"code": null,
"e": 27126,
"s": 26794,
"text": "C++ sort function uses introsort which is a hybrid algorithm. Different implementations use different algorithms. The GNU Standard C++ library, for example, uses a 3-part hybrid sorting algorithm: introsort is performed first (introsort itself being a hybrid of quicksort and heap sort) followed by an insertion sort on the result."
},
{
"code": null,
"e": 27436,
"s": 27126,
"text": "2. Complexity :The C standard doesn’t talk about its complexity of qsort. The new C++11 standard requires that the complexity of sort to be O(Nlog(N)) in the worst case. Previous versions of C++ such as C++03 allow possible worst case scenario of O(N^2). Only average complexity was required to be O(N log N)."
},
{
"code": null,
"e": 27603,
"s": 27436,
"text": "3. Running time:STL’s sort ran faster than C’s qsort, because C++’s templates generate optimized code for a particular data type and a particular comparison function."
},
{
"code": null,
"e": 27783,
"s": 27603,
"text": "STL’s sort runs 20% to 50% faster than the hand-coded quicksort and 250% to 1000% faster than the C qsort library function. C might be the fastest language but qsort is very slow."
},
{
"code": null,
"e": 27928,
"s": 27783,
"text": "When we tried to sort one million integers on C++14, Time taken by C qsort() was 0.247883 sec and time taken by C++ sort() was only 0.086125 sec"
},
{
"code": "// C++ program to demonstrate performance of// C qsort and C++ sort() algorithm#include <bits/stdc++.h>using namespace std; // Number of elements to be sorted#define N 1000000 // A comparator function used by qsortint compare(const void * a, const void * b){ return ( *(int*)a - *(int*)b );} // Driver program to test above functionsint main(){ int arr[N], dupArr[N]; // seed for random input srand(time(NULL)); // to measure time taken by qsort and sort clock_t begin, end; double time_spent; // generate random input for (int i = 0; i < N; i++) dupArr[i] = arr[i] = rand()%100000; begin = clock(); qsort(arr, N, sizeof(int), compare); end = clock(); // calculate time taken by C qsort function time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout << \"Time taken by C qsort() - \" << time_spent << endl; time_spent = 0.0; begin = clock(); sort(dupArr, dupArr + N); end = clock(); // calculate time taken by C++ sort time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout << \"Time taken by C++ sort() - \" << time_spent << endl; return 0;}",
"e": 29091,
"s": 27928,
"text": null
},
{
"code": null,
"e": 29100,
"s": 29091,
"text": "Output :"
},
{
"code": null,
"e": 29172,
"s": 29100,
"text": "Time taken by C qsort() - 0.247883\nTime taken by C++ sort() - 0.086125 "
},
{
"code": null,
"e": 29560,
"s": 29172,
"text": "C++ sort() is blazingly faster than qsort() on equivalent data due to inlining. sort() on a container of integers will be compiled to use std::less::operator() by default, which will be inlined and sort() will be comparing the integers directly. On the other hand, qsort() will be making an indirect call through a function pointer for every comparison which compilers fails to optimize."
},
{
"code": null,
"e": 29805,
"s": 29560,
"text": "4. Flexibility:STL’s sort works for all data types and for different data containers like C arrays, C++ vectors, C++ deques, etc and other containers that can be written by the user. This kind of flexibility is rather difficult to achieve in C."
},
{
"code": null,
"e": 29963,
"s": 29805,
"text": "5. Safety:Compared to qsort, the templated sort is more type-safe since it does not require access to data items through unsafe void pointers, as qsort does."
},
{
"code": null,
"e": 30067,
"s": 29963,
"text": "References:http://theory.stanford.edu/~amitp/rants/c++-vs-chttps://en.wikipedia.org/wiki/Sort_(C%2B%2B)"
},
{
"code": null,
"e": 30332,
"s": 30067,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30456,
"s": 30332,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 30468,
"s": 30456,
"text": "CPP-Library"
},
{
"code": null,
"e": 30479,
"s": 30468,
"text": "Quick Sort"
},
{
"code": null,
"e": 30490,
"s": 30479,
"text": "C Language"
},
{
"code": null,
"e": 30494,
"s": 30490,
"text": "C++"
},
{
"code": null,
"e": 30518,
"s": 30494,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30526,
"s": 30518,
"text": "Sorting"
},
{
"code": null,
"e": 30534,
"s": 30526,
"text": "Sorting"
},
{
"code": null,
"e": 30538,
"s": 30534,
"text": "CPP"
},
{
"code": null,
"e": 30636,
"s": 30538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30674,
"s": 30636,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 30700,
"s": 30674,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 30720,
"s": 30700,
"text": "Multithreading in C"
},
{
"code": null,
"e": 30742,
"s": 30720,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 30783,
"s": 30742,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30801,
"s": 30783,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 30820,
"s": 30801,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30866,
"s": 30820,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30909,
"s": 30866,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Number of substrings with count of each character as k - GeeksforGeeks | 21 Feb, 2022
Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times.
Examples:
Input : s = "aabbcc"
k = 2
Output : 6
The substrings are aa, bb, cc,
aabb, bbcc and aabbcc.
Input : s = "aabccc"
k = 2
Output : 3
There are three substrings aa,
cc and cc
The idea is to traverse through all substrings. We fix a starting point, traverse through all substrings starting with the picked point, we keep incrementing frequencies of all characters. If all frequencies become k, we increment the result. If the count of any frequency becomes more than k, we break and change starting point.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of substrings// with counts of distinct characters as k.#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.bool check(int freq[], int k){ for (int i = 0; i < MAX_CHAR; i++) if (freq[i] && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kint substrings(string s, int k){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; s[i]; i++) { // Initialize all frequencies as 0 // for this starting point int freq[MAX_CHAR] = { 0 }; // One by one pick ending points for (int j = i; s[j]; j++) { // Increment frequency of current char int index = s[j] - 'a'; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codeint main(){ string s = "aabbcc"; int k = 2; cout << substrings(s, k) << endl; s = "aabbc"; k = 2; cout << substrings(s, k) << endl;}
// Java program to count number of substrings// with counts of distinct characters as k.class GFG{ static int MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.static boolean check(int freq[], int k){ for (int i = 0; i < MAX_CHAR; i++) if (freq[i] !=0 && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kstatic int substrings(String s, int k){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; i< s.length(); i++) { // Initialize all frequencies as 0 // for this starting point int freq[] = new int[MAX_CHAR]; // One by one pick ending points for (int j = i; j<s.length(); j++) { // Increment frequency of current char int index = s.charAt(j) - 'a'; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codepublic static void main(String[] args){ String s = "aabbcc"; int k = 2; System.out.println(substrings(s, k)); s = "aabbc"; k = 2; System.out.println(substrings(s, k));}} // This code has been contributed by 29AjayKumar
# Python3 program to count number of substrings# with counts of distinct characters as k. MAX_CHAR = 26 # Returns true if all values# in freq[] are either 0 or k.def check(freq, k): for i in range(0, MAX_CHAR): if(freq[i] and freq[i] != k): return False return True # Returns count of substrings where# frequency of every present character is kdef substrings(s, k): res = 0 # Initialize result # Pick a starting point for i in range(0, len(s)): # Initialize all frequencies as 0 # for this starting point freq = [0] * MAX_CHAR # One by one pick ending points for j in range(i, len(s)): # Increment frequency of current char index = ord(s[j]) - ord('a') freq[index] += 1 # If frequency becomes more than # k, we can't have more substrings # starting with i if(freq[index] > k): break # If frequency becomes k, then check # other frequencies as well elif(freq[index] == k and check(freq, k) == True): res += 1 return res # Driver Codeif __name__ == "__main__": s = "aabbcc" k = 2 print(substrings(s, k)) s = "aabbc"; k = 2; print(substrings(s, k)) # This code is contributed# by Sairahul Jella
// C# program to count number of substrings// with counts of distinct characters as k.using System; class GFG{ static int MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.static bool check(int []freq, int k){ for (int i = 0; i < MAX_CHAR; i++) if (freq[i] != 0 && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kstatic int substrings(String s, int k){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; i < s.Length; i++) { // Initialize all frequencies as 0 // for this starting point int []freq = new int[MAX_CHAR]; // One by one pick ending points for (int j = i; j < s.Length; j++) { // Increment frequency of current char int index = s[j] - 'a'; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codepublic static void Main(String[] args){ String s = "aabbcc"; int k = 2; Console.WriteLine(substrings(s, k)); s = "aabbc"; k = 2; Console.WriteLine(substrings(s, k));}} /* This code contributed by PrinciRaj1992 */
<?php // PHP program to count number of substrings// with counts of distinct characters as k.$MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.function check(&$freq, $k){ global $MAX_CHAR; for ($i = 0; $i < $MAX_CHAR; $i++) if ($freq[$i] && $freq[$i] != $k) return false; return true;} // Returns count of substrings where frequency// of every present character is kfunction substrings($s, $k){ global $MAX_CHAR; $res = 0; // Initialize result // Pick a starting point for ($i = 0; $i < strlen($s); $i++) { // Initialize all frequencies as 0 // for this starting point $freq = array_fill(0, $MAX_CHAR,NULL); // One by one pick ending points for ($j = $i; $j < strlen($s); $j++) { // Increment frequency of current char $index = ord($s[$j]) - ord('a'); $freq[$index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if ($freq[$index] > $k) break; // If frequency becomes k, then check // other frequencies as well. else if ($freq[$index] == $k && check($freq, $k) == true) $res++; } } return $res;} // Driver code$s = "aabbcc";$k = 2;echo substrings($s, $k)."\n";$s = "aabbc";$k = 2;echo substrings($s, $k)."\n"; // This code is contributed by Ita_c.?>
<script> // Javascript program to count number of// substrings with counts of distinct// characters as k.let MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.function check(freq,k){ for(let i = 0; i < MAX_CHAR; i++) if (freq[i] != 0 && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kfunction substrings(s, k){ // Initialize result let res = 0; // Pick a starting point for(let i = 0; i< s.length; i++) { // Initialize all frequencies as 0 // for this starting point let freq = new Array(MAX_CHAR); for(let i = 0; i < freq.length ;i++) { freq[i] = 0; } // One by one pick ending points for(let j = i; j < s.length; j++) { // Increment frequency of current char let index = s[j].charCodeAt(0) - 'a'.charCodeAt(0); freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codelet s = "aabbcc";let k = 2;document.write(substrings(s, k) + "<br>"); s = "aabbc";k = 2;document.write(substrings(s, k) + "<br>"); // This code is contributed by avanitrachhadiya2155 </script>
6
3
Time Complexity: O(n*n) where n is the length of input string. Function Check() is running a loop of constant length from 0 to MAX_CHAR (ie; 26 always) so this function check() is running in O(MAX_CHAR) time so Time complexity is O(MAX_CHAR*n*n)=O(n^2).
On very careful observation, we can see that it is enough to check the same for substrings of length where is the number of distinct characters present in the given string.
Consider a substring S_{i+1}S_{i+2}\dots S_{i+p} of length ‘p’. If this substring has ‘m’ distinct characters and each distinct character occurs exactly ‘K’ times, then the length of the substring, ‘p’, is given by p = K\times m. Since ‘‘ is always a multiple of ‘K’ and for the given string, it is enough to iterate over the substrings whose length is divisible by ‘K’ and having m, 1 \le m \le 26 distinct characters. We will use Sliding window to iterate over the substrings of fixed length.
Find the number of distinct characters present in the given string. Let it be D.
For each i, 1\le i\le D, do the followingIterate over the substrings of length $i \times K$, using a sliding window.Check if they satisfy the condition – All distinct characters in the substring occur exactly K times.If they satisfy the condition, increment the count.
Iterate over the substrings of length $i \times K$, using a sliding window.
Check if they satisfy the condition – All distinct characters in the substring occur exactly K times.
If they satisfy the condition, increment the count.
C++
C
Java
Python3
C#
Javascript
#include <iostream>#include <map>#include <set>#include <string> int min(int a, int b) { return a < b ? a : b; } using namespace std; bool have_same_frequency(map<char, int>& freq, int k){ for (auto& pair : freq) { if (pair.second != k && pair.second != 0) { return false; } } return true;} int count_substrings(string s, int k){ int count = 0; int distinct = (set<char>(s.begin(), s.end())).size(); for (int length = 1; length <= distinct; length++) { int window_length = length * k; map<char, int> freq; int window_start = 0; int window_end = window_start + window_length - 1; for (int i = window_start; i <= min(window_end, s.length() - 1); i++) { freq[s[i]]++; } while (window_end < s.length()) { if (have_same_frequency(freq, k)) { count++; } freq[s[window_start]]--; window_start++; window_end++; if (window_length < s.length()) { freq[s[window_end]]++; } } } return count;} int main(){ string s = "aabbcc"; int k = 2; cout << count_substrings(s, k) << endl; s = "aabbc"; k = 2; cout << count_substrings(s, k) << endl; return 0;}
#include <stdbool.h>#include <stdio.h>#include <string.h> int min(int a, int b) { return a < b ? a : b; } bool have_same_frequency(int freq[], int k){ for (int i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true;} int count_substrings(char* s, int n, int k){ int count = 0; int distinct = 0; bool have[26] = { false }; for (int i = 0; i < n; i++) { have[s[i] - 'a'] = true; } for (int i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for (int length = 1; length <= distinct; length++) { int window_length = length * k; int freq[26] = { 0 }; int window_start = 0; int window_end = window_start + window_length - 1; for (int i = window_start; i <= min(window_end, n - 1); i++) { freq[s[i] - 'a']++; } while (window_end < n) { if (have_same_frequency(freq, k)) { count++; } freq[s[window_start] - 'a']--; window_start++; window_end++; if (window_end < n) { freq[s[window_end] - 'a']++; } } } return count;} int main(){ char* s = "aabbcc"; int k = 2; printf("%d\n", count_substrings(s, 6, k)); s = "aabbc"; k = 2; printf("%d\n", count_substrings(s, 5, k)); return 0;}
import java.util.*; class GFG { static boolean have_same_frequency(int[] freq, int k) { for (int i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true; } static int count_substrings(String s, int k) { int count = 0; int distinct = 0; boolean[] have = new boolean[26]; Arrays.fill(have, false); for (int i = 0; i < s.length(); i++) { have[((int)(s.charAt(i) - 'a'))] = true; } for (int i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for (int length = 1; length <= distinct; length++) { int window_length = length * k; int[] freq = new int[26]; Arrays.fill(freq, 0); int window_start = 0; int window_end = window_start + window_length - 1; for (int i = window_start; i <= Math.min(window_end, s.length() - 1); i++) { freq[((int)(s.charAt(i) - 'a'))]++; } while (window_end < s.length()) { if (have_same_frequency(freq, k)) { count++; } freq[( (int)(s.charAt(window_start) - 'a'))]--; window_start++; window_end++; if (window_end < s.length()) { freq[((int)(s.charAt(window_end) - 'a'))]++; } } } return count; } public static void main(String[] args) { String s = "aabbcc"; int k = 2; System.out.println(count_substrings(s, k)); s = "aabbc"; k = 2; System.out.println(count_substrings(s, k)); }}
from collections import defaultdict def have_same_frequency(freq: defaultdict, k: int): return all([freq[i] == k or freq[i] == 0 for i in freq]) def count_substrings(s: str, k: int) -> int: count = 0 distinct = len(set([i for i in s])) for length in range(1, distinct + 1): window_length = length * k freq = defaultdict(int) window_start = 0 window_end = window_start + window_length - 1 for i in range(window_start, min(window_end + 1, len(s))): freq[s[i]] += 1 while window_end < len(s): if have_same_frequency(freq, k): count += 1 freq[s[window_start]] -= 1 window_start += 1 window_end += 1 if window_end < len(s): freq[s[window_end]] += 1 return count if __name__ == '__main__': s = "aabbcc" k = 2 print(count_substrings(s, k)) s = "aabbc" k = 2 print(count_substrings(s, k))
using System; class GFG{ static bool have_same_frequency(int[] freq, int k){ for(int i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true;} static int count_substrings(string s, int k){ int count = 0; int distinct = 0; bool[] have = new bool[26]; Array.Fill(have, false); for(int i = 0; i < s.Length; i++) { have[((int)(s[i] - 'a'))] = true; } for(int i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for(int length = 1; length <= distinct; length++) { int window_length = length * k; int[] freq = new int[26]; Array.Fill(freq, 0); int window_start = 0; int window_end = window_start + window_length - 1; for(int i = window_start; i <= Math.Min(window_end, s.Length - 1); i++) { freq[((int)(s[i] - 'a'))]++; } while (window_end < s.Length) { if (have_same_frequency(freq, k)) { count++; } freq[((int)(s[window_start] - 'a'))]--; window_start++; window_end++; if (window_end < s.Length) { freq[((int)(s[window_end] - 'a'))]++; } } } return count;} // Driver codepublic static void Main(string[] args){ string s = "aabbcc"; int k = 2; Console.WriteLine(count_substrings(s, k)); s = "aabbc"; k = 2; Console.WriteLine(count_substrings(s, k));}} // This code is contributed by gaurav01
<script> function have_same_frequency(freq,k){ for (let i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true;} function count_substrings(s,k){ let count = 0; let distinct = 0; let have = new Array(26); for(let i=0;i<26;i++) { have[i]=false; } for (let i = 0; i < s.length; i++) { have[((s[i].charCodeAt(0) - 'a'.charCodeAt(0)))] = true; } for (let i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for (let length = 1; length <= distinct; length++) { let window_length = length * k; let freq = new Array(26); for(let i=0;i<26;i++) freq[i]=0; let window_start = 0; let window_end = window_start + window_length - 1; for (let i = window_start; i <= Math.min(window_end, s.length - 1); i++) { freq[((s[i].charCodeAt(0) - 'a'.charCodeAt(0)))]++; } while (window_end < s.length) { if (have_same_frequency(freq, k)) { count++; } freq[( (s[window_start].charCodeAt(0) - 'a'.charCodeAt(0)))]--; window_start++; window_end++; if (window_end < s.length) { freq[(s[window_end].charCodeAt(0) - 'a'.charCodeAt(0))]++; } } } return count;} let s = "aabbcc";let k = 2;document.write(count_substrings(s, k)+"<br>");s = "aabbc";k = 2;document.write(count_substrings(s, k)+"<br>"); // This code is contributed by rag2127 </script>
6
3
Time Complexity: O(N * D) where D is the number of distinct characters present in the string and N is the length of the string.
This article is contributed by Rahul Chawla. 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.
Sairahul Jella
ukasp
29AjayKumar
princiraj1992
gaveesh
avanitrachhadiya2155
suman_1729
rag2127
gaurav01
rajatkumargla19
varshagumber28
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Check whether two strings are anagram of each other
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters | [
{
"code": null,
"e": 26731,
"s": 26703,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 26856,
"s": 26731,
"text": "Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times. "
},
{
"code": null,
"e": 26867,
"s": 26856,
"text": "Examples: "
},
{
"code": null,
"e": 27057,
"s": 26867,
"text": "Input : s = \"aabbcc\"\n k = 2 \nOutput : 6\nThe substrings are aa, bb, cc,\naabb, bbcc and aabbcc.\n\nInput : s = \"aabccc\"\n k = 2\nOutput : 3\nThere are three substrings aa, \ncc and cc"
},
{
"code": null,
"e": 27388,
"s": 27057,
"text": "The idea is to traverse through all substrings. We fix a starting point, traverse through all substrings starting with the picked point, we keep incrementing frequencies of all characters. If all frequencies become k, we increment the result. If the count of any frequency becomes more than k, we break and change starting point. "
},
{
"code": null,
"e": 27392,
"s": 27388,
"text": "C++"
},
{
"code": null,
"e": 27397,
"s": 27392,
"text": "Java"
},
{
"code": null,
"e": 27405,
"s": 27397,
"text": "Python3"
},
{
"code": null,
"e": 27408,
"s": 27405,
"text": "C#"
},
{
"code": null,
"e": 27412,
"s": 27408,
"text": "PHP"
},
{
"code": null,
"e": 27423,
"s": 27412,
"text": "Javascript"
},
{
"code": "// C++ program to count number of substrings// with counts of distinct characters as k.#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.bool check(int freq[], int k){ for (int i = 0; i < MAX_CHAR; i++) if (freq[i] && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kint substrings(string s, int k){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; s[i]; i++) { // Initialize all frequencies as 0 // for this starting point int freq[MAX_CHAR] = { 0 }; // One by one pick ending points for (int j = i; s[j]; j++) { // Increment frequency of current char int index = s[j] - 'a'; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codeint main(){ string s = \"aabbcc\"; int k = 2; cout << substrings(s, k) << endl; s = \"aabbc\"; k = 2; cout << substrings(s, k) << endl;}",
"e": 28867,
"s": 27423,
"text": null
},
{
"code": "// Java program to count number of substrings// with counts of distinct characters as k.class GFG{ static int MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.static boolean check(int freq[], int k){ for (int i = 0; i < MAX_CHAR; i++) if (freq[i] !=0 && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kstatic int substrings(String s, int k){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; i< s.length(); i++) { // Initialize all frequencies as 0 // for this starting point int freq[] = new int[MAX_CHAR]; // One by one pick ending points for (int j = i; j<s.length(); j++) { // Increment frequency of current char int index = s.charAt(j) - 'a'; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codepublic static void main(String[] args){ String s = \"aabbcc\"; int k = 2; System.out.println(substrings(s, k)); s = \"aabbc\"; k = 2; System.out.println(substrings(s, k));}} // This code has been contributed by 29AjayKumar",
"e": 30421,
"s": 28867,
"text": null
},
{
"code": "# Python3 program to count number of substrings# with counts of distinct characters as k. MAX_CHAR = 26 # Returns true if all values# in freq[] are either 0 or k.def check(freq, k): for i in range(0, MAX_CHAR): if(freq[i] and freq[i] != k): return False return True # Returns count of substrings where# frequency of every present character is kdef substrings(s, k): res = 0 # Initialize result # Pick a starting point for i in range(0, len(s)): # Initialize all frequencies as 0 # for this starting point freq = [0] * MAX_CHAR # One by one pick ending points for j in range(i, len(s)): # Increment frequency of current char index = ord(s[j]) - ord('a') freq[index] += 1 # If frequency becomes more than # k, we can't have more substrings # starting with i if(freq[index] > k): break # If frequency becomes k, then check # other frequencies as well elif(freq[index] == k and check(freq, k) == True): res += 1 return res # Driver Codeif __name__ == \"__main__\": s = \"aabbcc\" k = 2 print(substrings(s, k)) s = \"aabbc\"; k = 2; print(substrings(s, k)) # This code is contributed# by Sairahul Jella",
"e": 31802,
"s": 30421,
"text": null
},
{
"code": "// C# program to count number of substrings// with counts of distinct characters as k.using System; class GFG{ static int MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.static bool check(int []freq, int k){ for (int i = 0; i < MAX_CHAR; i++) if (freq[i] != 0 && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kstatic int substrings(String s, int k){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; i < s.Length; i++) { // Initialize all frequencies as 0 // for this starting point int []freq = new int[MAX_CHAR]; // One by one pick ending points for (int j = i; j < s.Length; j++) { // Increment frequency of current char int index = s[j] - 'a'; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codepublic static void Main(String[] args){ String s = \"aabbcc\"; int k = 2; Console.WriteLine(substrings(s, k)); s = \"aabbc\"; k = 2; Console.WriteLine(substrings(s, k));}} /* This code contributed by PrinciRaj1992 */",
"e": 33352,
"s": 31802,
"text": null
},
{
"code": "<?php // PHP program to count number of substrings// with counts of distinct characters as k.$MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.function check(&$freq, $k){ global $MAX_CHAR; for ($i = 0; $i < $MAX_CHAR; $i++) if ($freq[$i] && $freq[$i] != $k) return false; return true;} // Returns count of substrings where frequency// of every present character is kfunction substrings($s, $k){ global $MAX_CHAR; $res = 0; // Initialize result // Pick a starting point for ($i = 0; $i < strlen($s); $i++) { // Initialize all frequencies as 0 // for this starting point $freq = array_fill(0, $MAX_CHAR,NULL); // One by one pick ending points for ($j = $i; $j < strlen($s); $j++) { // Increment frequency of current char $index = ord($s[$j]) - ord('a'); $freq[$index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if ($freq[$index] > $k) break; // If frequency becomes k, then check // other frequencies as well. else if ($freq[$index] == $k && check($freq, $k) == true) $res++; } } return $res;} // Driver code$s = \"aabbcc\";$k = 2;echo substrings($s, $k).\"\\n\";$s = \"aabbc\";$k = 2;echo substrings($s, $k).\"\\n\"; // This code is contributed by Ita_c.?>",
"e": 34831,
"s": 33352,
"text": null
},
{
"code": "<script> // Javascript program to count number of// substrings with counts of distinct// characters as k.let MAX_CHAR = 26; // Returns true if all values// in freq[] are either 0 or k.function check(freq,k){ for(let i = 0; i < MAX_CHAR; i++) if (freq[i] != 0 && freq[i] != k) return false; return true;} // Returns count of substrings where frequency// of every present character is kfunction substrings(s, k){ // Initialize result let res = 0; // Pick a starting point for(let i = 0; i< s.length; i++) { // Initialize all frequencies as 0 // for this starting point let freq = new Array(MAX_CHAR); for(let i = 0; i < freq.length ;i++) { freq[i] = 0; } // One by one pick ending points for(let j = i; j < s.length; j++) { // Increment frequency of current char let index = s[j].charCodeAt(0) - 'a'.charCodeAt(0); freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res;} // Driver codelet s = \"aabbcc\";let k = 2;document.write(substrings(s, k) + \"<br>\"); s = \"aabbc\";k = 2;document.write(substrings(s, k) + \"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 36494,
"s": 34831,
"text": null
},
{
"code": null,
"e": 36498,
"s": 36494,
"text": "6\n3"
},
{
"code": null,
"e": 36752,
"s": 36498,
"text": "Time Complexity: O(n*n) where n is the length of input string. Function Check() is running a loop of constant length from 0 to MAX_CHAR (ie; 26 always) so this function check() is running in O(MAX_CHAR) time so Time complexity is O(MAX_CHAR*n*n)=O(n^2)."
},
{
"code": null,
"e": 36927,
"s": 36752,
"text": "On very careful observation, we can see that it is enough to check the same for substrings of length where is the number of distinct characters present in the given string."
},
{
"code": null,
"e": 37423,
"s": 36927,
"text": "Consider a substring S_{i+1}S_{i+2}\\dots S_{i+p} of length ‘p’. If this substring has ‘m’ distinct characters and each distinct character occurs exactly ‘K’ times, then the length of the substring, ‘p’, is given by p = K\\times m. Since ‘‘ is always a multiple of ‘K’ and for the given string, it is enough to iterate over the substrings whose length is divisible by ‘K’ and having m, 1 \\le m \\le 26 distinct characters. We will use Sliding window to iterate over the substrings of fixed length."
},
{
"code": null,
"e": 37504,
"s": 37423,
"text": "Find the number of distinct characters present in the given string. Let it be D."
},
{
"code": null,
"e": 37773,
"s": 37504,
"text": "For each i, 1\\le i\\le D, do the followingIterate over the substrings of length $i \\times K$, using a sliding window.Check if they satisfy the condition – All distinct characters in the substring occur exactly K times.If they satisfy the condition, increment the count."
},
{
"code": null,
"e": 37849,
"s": 37773,
"text": "Iterate over the substrings of length $i \\times K$, using a sliding window."
},
{
"code": null,
"e": 37951,
"s": 37849,
"text": "Check if they satisfy the condition – All distinct characters in the substring occur exactly K times."
},
{
"code": null,
"e": 38003,
"s": 37951,
"text": "If they satisfy the condition, increment the count."
},
{
"code": null,
"e": 38007,
"s": 38003,
"text": "C++"
},
{
"code": null,
"e": 38009,
"s": 38007,
"text": "C"
},
{
"code": null,
"e": 38014,
"s": 38009,
"text": "Java"
},
{
"code": null,
"e": 38022,
"s": 38014,
"text": "Python3"
},
{
"code": null,
"e": 38025,
"s": 38022,
"text": "C#"
},
{
"code": null,
"e": 38036,
"s": 38025,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <map>#include <set>#include <string> int min(int a, int b) { return a < b ? a : b; } using namespace std; bool have_same_frequency(map<char, int>& freq, int k){ for (auto& pair : freq) { if (pair.second != k && pair.second != 0) { return false; } } return true;} int count_substrings(string s, int k){ int count = 0; int distinct = (set<char>(s.begin(), s.end())).size(); for (int length = 1; length <= distinct; length++) { int window_length = length * k; map<char, int> freq; int window_start = 0; int window_end = window_start + window_length - 1; for (int i = window_start; i <= min(window_end, s.length() - 1); i++) { freq[s[i]]++; } while (window_end < s.length()) { if (have_same_frequency(freq, k)) { count++; } freq[s[window_start]]--; window_start++; window_end++; if (window_length < s.length()) { freq[s[window_end]]++; } } } return count;} int main(){ string s = \"aabbcc\"; int k = 2; cout << count_substrings(s, k) << endl; s = \"aabbc\"; k = 2; cout << count_substrings(s, k) << endl; return 0;}",
"e": 39328,
"s": 38036,
"text": null
},
{
"code": "#include <stdbool.h>#include <stdio.h>#include <string.h> int min(int a, int b) { return a < b ? a : b; } bool have_same_frequency(int freq[], int k){ for (int i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true;} int count_substrings(char* s, int n, int k){ int count = 0; int distinct = 0; bool have[26] = { false }; for (int i = 0; i < n; i++) { have[s[i] - 'a'] = true; } for (int i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for (int length = 1; length <= distinct; length++) { int window_length = length * k; int freq[26] = { 0 }; int window_start = 0; int window_end = window_start + window_length - 1; for (int i = window_start; i <= min(window_end, n - 1); i++) { freq[s[i] - 'a']++; } while (window_end < n) { if (have_same_frequency(freq, k)) { count++; } freq[s[window_start] - 'a']--; window_start++; window_end++; if (window_end < n) { freq[s[window_end] - 'a']++; } } } return count;} int main(){ char* s = \"aabbcc\"; int k = 2; printf(\"%d\\n\", count_substrings(s, 6, k)); s = \"aabbc\"; k = 2; printf(\"%d\\n\", count_substrings(s, 5, k)); return 0;}",
"e": 40735,
"s": 39328,
"text": null
},
{
"code": "import java.util.*; class GFG { static boolean have_same_frequency(int[] freq, int k) { for (int i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true; } static int count_substrings(String s, int k) { int count = 0; int distinct = 0; boolean[] have = new boolean[26]; Arrays.fill(have, false); for (int i = 0; i < s.length(); i++) { have[((int)(s.charAt(i) - 'a'))] = true; } for (int i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for (int length = 1; length <= distinct; length++) { int window_length = length * k; int[] freq = new int[26]; Arrays.fill(freq, 0); int window_start = 0; int window_end = window_start + window_length - 1; for (int i = window_start; i <= Math.min(window_end, s.length() - 1); i++) { freq[((int)(s.charAt(i) - 'a'))]++; } while (window_end < s.length()) { if (have_same_frequency(freq, k)) { count++; } freq[( (int)(s.charAt(window_start) - 'a'))]--; window_start++; window_end++; if (window_end < s.length()) { freq[((int)(s.charAt(window_end) - 'a'))]++; } } } return count; } public static void main(String[] args) { String s = \"aabbcc\"; int k = 2; System.out.println(count_substrings(s, k)); s = \"aabbc\"; k = 2; System.out.println(count_substrings(s, k)); }}",
"e": 42577,
"s": 40735,
"text": null
},
{
"code": "from collections import defaultdict def have_same_frequency(freq: defaultdict, k: int): return all([freq[i] == k or freq[i] == 0 for i in freq]) def count_substrings(s: str, k: int) -> int: count = 0 distinct = len(set([i for i in s])) for length in range(1, distinct + 1): window_length = length * k freq = defaultdict(int) window_start = 0 window_end = window_start + window_length - 1 for i in range(window_start, min(window_end + 1, len(s))): freq[s[i]] += 1 while window_end < len(s): if have_same_frequency(freq, k): count += 1 freq[s[window_start]] -= 1 window_start += 1 window_end += 1 if window_end < len(s): freq[s[window_end]] += 1 return count if __name__ == '__main__': s = \"aabbcc\" k = 2 print(count_substrings(s, k)) s = \"aabbc\" k = 2 print(count_substrings(s, k))",
"e": 43532,
"s": 42577,
"text": null
},
{
"code": "using System; class GFG{ static bool have_same_frequency(int[] freq, int k){ for(int i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true;} static int count_substrings(string s, int k){ int count = 0; int distinct = 0; bool[] have = new bool[26]; Array.Fill(have, false); for(int i = 0; i < s.Length; i++) { have[((int)(s[i] - 'a'))] = true; } for(int i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for(int length = 1; length <= distinct; length++) { int window_length = length * k; int[] freq = new int[26]; Array.Fill(freq, 0); int window_start = 0; int window_end = window_start + window_length - 1; for(int i = window_start; i <= Math.Min(window_end, s.Length - 1); i++) { freq[((int)(s[i] - 'a'))]++; } while (window_end < s.Length) { if (have_same_frequency(freq, k)) { count++; } freq[((int)(s[window_start] - 'a'))]--; window_start++; window_end++; if (window_end < s.Length) { freq[((int)(s[window_end] - 'a'))]++; } } } return count;} // Driver codepublic static void Main(string[] args){ string s = \"aabbcc\"; int k = 2; Console.WriteLine(count_substrings(s, k)); s = \"aabbc\"; k = 2; Console.WriteLine(count_substrings(s, k));}} // This code is contributed by gaurav01",
"e": 45225,
"s": 43532,
"text": null
},
{
"code": "<script> function have_same_frequency(freq,k){ for (let i = 0; i < 26; i++) { if (freq[i] != 0 && freq[i] != k) { return false; } } return true;} function count_substrings(s,k){ let count = 0; let distinct = 0; let have = new Array(26); for(let i=0;i<26;i++) { have[i]=false; } for (let i = 0; i < s.length; i++) { have[((s[i].charCodeAt(0) - 'a'.charCodeAt(0)))] = true; } for (let i = 0; i < 26; i++) { if (have[i]) { distinct++; } } for (let length = 1; length <= distinct; length++) { let window_length = length * k; let freq = new Array(26); for(let i=0;i<26;i++) freq[i]=0; let window_start = 0; let window_end = window_start + window_length - 1; for (let i = window_start; i <= Math.min(window_end, s.length - 1); i++) { freq[((s[i].charCodeAt(0) - 'a'.charCodeAt(0)))]++; } while (window_end < s.length) { if (have_same_frequency(freq, k)) { count++; } freq[( (s[window_start].charCodeAt(0) - 'a'.charCodeAt(0)))]--; window_start++; window_end++; if (window_end < s.length) { freq[(s[window_end].charCodeAt(0) - 'a'.charCodeAt(0))]++; } } } return count;} let s = \"aabbcc\";let k = 2;document.write(count_substrings(s, k)+\"<br>\");s = \"aabbc\";k = 2;document.write(count_substrings(s, k)+\"<br>\"); // This code is contributed by rag2127 </script>",
"e": 47091,
"s": 45225,
"text": null
},
{
"code": null,
"e": 47095,
"s": 47091,
"text": "6\n3"
},
{
"code": null,
"e": 47223,
"s": 47095,
"text": "Time Complexity: O(N * D) where D is the number of distinct characters present in the string and N is the length of the string."
},
{
"code": null,
"e": 47643,
"s": 47223,
"text": "This article is contributed by Rahul Chawla. 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": 47658,
"s": 47643,
"text": "Sairahul Jella"
},
{
"code": null,
"e": 47664,
"s": 47658,
"text": "ukasp"
},
{
"code": null,
"e": 47676,
"s": 47664,
"text": "29AjayKumar"
},
{
"code": null,
"e": 47690,
"s": 47676,
"text": "princiraj1992"
},
{
"code": null,
"e": 47698,
"s": 47690,
"text": "gaveesh"
},
{
"code": null,
"e": 47719,
"s": 47698,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 47730,
"s": 47719,
"text": "suman_1729"
},
{
"code": null,
"e": 47738,
"s": 47730,
"text": "rag2127"
},
{
"code": null,
"e": 47747,
"s": 47738,
"text": "gaurav01"
},
{
"code": null,
"e": 47763,
"s": 47747,
"text": "rajatkumargla19"
},
{
"code": null,
"e": 47778,
"s": 47763,
"text": "varshagumber28"
},
{
"code": null,
"e": 47786,
"s": 47778,
"text": "Strings"
},
{
"code": null,
"e": 47794,
"s": 47786,
"text": "Strings"
},
{
"code": null,
"e": 47892,
"s": 47794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47949,
"s": 47892,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 47985,
"s": 47949,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 48032,
"s": 47985,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 48085,
"s": 48032,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 48121,
"s": 48085,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 48173,
"s": 48121,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 48211,
"s": 48173,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 48241,
"s": 48211,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 48286,
"s": 48241,
"text": "Top 50 String Coding Problems for Interviews"
}
] |
Python | Check if substring present in string - GeeksforGeeks | 24 Nov, 2018
Lets solve this general problem of finding if a particular piece of string is present in a larger string in different ways. This is a very common kind of problem every programmer comes across aleast once in his/her lifetime. This article gives various techniques to solve it.
Method 1 : Using in operatorThe in operator is the most generic, fastest method to check for a substring, the power of in operator in python is very well known and is used in many operations across the entire language.
# Python 3 code to demonstrate # checking substring in string# using in operator # initializing string test_str = "GeeksforGeeks" # using in to test# for substringprint ("Does for exists in GeeksforGeeks ? : ")if "for" in test_str : print ("Yes, String found")else : print ("No, String not found")
Output :
Does for exists in GeeksforGeeks ? :
Yes, String found
Method 2 : Using str.find()str.find() method is generally used to get the lowest index at which the string occurs, but also returns -1, if string is not present, hence if any value returns >= 0, string is present, else not present.
# Python 3 code to demonstrate # checking substring in string# using str.find() # initializing string test_str = "GeeksforGeeks" # using str.find() to test# for substringres = test_str.find("for")if res >= 0: print ("for is present in GeeksforGeeks")else : print ("for is not present in GeeksforGeeks")
Output :
for is present in GeeksforGeeks
Method 3 : Using str.index()This method can be used to performs the similar task, but like str.find(), it doesn’t return a value, but a ValueError if string is not present, hence catching the exception is the way to check for string in substring.
# Python 3 code to demonstrate # checking substring in string# using str.index() # initializing string test_str = "GeeksforGeeks" # using str.index() to test# for substringtry : res = test_str.index("forg") print ("forg exists in GeeksforGeeks")except : print ("forg does not exists in GeeksforGeeks")
Output :
forg does not exists in GeeksforGeeks
Method 4 : Using operator.contains()This is lesser known method to check for substring in a string, this method is also effective in accomplishing this task of checking a string in a string.
# Python 3 code to demonstrate # checking substring in string# using operator.contains()import operator # initializing string test_str = "GeeksforGeeks" # using operator.contains() to test# for substringif operator.contains(test_str, "for"): print ("for is present in GeeksforGeeks")else : print ("for is not present in GeeksforGeeks")
Output :
for is present in GeeksforGeeks
Python string-programs
python-string
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": 26291,
"s": 26263,
"text": "\n24 Nov, 2018"
},
{
"code": null,
"e": 26567,
"s": 26291,
"text": "Lets solve this general problem of finding if a particular piece of string is present in a larger string in different ways. This is a very common kind of problem every programmer comes across aleast once in his/her lifetime. This article gives various techniques to solve it."
},
{
"code": null,
"e": 26786,
"s": 26567,
"text": "Method 1 : Using in operatorThe in operator is the most generic, fastest method to check for a substring, the power of in operator in python is very well known and is used in many operations across the entire language."
},
{
"code": "# Python 3 code to demonstrate # checking substring in string# using in operator # initializing string test_str = \"GeeksforGeeks\" # using in to test# for substringprint (\"Does for exists in GeeksforGeeks ? : \")if \"for\" in test_str : print (\"Yes, String found\")else : print (\"No, String not found\")",
"e": 27093,
"s": 26786,
"text": null
},
{
"code": null,
"e": 27102,
"s": 27093,
"text": "Output :"
},
{
"code": null,
"e": 27159,
"s": 27102,
"text": "Does for exists in GeeksforGeeks ? : \nYes, String found\n"
},
{
"code": null,
"e": 27391,
"s": 27159,
"text": "Method 2 : Using str.find()str.find() method is generally used to get the lowest index at which the string occurs, but also returns -1, if string is not present, hence if any value returns >= 0, string is present, else not present."
},
{
"code": "# Python 3 code to demonstrate # checking substring in string# using str.find() # initializing string test_str = \"GeeksforGeeks\" # using str.find() to test# for substringres = test_str.find(\"for\")if res >= 0: print (\"for is present in GeeksforGeeks\")else : print (\"for is not present in GeeksforGeeks\")",
"e": 27702,
"s": 27391,
"text": null
},
{
"code": null,
"e": 27711,
"s": 27702,
"text": "Output :"
},
{
"code": null,
"e": 27744,
"s": 27711,
"text": "for is present in GeeksforGeeks\n"
},
{
"code": null,
"e": 27991,
"s": 27744,
"text": "Method 3 : Using str.index()This method can be used to performs the similar task, but like str.find(), it doesn’t return a value, but a ValueError if string is not present, hence catching the exception is the way to check for string in substring."
},
{
"code": "# Python 3 code to demonstrate # checking substring in string# using str.index() # initializing string test_str = \"GeeksforGeeks\" # using str.index() to test# for substringtry : res = test_str.index(\"forg\") print (\"forg exists in GeeksforGeeks\")except : print (\"forg does not exists in GeeksforGeeks\")",
"e": 28305,
"s": 27991,
"text": null
},
{
"code": null,
"e": 28314,
"s": 28305,
"text": "Output :"
},
{
"code": null,
"e": 28353,
"s": 28314,
"text": "forg does not exists in GeeksforGeeks\n"
},
{
"code": null,
"e": 28544,
"s": 28353,
"text": "Method 4 : Using operator.contains()This is lesser known method to check for substring in a string, this method is also effective in accomplishing this task of checking a string in a string."
},
{
"code": "# Python 3 code to demonstrate # checking substring in string# using operator.contains()import operator # initializing string test_str = \"GeeksforGeeks\" # using operator.contains() to test# for substringif operator.contains(test_str, \"for\"): print (\"for is present in GeeksforGeeks\")else : print (\"for is not present in GeeksforGeeks\")",
"e": 28888,
"s": 28544,
"text": null
},
{
"code": null,
"e": 28897,
"s": 28888,
"text": "Output :"
},
{
"code": null,
"e": 28930,
"s": 28897,
"text": "for is present in GeeksforGeeks\n"
},
{
"code": null,
"e": 28953,
"s": 28930,
"text": "Python string-programs"
},
{
"code": null,
"e": 28967,
"s": 28953,
"text": "python-string"
},
{
"code": null,
"e": 28974,
"s": 28967,
"text": "Python"
},
{
"code": null,
"e": 29072,
"s": 28974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29090,
"s": 29072,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29125,
"s": 29090,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29157,
"s": 29125,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29179,
"s": 29157,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29221,
"s": 29179,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29251,
"s": 29221,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29280,
"s": 29251,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29324,
"s": 29280,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29361,
"s": 29324,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Minimum number of bottles required to fill K glasses - GeeksforGeeks | 30 Sep, 2021
Given N glasses having water, and a list A of each of their capacity. The task is to find the minimum number of bottles required to fill out exactly K glasses. The capacity of each bottle is 100 units.
Examples:
Input: N = 4, K = 3, arr[] = {200, 150, 140, 300} Output: 5 We have to fill out exactly 3 glasses. So we fill out 140, 150, 200 whose sum is 490, so we need 5 bottles for this.Input: N = 5, K = 4, arr[] = {1, 2, 3, 2, 1} Output: 1
Approach: To fill out exactly K glasses, take the K glasses with the least capacity. So for this sort the list of given capacities. The final answer will be the ceiling value of (Sum of capacities of 1st k glasses) / (Capacity of 1 bottle).Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // function to calculate minimum glassesdouble Min_glass(int n, int k, int a[]){ // sort the array based on // their capacity int sum = 0; // taking sum of capacity // of first k glasses for (int i = 0; i < k; i++) sum += a[i]; // calculate the answer double ans = ceil((double)sum / (double)100); return ans;} // Driver codeint main(){ int n = 4; int k = 3; int a[] = { 200, 150, 140, 300 }; sort(a, a+n); cout << Min_glass(n, k, a); return 0;} // This code is contributed by target_2.
// Java implementation of the// above approachimport java.util.*; class GFG{// function to calculate minimum glassespublic static double Min_glass(int n, int k, int[] a){ // sort the array based on // their capacity int sum = 0; // taking sum of capacity // of first k glasses for (int i = 0; i < k; i++) sum += a[i]; // calculate the answer double ans = Math.ceil((double)sum / (double)100); return ans;} // Driver codepublic static void main(String[] args){ int n = 4; int k = 3; int[] a = { 200, 150, 140, 300 }; Arrays.sort(a); System.out.println(Min_glass(n, k, a));}} // This code is contributed by mits
# Python3 implementation of the above approachfrom math import ceil # Function to calculate minimum glassesdef Min_glass(n, k, a): # sort the array based on their capacity a.sort() # calculate the answer return ceil(sum(a[:k]) / 100) # Driver codeif __name__ == "__main__": n, k = 4, 3 a = [200, 150, 140, 300] print(Min_glass(n, k, a)) # This code is contributed by Rituraj Jain
// C# implementation of the// above approachusing System; class GFG{// function to calculate minimum glassespublic static double Min_glass(int n, int k, int []a){ // sort the array based on // their capacity int sum = 0; // taking sum of capacity // of first k glasses for (int i = 0; i < k; i++) sum += a[i]; // calculate the answer double ans = Math.Ceiling((double)sum / (double)100); return ans;} // Driver codepublic static void Main(){ int n = 4; int k = 3; int[] a = { 200, 150, 140, 300 }; Array.Sort(a); Console.WriteLine(Min_glass(n, k, a));}} // This code is contributed// by Soumik Mondal
<?php// PHP implementation of the above approach // function to calculate minimum glassesfunction Min_glass($n, $k, $a){ // sort the array based on // their capacity sort($a); $sum = 0; // taking sum of capacity // of first k glasses for ($i = 0; $i < $k; $i++) $sum += $a[$i]; // calculate the answer $ans = ceil($sum /100); return $ans;} // Driver code$n = 4;$k = 3;$a = array( 200, 150, 140, 300 ); echo Min_glass($n, $k, $a); // This code is contributed// by akt_mit?>
<script> // Javascript implementation of the// above approach // Function to calculate minimum glassesfunction Min_glass(n, k, a){ // Sort the array based on // their capacity var sum = 0; // Taking sum of capacity // of first k glasses for(var i = 0; i < k; i++) sum += a[i]; // Calculate the answer var ans = parseInt(Math.ceil(sum / 100)); return ans;} // Driver Codevar n = 4;var k = 3;var a = [ 200, 150, 140, 300 ];a.sort(); document.write(Min_glass(n, k, a)); // This code is contributed by Ankita saini </script>
5
jit_t
SoumikMondal
Mithun Kumar
rituraj_jain
ankita_saini
target_2
simmytarika5
Greedy
Mathematical
Sorting
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Program for First Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
Max Flow Problem Introduction
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 26561,
"s": 26533,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 26764,
"s": 26561,
"text": "Given N glasses having water, and a list A of each of their capacity. The task is to find the minimum number of bottles required to fill out exactly K glasses. The capacity of each bottle is 100 units. "
},
{
"code": null,
"e": 26776,
"s": 26764,
"text": "Examples: "
},
{
"code": null,
"e": 27008,
"s": 26776,
"text": "Input: N = 4, K = 3, arr[] = {200, 150, 140, 300} Output: 5 We have to fill out exactly 3 glasses. So we fill out 140, 150, 200 whose sum is 490, so we need 5 bottles for this.Input: N = 5, K = 4, arr[] = {1, 2, 3, 2, 1} Output: 1 "
},
{
"code": null,
"e": 27300,
"s": 27008,
"text": "Approach: To fill out exactly K glasses, take the K glasses with the least capacity. So for this sort the list of given capacities. The final answer will be the ceiling value of (Sum of capacities of 1st k glasses) / (Capacity of 1 bottle).Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27304,
"s": 27300,
"text": "C++"
},
{
"code": null,
"e": 27309,
"s": 27304,
"text": "Java"
},
{
"code": null,
"e": 27317,
"s": 27309,
"text": "Python3"
},
{
"code": null,
"e": 27320,
"s": 27317,
"text": "C#"
},
{
"code": null,
"e": 27324,
"s": 27320,
"text": "PHP"
},
{
"code": null,
"e": 27335,
"s": 27324,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // function to calculate minimum glassesdouble Min_glass(int n, int k, int a[]){ // sort the array based on // their capacity int sum = 0; // taking sum of capacity // of first k glasses for (int i = 0; i < k; i++) sum += a[i]; // calculate the answer double ans = ceil((double)sum / (double)100); return ans;} // Driver codeint main(){ int n = 4; int k = 3; int a[] = { 200, 150, 140, 300 }; sort(a, a+n); cout << Min_glass(n, k, a); return 0;} // This code is contributed by target_2.",
"e": 28020,
"s": 27335,
"text": null
},
{
"code": "// Java implementation of the// above approachimport java.util.*; class GFG{// function to calculate minimum glassespublic static double Min_glass(int n, int k, int[] a){ // sort the array based on // their capacity int sum = 0; // taking sum of capacity // of first k glasses for (int i = 0; i < k; i++) sum += a[i]; // calculate the answer double ans = Math.ceil((double)sum / (double)100); return ans;} // Driver codepublic static void main(String[] args){ int n = 4; int k = 3; int[] a = { 200, 150, 140, 300 }; Arrays.sort(a); System.out.println(Min_glass(n, k, a));}} // This code is contributed by mits",
"e": 28737,
"s": 28020,
"text": null
},
{
"code": "# Python3 implementation of the above approachfrom math import ceil # Function to calculate minimum glassesdef Min_glass(n, k, a): # sort the array based on their capacity a.sort() # calculate the answer return ceil(sum(a[:k]) / 100) # Driver codeif __name__ == \"__main__\": n, k = 4, 3 a = [200, 150, 140, 300] print(Min_glass(n, k, a)) # This code is contributed by Rituraj Jain",
"e": 29146,
"s": 28737,
"text": null
},
{
"code": "// C# implementation of the// above approachusing System; class GFG{// function to calculate minimum glassespublic static double Min_glass(int n, int k, int []a){ // sort the array based on // their capacity int sum = 0; // taking sum of capacity // of first k glasses for (int i = 0; i < k; i++) sum += a[i]; // calculate the answer double ans = Math.Ceiling((double)sum / (double)100); return ans;} // Driver codepublic static void Main(){ int n = 4; int k = 3; int[] a = { 200, 150, 140, 300 }; Array.Sort(a); Console.WriteLine(Min_glass(n, k, a));}} // This code is contributed// by Soumik Mondal",
"e": 29859,
"s": 29146,
"text": null
},
{
"code": "<?php// PHP implementation of the above approach // function to calculate minimum glassesfunction Min_glass($n, $k, $a){ // sort the array based on // their capacity sort($a); $sum = 0; // taking sum of capacity // of first k glasses for ($i = 0; $i < $k; $i++) $sum += $a[$i]; // calculate the answer $ans = ceil($sum /100); return $ans;} // Driver code$n = 4;$k = 3;$a = array( 200, 150, 140, 300 ); echo Min_glass($n, $k, $a); // This code is contributed// by akt_mit?>",
"e": 30373,
"s": 29859,
"text": null
},
{
"code": "<script> // Javascript implementation of the// above approach // Function to calculate minimum glassesfunction Min_glass(n, k, a){ // Sort the array based on // their capacity var sum = 0; // Taking sum of capacity // of first k glasses for(var i = 0; i < k; i++) sum += a[i]; // Calculate the answer var ans = parseInt(Math.ceil(sum / 100)); return ans;} // Driver Codevar n = 4;var k = 3;var a = [ 200, 150, 140, 300 ];a.sort(); document.write(Min_glass(n, k, a)); // This code is contributed by Ankita saini </script>",
"e": 30936,
"s": 30373,
"text": null
},
{
"code": null,
"e": 30938,
"s": 30936,
"text": "5"
},
{
"code": null,
"e": 30946,
"s": 30940,
"text": "jit_t"
},
{
"code": null,
"e": 30959,
"s": 30946,
"text": "SoumikMondal"
},
{
"code": null,
"e": 30972,
"s": 30959,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30985,
"s": 30972,
"text": "rituraj_jain"
},
{
"code": null,
"e": 30998,
"s": 30985,
"text": "ankita_saini"
},
{
"code": null,
"e": 31007,
"s": 30998,
"text": "target_2"
},
{
"code": null,
"e": 31020,
"s": 31007,
"text": "simmytarika5"
},
{
"code": null,
"e": 31027,
"s": 31020,
"text": "Greedy"
},
{
"code": null,
"e": 31040,
"s": 31027,
"text": "Mathematical"
},
{
"code": null,
"e": 31048,
"s": 31040,
"text": "Sorting"
},
{
"code": null,
"e": 31055,
"s": 31048,
"text": "Greedy"
},
{
"code": null,
"e": 31068,
"s": 31055,
"text": "Mathematical"
},
{
"code": null,
"e": 31076,
"s": 31068,
"text": "Sorting"
},
{
"code": null,
"e": 31174,
"s": 31076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31209,
"s": 31174,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 31261,
"s": 31209,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 31314,
"s": 31261,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 31365,
"s": 31314,
"text": "Bin Packing Problem (Minimize number of used Bins)"
},
{
"code": null,
"e": 31395,
"s": 31365,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 31425,
"s": 31395,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31440,
"s": 31425,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31483,
"s": 31440,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 31507,
"s": 31483,
"text": "Merge two sorted arrays"
}
] |
Modify a string by circularly shifting each character to the right by respective frequencies - GeeksforGeeks | 28 May, 2021
Given a string S consisting of lowercase English alphabets, the task is to right shift each character of the given string S circularly by its frequency.
Circular shifting of characters refers to shifting character ‘z’ to ‘a’, as its next character.
Examples:
Input: S = “geeksforgeeks”Output: iiimugpsiiimu Explanation:Following changes are made on the string S:
Frequency of ‘g’ is 2. Therefore, shifting the character ‘g’ by 2 becomes ‘i’.Frequency of ‘e’ is 4. Therefore, shifting the character ‘e’ by 4 becomes ‘i’.Frequency of ‘k’ is 2. Therefore, shifting the character ‘k’ by 2 becomes ‘m’.Frequency of ‘s’ is 2. Therefore, shifting the character ‘s’ by 2 becomes ‘u’.Frequency of ‘f’ is 1. Therefore, shifting the character ‘f’ by 1 becomes ‘g’.Frequency of ‘o’ is 1. Therefore, shifting the character ‘o’ by 1 becomes ‘p’.Frequency of ‘r’ is 1. Therefore, shifting the character ‘r’ by 1 becomes ‘s’.
Frequency of ‘g’ is 2. Therefore, shifting the character ‘g’ by 2 becomes ‘i’.
Frequency of ‘e’ is 4. Therefore, shifting the character ‘e’ by 4 becomes ‘i’.
Frequency of ‘k’ is 2. Therefore, shifting the character ‘k’ by 2 becomes ‘m’.
Frequency of ‘s’ is 2. Therefore, shifting the character ‘s’ by 2 becomes ‘u’.
Frequency of ‘f’ is 1. Therefore, shifting the character ‘f’ by 1 becomes ‘g’.
Frequency of ‘o’ is 1. Therefore, shifting the character ‘o’ by 1 becomes ‘p’.
Frequency of ‘r’ is 1. Therefore, shifting the character ‘r’ by 1 becomes ‘s’.
After the above shifting of characters, the string modifies to “iiimugpsiiimu”.
Input: S = “aabcadb”Output: ddddded
Approach: The idea to solve this problem is to traverse the string and find the frequency of occurrence of each character in the string and then increment each of the characters by its frequency. Follow the steps below to solve the problem:
Initialize an array, say frequency[] that stores the occurrences of each character in the string S.
Traverse the given string S and perform the following steps:Find the frequency of the current character S[i].Increment the current character by its frequency and update the value of S[i] to its updated character.
Find the frequency of the current character S[i].
Increment the current character by its frequency and update the value of S[i] to its updated character.
After completing the above steps, print the string S as the resultant modified string.
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 replace the characters// by its frequency of character in itvoid addFrequencyToCharacter(string S){ // Stores frequencies of characters // in the string S int frequency[26] = { 0 }; int N = S.length(); // Traverse the string S for (int i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i] - 'a'] += 1; } // Traverse the string S for (int i = 0; i < N; i++) { // Find the frequency of // the current character int add = frequency[S[i] - 'a'] % 26; // Update the character if (int(S[i]) + add <= int('z')) S[i] = char(int(S[i]) + add); else { add = (int(S[i]) + add) - (int('z')); S[i] = char(int('a') + add - 1); } } // Print the resultant string cout << S;} // Driver Codeint main(){ string S = "geeksforgeeks"; addFrequencyToCharacter(S); return 0;}
// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Function to replace the characters // by its frequency of character in it static void addFrequencyToCharacter(String Str) { // Stores frequencies of characters // in the string S int frequency[] = new int[26]; int N = Str.length(); char S[] = Str.toCharArray(); // Traverse the string S for (int i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i] - 'a'] += 1; } // Traverse the string S for (int i = 0; i < N; i++) { // Find the frequency of // the current character int add = frequency[S[i] - 'a'] % 26; // Update the character if ((int)(S[i]) + add <= (int)('z')) S[i] = (char)((int)(S[i]) + add); else { add = ((int)(S[i]) + add) - ((int)('z')); S[i] = (char)((int)('a') + add - 1); } } // Print the resultant string System.out.println(new String(S)); } // Driver Code public static void main(String[] args) { String S = "geeksforgeeks"; addFrequencyToCharacter(S); }} // This code is contributed by Kingash.
# Python3 program for the above approach # Function to replace the characters# by its frequency of character in itdef addFrequencyToCharacter(S): # Stores frequencies of characters # in the string S frequency = [0 for i in range(26)] N = len(S) S = list(S) # Traverse the string S for i in range(N): # Increment the frequency of # each character by 1 frequency[ord(S[i]) - ord('a')] += 1 # Traverse the string S for i in range(N): # Find the frequency of # the current character add = frequency[ord(S[i]) - ord('a')] % 26 # Update the character if ord(S[i]) + add <= ord('z'): S[i] = chr(ord(S[i]) + add) else: add = ord(S[i]) + add - ord('z') S[i] = chr(ord('a') + add - 1) # Print the resultant string s = "" print(s.join(S)) # Driver Codeif __name__ == '__main__': S = "geeksforgeeks" addFrequencyToCharacter(S) # This code is contributed by jana_sayantan
// C# program for the above approachusing System;class GFG{ // Function to replace the characters// by its frequency of character in itstatic void addFrequencyToCharacter(string Str){ // Stores frequencies of characters // in the string S int[] frequency = new int[26]; int N = Str.Length; char[] S = Str.ToCharArray(); // Traverse the string S for(int i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i] - 'a'] += 1; } // Traverse the string S for(int i = 0; i < N; i++) { // Find the frequency of // the current character int add = frequency[S[i] - 'a'] % 26; // Update the character if ((int)(S[i]) + add <= (int)('z')) S[i] = (char)((int)(S[i]) + add); else { add = ((int)(S[i]) + add) - ((int)('z')); S[i] = (char)((int)('a') + add - 1); } } // Print the resultant string Console.Write(new string(S));} // Driver Codepublic static void Main(string[] args){ string S = "geeksforgeeks"; addFrequencyToCharacter(S);}} // This code is contributed by ukasp
<script> // Javascript program for the above approach // Function to replace the characters// by its frequency of character in itfunction addFrequencyToCharacter(Str){ // Stores frequencies of characters // in the string S var frequency = Array.from({length: 26}, (_, i) => 0); var N = Str.length; var S = Str.split(''); // Traverse the string S for (var i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } // Traverse the string S for (var i = 0; i < N; i++) { // Find the frequency of // the current character var add = frequency[S[i].charCodeAt(0) - 'a'.charCodeAt(0)] % 26; // Update the character if ((S[i].charCodeAt(0)) + add <= ('z').charCodeAt(0)) S[i] = String.fromCharCode((S[i].charCodeAt(0)) + add); else { add = ((S[i].charCodeAt(0)) + add) - (('z').charCodeAt(0)); S[i] = String.fromCharCode(('a'.charCodeAt(0)) + add - 1); } } // Print the resultant string document.write(S.join(''));} // Driver Codevar S = "geeksforgeeks";addFrequencyToCharacter(S); // This code contributed by shikhasingrajput </script>
iiimugpsiiimu
Time Complexity: O(N)Auxiliary Space: O(26)
Kingash
ukasp
shikhasingrajput
jana_sayantan
frequency-counting
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 26090,
"s": 25937,
"text": "Given a string S consisting of lowercase English alphabets, the task is to right shift each character of the given string S circularly by its frequency."
},
{
"code": null,
"e": 26186,
"s": 26090,
"text": "Circular shifting of characters refers to shifting character ‘z’ to ‘a’, as its next character."
},
{
"code": null,
"e": 26196,
"s": 26186,
"text": "Examples:"
},
{
"code": null,
"e": 26300,
"s": 26196,
"text": "Input: S = “geeksforgeeks”Output: iiimugpsiiimu Explanation:Following changes are made on the string S:"
},
{
"code": null,
"e": 26847,
"s": 26300,
"text": "Frequency of ‘g’ is 2. Therefore, shifting the character ‘g’ by 2 becomes ‘i’.Frequency of ‘e’ is 4. Therefore, shifting the character ‘e’ by 4 becomes ‘i’.Frequency of ‘k’ is 2. Therefore, shifting the character ‘k’ by 2 becomes ‘m’.Frequency of ‘s’ is 2. Therefore, shifting the character ‘s’ by 2 becomes ‘u’.Frequency of ‘f’ is 1. Therefore, shifting the character ‘f’ by 1 becomes ‘g’.Frequency of ‘o’ is 1. Therefore, shifting the character ‘o’ by 1 becomes ‘p’.Frequency of ‘r’ is 1. Therefore, shifting the character ‘r’ by 1 becomes ‘s’."
},
{
"code": null,
"e": 26926,
"s": 26847,
"text": "Frequency of ‘g’ is 2. Therefore, shifting the character ‘g’ by 2 becomes ‘i’."
},
{
"code": null,
"e": 27005,
"s": 26926,
"text": "Frequency of ‘e’ is 4. Therefore, shifting the character ‘e’ by 4 becomes ‘i’."
},
{
"code": null,
"e": 27084,
"s": 27005,
"text": "Frequency of ‘k’ is 2. Therefore, shifting the character ‘k’ by 2 becomes ‘m’."
},
{
"code": null,
"e": 27163,
"s": 27084,
"text": "Frequency of ‘s’ is 2. Therefore, shifting the character ‘s’ by 2 becomes ‘u’."
},
{
"code": null,
"e": 27242,
"s": 27163,
"text": "Frequency of ‘f’ is 1. Therefore, shifting the character ‘f’ by 1 becomes ‘g’."
},
{
"code": null,
"e": 27321,
"s": 27242,
"text": "Frequency of ‘o’ is 1. Therefore, shifting the character ‘o’ by 1 becomes ‘p’."
},
{
"code": null,
"e": 27400,
"s": 27321,
"text": "Frequency of ‘r’ is 1. Therefore, shifting the character ‘r’ by 1 becomes ‘s’."
},
{
"code": null,
"e": 27480,
"s": 27400,
"text": "After the above shifting of characters, the string modifies to “iiimugpsiiimu”."
},
{
"code": null,
"e": 27516,
"s": 27480,
"text": "Input: S = “aabcadb”Output: ddddded"
},
{
"code": null,
"e": 27757,
"s": 27516,
"text": "Approach: The idea to solve this problem is to traverse the string and find the frequency of occurrence of each character in the string and then increment each of the characters by its frequency. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27857,
"s": 27757,
"text": "Initialize an array, say frequency[] that stores the occurrences of each character in the string S."
},
{
"code": null,
"e": 28070,
"s": 27857,
"text": "Traverse the given string S and perform the following steps:Find the frequency of the current character S[i].Increment the current character by its frequency and update the value of S[i] to its updated character."
},
{
"code": null,
"e": 28120,
"s": 28070,
"text": "Find the frequency of the current character S[i]."
},
{
"code": null,
"e": 28224,
"s": 28120,
"text": "Increment the current character by its frequency and update the value of S[i] to its updated character."
},
{
"code": null,
"e": 28311,
"s": 28224,
"text": "After completing the above steps, print the string S as the resultant modified string."
},
{
"code": null,
"e": 28362,
"s": 28311,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28366,
"s": 28362,
"text": "C++"
},
{
"code": null,
"e": 28371,
"s": 28366,
"text": "Java"
},
{
"code": null,
"e": 28379,
"s": 28371,
"text": "Python3"
},
{
"code": null,
"e": 28382,
"s": 28379,
"text": "C#"
},
{
"code": null,
"e": 28393,
"s": 28382,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to replace the characters// by its frequency of character in itvoid addFrequencyToCharacter(string S){ // Stores frequencies of characters // in the string S int frequency[26] = { 0 }; int N = S.length(); // Traverse the string S for (int i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i] - 'a'] += 1; } // Traverse the string S for (int i = 0; i < N; i++) { // Find the frequency of // the current character int add = frequency[S[i] - 'a'] % 26; // Update the character if (int(S[i]) + add <= int('z')) S[i] = char(int(S[i]) + add); else { add = (int(S[i]) + add) - (int('z')); S[i] = char(int('a') + add - 1); } } // Print the resultant string cout << S;} // Driver Codeint main(){ string S = \"geeksforgeeks\"; addFrequencyToCharacter(S); return 0;}",
"e": 29509,
"s": 28393,
"text": null
},
{
"code": "// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Function to replace the characters // by its frequency of character in it static void addFrequencyToCharacter(String Str) { // Stores frequencies of characters // in the string S int frequency[] = new int[26]; int N = Str.length(); char S[] = Str.toCharArray(); // Traverse the string S for (int i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i] - 'a'] += 1; } // Traverse the string S for (int i = 0; i < N; i++) { // Find the frequency of // the current character int add = frequency[S[i] - 'a'] % 26; // Update the character if ((int)(S[i]) + add <= (int)('z')) S[i] = (char)((int)(S[i]) + add); else { add = ((int)(S[i]) + add) - ((int)('z')); S[i] = (char)((int)('a') + add - 1); } } // Print the resultant string System.out.println(new String(S)); } // Driver Code public static void main(String[] args) { String S = \"geeksforgeeks\"; addFrequencyToCharacter(S); }} // This code is contributed by Kingash.",
"e": 30872,
"s": 29509,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to replace the characters# by its frequency of character in itdef addFrequencyToCharacter(S): # Stores frequencies of characters # in the string S frequency = [0 for i in range(26)] N = len(S) S = list(S) # Traverse the string S for i in range(N): # Increment the frequency of # each character by 1 frequency[ord(S[i]) - ord('a')] += 1 # Traverse the string S for i in range(N): # Find the frequency of # the current character add = frequency[ord(S[i]) - ord('a')] % 26 # Update the character if ord(S[i]) + add <= ord('z'): S[i] = chr(ord(S[i]) + add) else: add = ord(S[i]) + add - ord('z') S[i] = chr(ord('a') + add - 1) # Print the resultant string s = \"\" print(s.join(S)) # Driver Codeif __name__ == '__main__': S = \"geeksforgeeks\" addFrequencyToCharacter(S) # This code is contributed by jana_sayantan",
"e": 31904,
"s": 30872,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to replace the characters// by its frequency of character in itstatic void addFrequencyToCharacter(string Str){ // Stores frequencies of characters // in the string S int[] frequency = new int[26]; int N = Str.Length; char[] S = Str.ToCharArray(); // Traverse the string S for(int i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i] - 'a'] += 1; } // Traverse the string S for(int i = 0; i < N; i++) { // Find the frequency of // the current character int add = frequency[S[i] - 'a'] % 26; // Update the character if ((int)(S[i]) + add <= (int)('z')) S[i] = (char)((int)(S[i]) + add); else { add = ((int)(S[i]) + add) - ((int)('z')); S[i] = (char)((int)('a') + add - 1); } } // Print the resultant string Console.Write(new string(S));} // Driver Codepublic static void Main(string[] args){ string S = \"geeksforgeeks\"; addFrequencyToCharacter(S);}} // This code is contributed by ukasp",
"e": 33088,
"s": 31904,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to replace the characters// by its frequency of character in itfunction addFrequencyToCharacter(Str){ // Stores frequencies of characters // in the string S var frequency = Array.from({length: 26}, (_, i) => 0); var N = Str.length; var S = Str.split(''); // Traverse the string S for (var i = 0; i < N; i++) { // Increment the frequency of // each character by 1 frequency[S[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } // Traverse the string S for (var i = 0; i < N; i++) { // Find the frequency of // the current character var add = frequency[S[i].charCodeAt(0) - 'a'.charCodeAt(0)] % 26; // Update the character if ((S[i].charCodeAt(0)) + add <= ('z').charCodeAt(0)) S[i] = String.fromCharCode((S[i].charCodeAt(0)) + add); else { add = ((S[i].charCodeAt(0)) + add) - (('z').charCodeAt(0)); S[i] = String.fromCharCode(('a'.charCodeAt(0)) + add - 1); } } // Print the resultant string document.write(S.join(''));} // Driver Codevar S = \"geeksforgeeks\";addFrequencyToCharacter(S); // This code contributed by shikhasingrajput </script>",
"e": 34419,
"s": 33088,
"text": null
},
{
"code": null,
"e": 34433,
"s": 34419,
"text": "iiimugpsiiimu"
},
{
"code": null,
"e": 34479,
"s": 34435,
"text": "Time Complexity: O(N)Auxiliary Space: O(26)"
},
{
"code": null,
"e": 34487,
"s": 34479,
"text": "Kingash"
},
{
"code": null,
"e": 34493,
"s": 34487,
"text": "ukasp"
},
{
"code": null,
"e": 34510,
"s": 34493,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 34524,
"s": 34510,
"text": "jana_sayantan"
},
{
"code": null,
"e": 34543,
"s": 34524,
"text": "frequency-counting"
},
{
"code": null,
"e": 34556,
"s": 34543,
"text": "Mathematical"
},
{
"code": null,
"e": 34564,
"s": 34556,
"text": "Strings"
},
{
"code": null,
"e": 34572,
"s": 34564,
"text": "Strings"
},
{
"code": null,
"e": 34585,
"s": 34572,
"text": "Mathematical"
},
{
"code": null,
"e": 34683,
"s": 34585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34727,
"s": 34683,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 34769,
"s": 34727,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 34800,
"s": 34769,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 34871,
"s": 34800,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 34896,
"s": 34871,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 34942,
"s": 34896,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 34967,
"s": 34942,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35001,
"s": 34967,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35076,
"s": 35001,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Disjoint set (Union-Find) | Practice | GeeksforGeeks | Given an array A[] that stores all number from 1 to N (both inclusive and sorted) and K queries.
The task is to do the following operations on array elements :
1. UNION X Z : Perform union of X and Z i.e. parent of Z will become the parent of X.
2. FIND X: Find the parent of X and print it.
Note: Initially all are the parent of themselves.
Input:
N = 5, K = 4
queries[] = {{find 4},
{find 1},
{unionSet 3 1},
{find 3}}
Output:
4 1 1
Explanation:
1. The parent of 4 is 4. Hence the output is 4.
2. The parent of 1 is 1. Hence the output is 1.
3. After performing unionSet 3 1, parent of 3 becomes 1,
since, parent of 1 is currently 1 itself.
4. The parent of 3 is now 1. Hence, the output is 1.
Your Task:
You don't need to read input or print anything. Your task is to complete the functions- find() which takes an array A[] and an integer X as an input parameter and return the parent of X and the function unionSet() which takes an array A[] and two integers X and Z and performs the union of X and Z.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N, K <= 100
0
badgujarsachin831 month ago
int find(int A[],int X)
{
//add code here
if(X==A[X]){
return X;
}
return A[X]=find(A,A[X]);
}
void unionSet(int A[],int X,int Z)
{
//add code here.
X=find(A,X);
Z=find(A,Z);
A[X]=Z;
}
+2
aloksinghbais023 months ago
C++ solution having time complexity as O(4*alpha) (mathematically proven) and auxiliary space complexity as O(1) is as follows :-
Execution Time :- 0.0 / 1.4 sec
int find(int A[],int X){ if(A[X] == X) return (X); return A[X] = find(A,A[X]);}void unionSet(int A[],int X,int Z){ X = find(A,X); Z = find(A,Z); A[X] = Z;}
+2
sangamchoudhary75 months ago
int find(int A[],int X){
if(X == A[X]){
return X;
}
return A[X] = find(A,A[X]);
}
void unionSet(int A[],int X,int Z){
A[find(A,X)] = find(A,Z);
}
0
shivam4215 months ago
int find(int A[],int X)
{
if(X==A[X]) return X;
return A[X]=find(A,A[X]);
}
void union (int A[],int X,int Z )
{
X=find(A,X);
Z=find(A,Z);
if(X==Z) return ;
A[X]=Z;
}
+2
shreysomu22117 months ago
int find(int A[],int X){ //add code here if (A[X]==X) return X; else return find(A,A[X]); }void unionSet(int A[],int X,int Z){//add code here.int XRep=find(A,X);int ZRep = find(A,Z);A[XRep] = ZRep;}
0
Stangly chang9 months ago
Stangly chang
int find(int A[],int X){ //add code here if(A[X]==X) return X; else return find(A,A[X]);}void unionSet(int A[],int X,int Z){//add code here.int xRep = find(A,X);int zRep = find(A,Z);A[xRep] = zRep;}
0
Ananya Ananth9 months ago
Ananya Ananth
python3 solutiondef find(A, X): for i,a in enumerate(A): if type(a) is list: for x in a: if x==X: return i+1 if X == a: return i+1# function shouldn't return or print anythingdef unionSet(A, X, Z): if X==Z : pass else: i=find(A,Z)-1 j=find(A,X)-1 if i!=j: if type(A[i]) is not list: A[i]=[A[i]] try: A[i]=A[i]+A[j] except: A[i].append(A[j]) try: A[j].remove(A[j]) A[j]=0 except: A[j]=0
0
Vikash Maddi9 months ago
Vikash Maddi
simple code - 0.0 /1.4 int find(int A[],int x){ while(A[x] != x){ int k = A[x]; A[x] = A[A[x]]; x = k; } return A[x];}void unionSet(int A[],int x,int z){ x=find(A,x);z=find(A,z);if(x==z) return;A[x]=z;}
+2
coderPlusTester9 months ago
coderPlusTester
Piece of advice, CPP Programmers. The Driver code is assuming 1-index array and not 0-index.
0
Prakhar Shukla10 months ago
Prakhar Shukla
In python. The driver code enters the array with 0 based indexing, so I think we have to convert it into 1 based indexing first before using recursion for find method! Make sure you compare x with arr[x-1] andnot arr[x]..Peace!
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": 335,
"s": 238,
"text": "Given an array A[] that stores all number from 1 to N (both inclusive and sorted) and K queries."
},
{
"code": null,
"e": 398,
"s": 335,
"text": "The task is to do the following operations on array elements :"
},
{
"code": null,
"e": 530,
"s": 398,
"text": "1. UNION X Z : Perform union of X and Z i.e. parent of Z will become the parent of X.\n2. FIND X: Find the parent of X and print it."
},
{
"code": null,
"e": 580,
"s": 530,
"text": "Note: Initially all are the parent of themselves."
},
{
"code": null,
"e": 978,
"s": 580,
"text": "Input:\nN = 5, K = 4\nqueries[] = {{find 4},\n {find 1},\n {unionSet 3 1},\n {find 3}}\nOutput:\n4 1 1\nExplanation:\n1. The parent of 4 is 4. Hence the output is 4.\n2. The parent of 1 is 1. Hence the output is 1.\n3. After performing unionSet 3 1, parent of 3 becomes 1,\n since, parent of 1 is currently 1 itself.\n4. The parent of 3 is now 1. Hence, the output is 1.\n\n"
},
{
"code": null,
"e": 1290,
"s": 978,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the functions- find() which takes an array A[] and an integer X as an input parameter and return the parent of X and the function unionSet() which takes an array A[] and two integers X and Z and performs the union of X and Z."
},
{
"code": null,
"e": 1352,
"s": 1290,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1382,
"s": 1352,
"text": "Constraints:\n1 <= N, K <= 100"
},
{
"code": null,
"e": 1384,
"s": 1382,
"text": "0"
},
{
"code": null,
"e": 1412,
"s": 1384,
"text": "badgujarsachin831 month ago"
},
{
"code": null,
"e": 1640,
"s": 1412,
"text": "int find(int A[],int X)\n{\n //add code here\n if(X==A[X]){\n return X;\n }\n return A[X]=find(A,A[X]);\n}\nvoid unionSet(int A[],int X,int Z)\n{\n\t//add code here.\n\tX=find(A,X);\n\tZ=find(A,Z);\n\tA[X]=Z;\n}"
},
{
"code": null,
"e": 1643,
"s": 1640,
"text": "+2"
},
{
"code": null,
"e": 1671,
"s": 1643,
"text": "aloksinghbais023 months ago"
},
{
"code": null,
"e": 1801,
"s": 1671,
"text": "C++ solution having time complexity as O(4*alpha) (mathematically proven) and auxiliary space complexity as O(1) is as follows :-"
},
{
"code": null,
"e": 1833,
"s": 1801,
"text": "Execution Time :- 0.0 / 1.4 sec"
},
{
"code": null,
"e": 2002,
"s": 1835,
"text": "int find(int A[],int X){ if(A[X] == X) return (X); return A[X] = find(A,A[X]);}void unionSet(int A[],int X,int Z){ X = find(A,X); Z = find(A,Z); A[X] = Z;}"
},
{
"code": null,
"e": 2005,
"s": 2002,
"text": "+2"
},
{
"code": null,
"e": 2034,
"s": 2005,
"text": "sangamchoudhary75 months ago"
},
{
"code": null,
"e": 2204,
"s": 2034,
"text": "int find(int A[],int X){\n if(X == A[X]){\n return X;\n }\n return A[X] = find(A,A[X]);\n}\nvoid unionSet(int A[],int X,int Z){\n A[find(A,X)] = find(A,Z);\n}"
},
{
"code": null,
"e": 2206,
"s": 2204,
"text": "0"
},
{
"code": null,
"e": 2228,
"s": 2206,
"text": "shivam4215 months ago"
},
{
"code": null,
"e": 2253,
"s": 2228,
"text": "int find(int A[],int X) "
},
{
"code": null,
"e": 2256,
"s": 2253,
"text": "{ "
},
{
"code": null,
"e": 2281,
"s": 2256,
"text": " if(X==A[X]) return X; "
},
{
"code": null,
"e": 2310,
"s": 2281,
"text": " return A[X]=find(A,A[X]); "
},
{
"code": null,
"e": 2313,
"s": 2310,
"text": "} "
},
{
"code": null,
"e": 2348,
"s": 2313,
"text": "void union (int A[],int X,int Z ) "
},
{
"code": null,
"e": 2351,
"s": 2348,
"text": "{ "
},
{
"code": null,
"e": 2371,
"s": 2351,
"text": " X=find(A,X); "
},
{
"code": null,
"e": 2391,
"s": 2371,
"text": " Z=find(A,Z); "
},
{
"code": null,
"e": 2415,
"s": 2391,
"text": " if(X==Z) return ; "
},
{
"code": null,
"e": 2429,
"s": 2415,
"text": " A[X]=Z; "
},
{
"code": null,
"e": 2431,
"s": 2429,
"text": "}"
},
{
"code": null,
"e": 2436,
"s": 2433,
"text": "+2"
},
{
"code": null,
"e": 2462,
"s": 2436,
"text": "shreysomu22117 months ago"
},
{
"code": null,
"e": 2704,
"s": 2462,
"text": "int find(int A[],int X){ //add code here if (A[X]==X) return X; else return find(A,A[X]); }void unionSet(int A[],int X,int Z){//add code here.int XRep=find(A,X);int ZRep = find(A,Z);A[XRep] = ZRep;}"
},
{
"code": null,
"e": 2706,
"s": 2704,
"text": "0"
},
{
"code": null,
"e": 2732,
"s": 2706,
"text": "Stangly chang9 months ago"
},
{
"code": null,
"e": 2746,
"s": 2732,
"text": "Stangly chang"
},
{
"code": null,
"e": 2964,
"s": 2746,
"text": "int find(int A[],int X){ //add code here if(A[X]==X) return X; else return find(A,A[X]);}void unionSet(int A[],int X,int Z){//add code here.int xRep = find(A,X);int zRep = find(A,Z);A[xRep] = zRep;}"
},
{
"code": null,
"e": 2966,
"s": 2964,
"text": "0"
},
{
"code": null,
"e": 2992,
"s": 2966,
"text": "Ananya Ananth9 months ago"
},
{
"code": null,
"e": 3006,
"s": 2992,
"text": "Ananya Ananth"
},
{
"code": null,
"e": 3644,
"s": 3006,
"text": "python3 solutiondef find(A, X): for i,a in enumerate(A): if type(a) is list: for x in a: if x==X: return i+1 if X == a: return i+1# function shouldn't return or print anythingdef unionSet(A, X, Z): if X==Z : pass else: i=find(A,Z)-1 j=find(A,X)-1 if i!=j: if type(A[i]) is not list: A[i]=[A[i]] try: A[i]=A[i]+A[j] except: A[i].append(A[j]) try: A[j].remove(A[j]) A[j]=0 except: A[j]=0"
},
{
"code": null,
"e": 3646,
"s": 3644,
"text": "0"
},
{
"code": null,
"e": 3671,
"s": 3646,
"text": "Vikash Maddi9 months ago"
},
{
"code": null,
"e": 3684,
"s": 3671,
"text": "Vikash Maddi"
},
{
"code": null,
"e": 3927,
"s": 3684,
"text": " simple code - 0.0 /1.4 int find(int A[],int x){ while(A[x] != x){ int k = A[x]; A[x] = A[A[x]]; x = k; } return A[x];}void unionSet(int A[],int x,int z){ x=find(A,x);z=find(A,z);if(x==z) return;A[x]=z;}"
},
{
"code": null,
"e": 3930,
"s": 3927,
"text": "+2"
},
{
"code": null,
"e": 3958,
"s": 3930,
"text": "coderPlusTester9 months ago"
},
{
"code": null,
"e": 3974,
"s": 3958,
"text": "coderPlusTester"
},
{
"code": null,
"e": 4067,
"s": 3974,
"text": "Piece of advice, CPP Programmers. The Driver code is assuming 1-index array and not 0-index."
},
{
"code": null,
"e": 4069,
"s": 4067,
"text": "0"
},
{
"code": null,
"e": 4097,
"s": 4069,
"text": "Prakhar Shukla10 months ago"
},
{
"code": null,
"e": 4112,
"s": 4097,
"text": "Prakhar Shukla"
},
{
"code": null,
"e": 4341,
"s": 4112,
"text": "In python. The driver code enters the array with 0 based indexing, so I think we have to convert it into 1 based indexing first before using recursion for find method! Make sure you compare x with arr[x-1] andnot arr[x]..Peace!"
},
{
"code": null,
"e": 4487,
"s": 4341,
"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": 4523,
"s": 4487,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4533,
"s": 4523,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4543,
"s": 4533,
"text": "\nContest\n"
},
{
"code": null,
"e": 4606,
"s": 4543,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4754,
"s": 4606,
"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": 4962,
"s": 4754,
"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": 5068,
"s": 4962,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to create a custom AlertDialog in Android - GeeksforGeeks | 01 Jun, 2020
Sometimes in AlertDialog, there is need to get input from the user or customize according to our requirements. So we create custom AlertDialogs. This post will show how to customize the AlertDialogs and take the input from it.
Below is the step by step implementation of the above approach:
Step 1: Create a XML file: custom_layout.xml. Add the below code in custom_layout.xml. This code defines the alertdialog box dimensions and add a edittext in it.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:paddingLeft="20dp" android:paddingRight="20dp" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content"/></LinearLayout>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:paddingLeft="20dp" android:paddingRight="20dp" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content"/></LinearLayout>
Step 2: Add a button in activity_main.xml. The button when clicked will show the AlertDialog box.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:id="@+id/root" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked" android:text="Show Dialog" /></LinearLayout>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:id="@+id/root" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked" android:text="Show Dialog" /></LinearLayout>
Step 3:Add custom_layout.xml in that activity in which you want to show custom alert dialog here it is added in MainActivity.java.public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showAlertDialogButtonClicked(View view) { // Create an alert builder AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Name"); // set the custom layout final View customLayout = getLayoutInflater() .inflate( R.layout.custom_layout, null); builder.setView(customLayout); // add a button builder .setPositiveButton( "OK", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { // send data from the // AlertDialog to the Activity EditText editText = customLayout .findViewById( R.id.editText); sendDialogDataToActivity( editText .getText() .toString()); } }); // create and show // the alert dialog AlertDialog dialog = builder.create(); dialog.show(); } // Do something with the data // coming from the AlertDialog private void sendDialogDataToActivity(String data) { Toast.makeText(this, data, Toast.LENGTH_SHORT) .show(); }}
Add custom_layout.xml in that activity in which you want to show custom alert dialog here it is added in MainActivity.java.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showAlertDialogButtonClicked(View view) { // Create an alert builder AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Name"); // set the custom layout final View customLayout = getLayoutInflater() .inflate( R.layout.custom_layout, null); builder.setView(customLayout); // add a button builder .setPositiveButton( "OK", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { // send data from the // AlertDialog to the Activity EditText editText = customLayout .findViewById( R.id.editText); sendDialogDataToActivity( editText .getText() .toString()); } }); // create and show // the alert dialog AlertDialog dialog = builder.create(); dialog.show(); } // Do something with the data // coming from the AlertDialog private void sendDialogDataToActivity(String data) { Toast.makeText(this, data, Toast.LENGTH_SHORT) .show(); }}
Output:
android
How To
Java
Java
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?
Java Tutorial
How to Install FFmpeg on Windows?
How to set fixed width for <td> in a table ?
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": 25958,
"s": 25930,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 26185,
"s": 25958,
"text": "Sometimes in AlertDialog, there is need to get input from the user or customize according to our requirements. So we create custom AlertDialogs. This post will show how to customize the AlertDialogs and take the input from it."
},
{
"code": null,
"e": 26249,
"s": 26185,
"text": "Below is the step by step implementation of the above approach:"
},
{
"code": null,
"e": 26826,
"s": 26249,
"text": "Step 1: Create a XML file: custom_layout.xml. Add the below code in custom_layout.xml. This code defines the alertdialog box dimensions and add a edittext in it.<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:paddingLeft=\"20dp\" android:paddingRight=\"20dp\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"/></LinearLayout>"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:paddingLeft=\"20dp\" android:paddingRight=\"20dp\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"/></LinearLayout>",
"e": 27242,
"s": 26826,
"text": null
},
{
"code": null,
"e": 27969,
"s": 27242,
"text": "Step 2: Add a button in activity_main.xml. The button when clicked will show the AlertDialog box.<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:id=\"@+id/root\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:onClick=\"showAlertDialogButtonClicked\" android:text=\"Show Dialog\" /></LinearLayout>"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:id=\"@+id/root\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:onClick=\"showAlertDialogButtonClicked\" android:text=\"Show Dialog\" /></LinearLayout>",
"e": 28599,
"s": 27969,
"text": null
},
{
"code": null,
"e": 30617,
"s": 28599,
"text": "Step 3:Add custom_layout.xml in that activity in which you want to show custom alert dialog here it is added in MainActivity.java.public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showAlertDialogButtonClicked(View view) { // Create an alert builder AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(\"Name\"); // set the custom layout final View customLayout = getLayoutInflater() .inflate( R.layout.custom_layout, null); builder.setView(customLayout); // add a button builder .setPositiveButton( \"OK\", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { // send data from the // AlertDialog to the Activity EditText editText = customLayout .findViewById( R.id.editText); sendDialogDataToActivity( editText .getText() .toString()); } }); // create and show // the alert dialog AlertDialog dialog = builder.create(); dialog.show(); } // Do something with the data // coming from the AlertDialog private void sendDialogDataToActivity(String data) { Toast.makeText(this, data, Toast.LENGTH_SHORT) .show(); }}"
},
{
"code": null,
"e": 30741,
"s": 30617,
"text": "Add custom_layout.xml in that activity in which you want to show custom alert dialog here it is added in MainActivity.java."
},
{
"code": "public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showAlertDialogButtonClicked(View view) { // Create an alert builder AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(\"Name\"); // set the custom layout final View customLayout = getLayoutInflater() .inflate( R.layout.custom_layout, null); builder.setView(customLayout); // add a button builder .setPositiveButton( \"OK\", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { // send data from the // AlertDialog to the Activity EditText editText = customLayout .findViewById( R.id.editText); sendDialogDataToActivity( editText .getText() .toString()); } }); // create and show // the alert dialog AlertDialog dialog = builder.create(); dialog.show(); } // Do something with the data // coming from the AlertDialog private void sendDialogDataToActivity(String data) { Toast.makeText(this, data, Toast.LENGTH_SHORT) .show(); }}",
"e": 32629,
"s": 30741,
"text": null
},
{
"code": null,
"e": 32637,
"s": 32629,
"text": "Output:"
},
{
"code": null,
"e": 32645,
"s": 32637,
"text": "android"
},
{
"code": null,
"e": 32652,
"s": 32645,
"text": "How To"
},
{
"code": null,
"e": 32657,
"s": 32652,
"text": "Java"
},
{
"code": null,
"e": 32662,
"s": 32657,
"text": "Java"
},
{
"code": null,
"e": 32760,
"s": 32662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32787,
"s": 32760,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 32835,
"s": 32787,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 32849,
"s": 32835,
"text": "Java Tutorial"
},
{
"code": null,
"e": 32883,
"s": 32849,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 32928,
"s": 32883,
"text": "How to set fixed width for <td> in a table ?"
},
{
"code": null,
"e": 32943,
"s": 32928,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32987,
"s": 32943,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 33009,
"s": 32987,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 33060,
"s": 33009,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Finding the probability of a state at a given time in a Markov chain | Set 2 - GeeksforGeeks | 07 Jul, 2021
Given a Markov chain G, we have the find the probability of reaching the state F at time t = T if we start from state S at time t = 0.A Markov chain is a random process consisting of various states and the probabilities of moving from one state to another. We can represent it using a directed graph where the nodes represent the states and the edges represent the probability of going from one node to another. It takes unit time to move from one node to another. The sum of the associated probabilities of the outgoing edges is one for every node.Consider the given Markov Chain( G ) as shown in below image:
Examples:
Input : S = 1, F = 2, T = 1
Output: 0.23
We start at state 1 at t = 0,
so there is a probability of 0.23
that we reach state 2 at t = 1.
Input: S = 4, F = 2, T = 100
Output: 0.284992
In the previous article, a dynamic programming approach is discussed with a time complexity of O(N2T), where N is the number of states. Matrix exponentiation approach: We can make an adjacency matrix for the Markov chain to represent the probabilities of transitions between the states. For example, the adjacency matrix for the graph given above is:
We can observe that the probability distribution at time t is given by P(t) = M * P(t – 1), and the initial probability distribution P(0) is a zero vector with the Sth element being one. Using these results, we can get solve the recursive expression for P(t). For example, if we take S to be 3, then P(t) is given by,
If we use effective matrix exponentiation technique, then the time complexity of this approach comes out to be O(N3 * log T). This approach performs better than the dynamic programming approach if the value of T is considerably higher than the number of states, i.e. N.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Macro to define a vector of float#define vf vector<float> // Function to multiply two matrices A and Bvector<vf > multiply(vector<vf > A, vector<vf > B, int N){ vector<vf > C(N, vf(N, 0)); for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) C[i][j] += A[i][k] * B[k][j]; return C;} // Function to calculate the power of a matrixvector<vf > matrix_power(vector<vf > M, int p, int n){ vector<vf > A(n, vf(n, 0)); for (int i = 0; i < n; ++i) A[i][i] = 1; while (p) { if (p % 2) A = multiply(A, M, n); M = multiply(M, M, n); p /= 2; } return A;} // Function to calculate the probability of// reaching F at time T after starting from Sfloat findProbability(vector<vf > M, int N, int F, int S, int T){ // Storing M^T in MT vector<vf > MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1][S - 1];} // Driver codeint main(){ // Adjacency matrix // The edges have been stored in the row // corresponding to their end-point vector<vf > G{ { 0, 0.09, 0, 0, 0, 0 }, { 0.23, 0, 0, 0, 0, 0.62 }, { 0, 0.06, 0, 0, 0, 0 }, { 0.77, 0, 0.63, 0, 0, 0 }, { 0, 0, 0, 0.65, 0, 0.38 }, { 0, 0.85, 0.37, 0.35, 1.0, 0 }}; // N is the number of states int N = 6; int S = 4, F = 2, T = 100; cout << "The probability of reaching " << F << " at time " << T << "\nafter starting from " << S << " is " << findProbability(G, N, F, S, T); return 0;}
// Java implementation of the above approachclass GFG{ // Function to multiply two matrices A and B static double[][] multiply(double[][] A, double[][] B, int N) { double[][] C = new double[N][N]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) C[i][j] += A[i][k] * B[k][j]; return C; } // Function to calculate the power of a matrix static double[][] matrix_power(double[][] M, int p, int n) { double[][] A = new double[n][n]; for (int i = 0; i < n; ++i) A[i][i] = 1; while (p > 0) { if (p % 2 == 1) A = multiply(A, M, n); M = multiply(M, M, n); p /= 2; } return A; } // Function to calculate the probability of // reaching F at time T after starting from S static double findProbability(double[][] M, int N, int F, int S, int T) { // Storing M^T in MT double[][] MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1][S - 1]; } // Driver code public static void main(String[] args) { // Adjacency matrix // The edges have been stored in the row // corresponding to their end-point double[][] G = { { 0, 0.09, 0, 0, 0, 0 }, { 0.23, 0, 0, 0, 0, 0.62 }, { 0, 0.06, 0, 0, 0, 0 }, { 0.77, 0, 0.63, 0, 0, 0 }, { 0, 0, 0, 0.65, 0, 0.38 }, { 0, 0.85, 0.37, 0.35, 1.0, 0 } }; // N is the number of states int N = 6; int S = 4, F = 2, T = 100; System.out.printf( "The probability of reaching " + F + " at time " + T + "\nafter starting from " + S + " is %f", findProbability(G, N, F, S, T)); }} // This code is contributed by Rajput-Ji
# Python implementation of the above approachfrom typing import List # Function to multiply two matrices A and Bdef multiply(A: List[List[float]], B: List[List[float]], N: int) -> List[List[float]]: C = [[0 for _ in range(N)] for _ in range(N)] for i in range(N): for j in range(N): for k in range(N): C[i][j] += A[i][k] * B[k][j] return C # Function to calculate the power of a matrixdef matrix_power(M: List[List[float]], p: int, n: int) -> List[List[float]]: A = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): A[i][i] = 1 while (p): if (p % 2): A = multiply(A, M, n) M = multiply(M, M, n) p //= 2 return A # Function to calculate the probability of# reaching F at time T after starting from Sdef findProbability(M: List[List[float]], N: int, F: int, S: int, T: int) -> float: # Storing M^T in MT MT = matrix_power(M, T, N) # Returning the answer return MT[F - 1][S - 1] # Driver codeif __name__ == "__main__": # Adjacency matrix # The edges have been stored in the row # corresponding to their end-point G = [[0, 0.09, 0, 0, 0, 0], [0.23, 0, 0, 0, 0, 0.62], [0, 0.06, 0, 0, 0, 0], [0.77, 0, 0.63, 0, 0, 0], [0, 0, 0, 0.65, 0, 0.38], [0, 0.85, 0.37, 0.35, 1.0, 0]] # N is the number of states N = 6 S = 4 F = 2 T = 100 print( "The probability of reaching {} at time {}\nafter starting from {} is {}\n" .format(F, T, S, findProbability(G, N, F, S, T))) # This code is contributed by sanjeev2552
// C# implementation of the above approachusing System; class GFG{ // Function to multiply two matrices A and B static double[,] multiply(double[,] A, double[,] B, int N) { double[,] C = new double[N, N]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) C[i, j] += A[i, k] * B[k, j]; return C; } // Function to calculate the power of a matrix static double[,] matrix_power(double[,] M, int p, int n) { double[,] A = new double[n,n]; for (int i = 0; i < n; ++i) A[i, i] = 1; while (p > 0) { if (p % 2 == 1) A = multiply(A, M, n); M = multiply(M, M, n); p /= 2; } return A; } // Function to calculate the probability of // reaching F at time T after starting from S static double findProbability(double[,] M, int N, int F, int S, int T) { // Storing M^T in MT double[,] MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1, S - 1]; } // Driver code public static void Main(String[] args) { // Adjacency matrix // The edges have been stored in the row // corresponding to their end-point double[,] G = { { 0, 0.09, 0, 0, 0, 0 }, { 0.23, 0, 0, 0, 0, 0.62 }, { 0, 0.06, 0, 0, 0, 0 }, { 0.77, 0, 0.63, 0, 0, 0 }, { 0, 0, 0, 0.65, 0, 0.38 }, { 0, 0.85, 0.37, 0.35, 1.0, 0 } }; // N is the number of states int N = 6; int S = 4, F = 2, T = 100; Console.Write("The probability of reaching " + F + " at time " + T + "\nafter starting from " + S + " is {0:F6}", findProbability(G, N, F, S, T)); }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the above approach// Function to multiply two matrices A and Bfunction multiply(A, B, N){ var C = Array.from(Array(N), ()=>Array(N).fill(0)); for (var i = 0; i < N; ++i) for (var j = 0; j < N; ++j) for (var k = 0; k < N; ++k) C[i][j] += A[i][k] * B[k][j]; return C;} // Function to calculate the power of a matrixfunction matrix_power(M, p, n){ var A = Array.from(Array(n), ()=>Array(n).fill(0)); for (var i = 0; i < n; ++i) A[i][i] = 1; while (p > 0) { if (p % 2 == 1) A = multiply(A, M, n); M = multiply(M, M, n); p = parseInt(p/2); } return A;} // Function to calculate the probability of// reaching F at time T after starting from Sfunction findProbability(M, N, F, S, T){ // Storing M^T in MT var MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1][ S - 1];} // Driver code// Adjacency matrix// The edges have been stored in the row// corresponding to their end-pointvar G = [ [ 0, 0.09, 0, 0, 0, 0 ], [ 0.23, 0, 0, 0, 0, 0.62 ], [ 0, 0.06, 0, 0, 0, 0 ], [ 0.77, 0, 0.63, 0, 0, 0 ], [ 0, 0, 0, 0.65, 0, 0.38 ], [ 0, 0.85, 0.37, 0.35, 1.0, 0 ] ]; // N is the number of statesvar N = 6;var S = 4, F = 2, T = 100;document.write("The probability of reaching " + F + " at time " + T + "<br>after starting from " + S + " is " + findProbability(G, N, F, S, T).toFixed(6)); // This code is contributed by rrrtnx.</script>
The probability of reaching 2 at time 100
after starting from 4 is 0.284991
Time Complexity: O(N3 * logT) Space Complexity: O(N2)
vaibhav29498
Rajput-Ji
29AjayKumar
sanjeev2552
rrrtnx
matrix-exponentiation
Probability
Technical Scripter 2018
Graph
Mathematical
Matrix
Technical Scripter
Mathematical
Matrix
Graph
Probability
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Detect Cycle in a Directed Graph
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26713,
"s": 26685,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 27326,
"s": 26713,
"text": "Given a Markov chain G, we have the find the probability of reaching the state F at time t = T if we start from state S at time t = 0.A Markov chain is a random process consisting of various states and the probabilities of moving from one state to another. We can represent it using a directed graph where the nodes represent the states and the edges represent the probability of going from one node to another. It takes unit time to move from one node to another. The sum of the associated probabilities of the outgoing edges is one for every node.Consider the given Markov Chain( G ) as shown in below image: "
},
{
"code": null,
"e": 27338,
"s": 27326,
"text": "Examples: "
},
{
"code": null,
"e": 27524,
"s": 27338,
"text": "Input : S = 1, F = 2, T = 1\nOutput: 0.23\nWe start at state 1 at t = 0, \nso there is a probability of 0.23 \nthat we reach state 2 at t = 1.\n\nInput: S = 4, F = 2, T = 100\nOutput: 0.284992"
},
{
"code": null,
"e": 27877,
"s": 27526,
"text": "In the previous article, a dynamic programming approach is discussed with a time complexity of O(N2T), where N is the number of states. Matrix exponentiation approach: We can make an adjacency matrix for the Markov chain to represent the probabilities of transitions between the states. For example, the adjacency matrix for the graph given above is:"
},
{
"code": null,
"e": 28200,
"s": 27882,
"text": "We can observe that the probability distribution at time t is given by P(t) = M * P(t – 1), and the initial probability distribution P(0) is a zero vector with the Sth element being one. Using these results, we can get solve the recursive expression for P(t). For example, if we take S to be 3, then P(t) is given by,"
},
{
"code": null,
"e": 28527,
"s": 28205,
"text": "If we use effective matrix exponentiation technique, then the time complexity of this approach comes out to be O(N3 * log T). This approach performs better than the dynamic programming approach if the value of T is considerably higher than the number of states, i.e. N.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28531,
"s": 28527,
"text": "C++"
},
{
"code": null,
"e": 28536,
"s": 28531,
"text": "Java"
},
{
"code": null,
"e": 28544,
"s": 28536,
"text": "Python3"
},
{
"code": null,
"e": 28547,
"s": 28544,
"text": "C#"
},
{
"code": null,
"e": 28558,
"s": 28547,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Macro to define a vector of float#define vf vector<float> // Function to multiply two matrices A and Bvector<vf > multiply(vector<vf > A, vector<vf > B, int N){ vector<vf > C(N, vf(N, 0)); for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) C[i][j] += A[i][k] * B[k][j]; return C;} // Function to calculate the power of a matrixvector<vf > matrix_power(vector<vf > M, int p, int n){ vector<vf > A(n, vf(n, 0)); for (int i = 0; i < n; ++i) A[i][i] = 1; while (p) { if (p % 2) A = multiply(A, M, n); M = multiply(M, M, n); p /= 2; } return A;} // Function to calculate the probability of// reaching F at time T after starting from Sfloat findProbability(vector<vf > M, int N, int F, int S, int T){ // Storing M^T in MT vector<vf > MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1][S - 1];} // Driver codeint main(){ // Adjacency matrix // The edges have been stored in the row // corresponding to their end-point vector<vf > G{ { 0, 0.09, 0, 0, 0, 0 }, { 0.23, 0, 0, 0, 0, 0.62 }, { 0, 0.06, 0, 0, 0, 0 }, { 0.77, 0, 0.63, 0, 0, 0 }, { 0, 0, 0, 0.65, 0, 0.38 }, { 0, 0.85, 0.37, 0.35, 1.0, 0 }}; // N is the number of states int N = 6; int S = 4, F = 2, T = 100; cout << \"The probability of reaching \" << F << \" at time \" << T << \"\\nafter starting from \" << S << \" is \" << findProbability(G, N, F, S, T); return 0;}",
"e": 30322,
"s": 28558,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ // Function to multiply two matrices A and B static double[][] multiply(double[][] A, double[][] B, int N) { double[][] C = new double[N][N]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) C[i][j] += A[i][k] * B[k][j]; return C; } // Function to calculate the power of a matrix static double[][] matrix_power(double[][] M, int p, int n) { double[][] A = new double[n][n]; for (int i = 0; i < n; ++i) A[i][i] = 1; while (p > 0) { if (p % 2 == 1) A = multiply(A, M, n); M = multiply(M, M, n); p /= 2; } return A; } // Function to calculate the probability of // reaching F at time T after starting from S static double findProbability(double[][] M, int N, int F, int S, int T) { // Storing M^T in MT double[][] MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1][S - 1]; } // Driver code public static void main(String[] args) { // Adjacency matrix // The edges have been stored in the row // corresponding to their end-point double[][] G = { { 0, 0.09, 0, 0, 0, 0 }, { 0.23, 0, 0, 0, 0, 0.62 }, { 0, 0.06, 0, 0, 0, 0 }, { 0.77, 0, 0.63, 0, 0, 0 }, { 0, 0, 0, 0.65, 0, 0.38 }, { 0, 0.85, 0.37, 0.35, 1.0, 0 } }; // N is the number of states int N = 6; int S = 4, F = 2, T = 100; System.out.printf( \"The probability of reaching \" + F + \" at time \" + T + \"\\nafter starting from \" + S + \" is %f\", findProbability(G, N, F, S, T)); }} // This code is contributed by Rajput-Ji",
"e": 32324,
"s": 30322,
"text": null
},
{
"code": "# Python implementation of the above approachfrom typing import List # Function to multiply two matrices A and Bdef multiply(A: List[List[float]], B: List[List[float]], N: int) -> List[List[float]]: C = [[0 for _ in range(N)] for _ in range(N)] for i in range(N): for j in range(N): for k in range(N): C[i][j] += A[i][k] * B[k][j] return C # Function to calculate the power of a matrixdef matrix_power(M: List[List[float]], p: int, n: int) -> List[List[float]]: A = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): A[i][i] = 1 while (p): if (p % 2): A = multiply(A, M, n) M = multiply(M, M, n) p //= 2 return A # Function to calculate the probability of# reaching F at time T after starting from Sdef findProbability(M: List[List[float]], N: int, F: int, S: int, T: int) -> float: # Storing M^T in MT MT = matrix_power(M, T, N) # Returning the answer return MT[F - 1][S - 1] # Driver codeif __name__ == \"__main__\": # Adjacency matrix # The edges have been stored in the row # corresponding to their end-point G = [[0, 0.09, 0, 0, 0, 0], [0.23, 0, 0, 0, 0, 0.62], [0, 0.06, 0, 0, 0, 0], [0.77, 0, 0.63, 0, 0, 0], [0, 0, 0, 0.65, 0, 0.38], [0, 0.85, 0.37, 0.35, 1.0, 0]] # N is the number of states N = 6 S = 4 F = 2 T = 100 print( \"The probability of reaching {} at time {}\\nafter starting from {} is {}\\n\" .format(F, T, S, findProbability(G, N, F, S, T))) # This code is contributed by sanjeev2552",
"e": 33936,
"s": 32324,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to multiply two matrices A and B static double[,] multiply(double[,] A, double[,] B, int N) { double[,] C = new double[N, N]; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) C[i, j] += A[i, k] * B[k, j]; return C; } // Function to calculate the power of a matrix static double[,] matrix_power(double[,] M, int p, int n) { double[,] A = new double[n,n]; for (int i = 0; i < n; ++i) A[i, i] = 1; while (p > 0) { if (p % 2 == 1) A = multiply(A, M, n); M = multiply(M, M, n); p /= 2; } return A; } // Function to calculate the probability of // reaching F at time T after starting from S static double findProbability(double[,] M, int N, int F, int S, int T) { // Storing M^T in MT double[,] MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1, S - 1]; } // Driver code public static void Main(String[] args) { // Adjacency matrix // The edges have been stored in the row // corresponding to their end-point double[,] G = { { 0, 0.09, 0, 0, 0, 0 }, { 0.23, 0, 0, 0, 0, 0.62 }, { 0, 0.06, 0, 0, 0, 0 }, { 0.77, 0, 0.63, 0, 0, 0 }, { 0, 0, 0, 0.65, 0, 0.38 }, { 0, 0.85, 0.37, 0.35, 1.0, 0 } }; // N is the number of states int N = 6; int S = 4, F = 2, T = 100; Console.Write(\"The probability of reaching \" + F + \" at time \" + T + \"\\nafter starting from \" + S + \" is {0:F6}\", findProbability(G, N, F, S, T)); }} // This code is contributed by 29AjayKumar",
"e": 35941,
"s": 33936,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach// Function to multiply two matrices A and Bfunction multiply(A, B, N){ var C = Array.from(Array(N), ()=>Array(N).fill(0)); for (var i = 0; i < N; ++i) for (var j = 0; j < N; ++j) for (var k = 0; k < N; ++k) C[i][j] += A[i][k] * B[k][j]; return C;} // Function to calculate the power of a matrixfunction matrix_power(M, p, n){ var A = Array.from(Array(n), ()=>Array(n).fill(0)); for (var i = 0; i < n; ++i) A[i][i] = 1; while (p > 0) { if (p % 2 == 1) A = multiply(A, M, n); M = multiply(M, M, n); p = parseInt(p/2); } return A;} // Function to calculate the probability of// reaching F at time T after starting from Sfunction findProbability(M, N, F, S, T){ // Storing M^T in MT var MT = matrix_power(M, T, N); // Returning the answer return MT[F - 1][ S - 1];} // Driver code// Adjacency matrix// The edges have been stored in the row// corresponding to their end-pointvar G = [ [ 0, 0.09, 0, 0, 0, 0 ], [ 0.23, 0, 0, 0, 0, 0.62 ], [ 0, 0.06, 0, 0, 0, 0 ], [ 0.77, 0, 0.63, 0, 0, 0 ], [ 0, 0, 0, 0.65, 0, 0.38 ], [ 0, 0.85, 0.37, 0.35, 1.0, 0 ] ]; // N is the number of statesvar N = 6;var S = 4, F = 2, T = 100;document.write(\"The probability of reaching \" + F + \" at time \" + T + \"<br>after starting from \" + S + \" is \" + findProbability(G, N, F, S, T).toFixed(6)); // This code is contributed by rrrtnx.</script>",
"e": 37555,
"s": 35941,
"text": null
},
{
"code": null,
"e": 37631,
"s": 37555,
"text": "The probability of reaching 2 at time 100\nafter starting from 4 is 0.284991"
},
{
"code": null,
"e": 37688,
"s": 37633,
"text": "Time Complexity: O(N3 * logT) Space Complexity: O(N2) "
},
{
"code": null,
"e": 37701,
"s": 37688,
"text": "vaibhav29498"
},
{
"code": null,
"e": 37711,
"s": 37701,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37723,
"s": 37711,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37735,
"s": 37723,
"text": "sanjeev2552"
},
{
"code": null,
"e": 37742,
"s": 37735,
"text": "rrrtnx"
},
{
"code": null,
"e": 37764,
"s": 37742,
"text": "matrix-exponentiation"
},
{
"code": null,
"e": 37776,
"s": 37764,
"text": "Probability"
},
{
"code": null,
"e": 37800,
"s": 37776,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 37806,
"s": 37800,
"text": "Graph"
},
{
"code": null,
"e": 37819,
"s": 37806,
"text": "Mathematical"
},
{
"code": null,
"e": 37826,
"s": 37819,
"text": "Matrix"
},
{
"code": null,
"e": 37845,
"s": 37826,
"text": "Technical Scripter"
},
{
"code": null,
"e": 37858,
"s": 37845,
"text": "Mathematical"
},
{
"code": null,
"e": 37865,
"s": 37858,
"text": "Matrix"
},
{
"code": null,
"e": 37871,
"s": 37865,
"text": "Graph"
},
{
"code": null,
"e": 37883,
"s": 37871,
"text": "Probability"
},
{
"code": null,
"e": 37981,
"s": 37883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38039,
"s": 37981,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 38059,
"s": 38039,
"text": "Topological Sorting"
},
{
"code": null,
"e": 38090,
"s": 38059,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 38123,
"s": 38090,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 38156,
"s": 38123,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 38186,
"s": 38156,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38246,
"s": 38186,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38261,
"s": 38246,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38304,
"s": 38261,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Python program to check if a given string is Keyword or not - GeeksforGeeks | 07 Feb, 2019
Given a string, write a Python program that checks if the given string is keyword or not.
Keywords are reserved words which cannot be used as variable names.
There are 33 keywords in Python programming language.(in python 3.6.2 version)
Examples:
Input: str = "geeks"
Output: geeks is not a keyword
Input: str = "for"
Output: for is a keyword
We can always get the list of keywords in the current Python version using kwlist method in keyword module.
# import keyword libraryimport keyword keyword_list = keyword.kwlistprint("No. of keywords present in current version :", len(keyword_list)) print(keyword_list)
No. of keywords present in current version : 33[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
Below is the Python code to check if a given string is Keyword or not:
# include keyword library in this programimport keyword # Function to check whether the given # string is a keyword or not def isKeyword(word) : # kwlist attribute of keyword # library return list of keywords # present in current version of # python language. keyword_list = keyword.kwlist # check word in present in # keyword_list or not. if word in keyword_list : return "Yes" else : return "No" # Driver Codeif __name__ == "__main__" : print(isKeyword("geeks")) print(isKeyword("for"))
No
Yes
python-string
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n07 Feb, 2019"
},
{
"code": null,
"e": 25651,
"s": 25561,
"text": "Given a string, write a Python program that checks if the given string is keyword or not."
},
{
"code": null,
"e": 25719,
"s": 25651,
"text": "Keywords are reserved words which cannot be used as variable names."
},
{
"code": null,
"e": 25798,
"s": 25719,
"text": "There are 33 keywords in Python programming language.(in python 3.6.2 version)"
},
{
"code": null,
"e": 25808,
"s": 25798,
"text": "Examples:"
},
{
"code": null,
"e": 25906,
"s": 25808,
"text": "Input: str = \"geeks\"\nOutput: geeks is not a keyword\n\nInput: str = \"for\"\nOutput: for is a keyword\n"
},
{
"code": null,
"e": 26014,
"s": 25906,
"text": "We can always get the list of keywords in the current Python version using kwlist method in keyword module."
},
{
"code": "# import keyword libraryimport keyword keyword_list = keyword.kwlistprint(\"No. of keywords present in current version :\", len(keyword_list)) print(keyword_list)",
"e": 26211,
"s": 26014,
"text": null
},
{
"code": null,
"e": 26536,
"s": 26211,
"text": "No. of keywords present in current version : 33[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]"
},
{
"code": null,
"e": 26607,
"s": 26536,
"text": "Below is the Python code to check if a given string is Keyword or not:"
},
{
"code": "# include keyword library in this programimport keyword # Function to check whether the given # string is a keyword or not def isKeyword(word) : # kwlist attribute of keyword # library return list of keywords # present in current version of # python language. keyword_list = keyword.kwlist # check word in present in # keyword_list or not. if word in keyword_list : return \"Yes\" else : return \"No\" # Driver Codeif __name__ == \"__main__\" : print(isKeyword(\"geeks\")) print(isKeyword(\"for\"))",
"e": 27153,
"s": 26607,
"text": null
},
{
"code": null,
"e": 27161,
"s": 27153,
"text": "No\nYes\n"
},
{
"code": null,
"e": 27175,
"s": 27161,
"text": "python-string"
},
{
"code": null,
"e": 27182,
"s": 27175,
"text": "Python"
},
{
"code": null,
"e": 27198,
"s": 27182,
"text": "Python Programs"
},
{
"code": null,
"e": 27296,
"s": 27198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27328,
"s": 27296,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27370,
"s": 27328,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27412,
"s": 27370,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27439,
"s": 27412,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27495,
"s": 27439,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27517,
"s": 27495,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27556,
"s": 27517,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27602,
"s": 27556,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27640,
"s": 27602,
"text": "Python | Convert a list to dictionary"
}
] |
Least number to be added to or subtracted from N to make it a Perfect Cube - GeeksforGeeks | 30 Mar, 2020
Given a number N, Find the minimum number that needs to be added to or subtracted from N, to make it a perfect cube. If the number is to be added, print it with a + sign, else if the number is to be subtracted, print it with a – sign.
Examples:
Input: N = 25Output: 2Nearest perfect cube before 25 = 8Nearest perfect cube after 25 = 27Therefore 2 needs to be added to 25 to get the closest perfect cube
Input: N = 40Output: -13Nearest perfect cube before 40 = 25Nearest perfect cube after 40 = 64Therefore 13 needs to be subtracted from 40 to get the closest perfect cube
Approach:
Get the number.Find the cube root of the number and convert the result as an integer.After converting the double value to integer, this will contain the root of the perfect cube before N, i.e. floor(cube root(N)).Then find the cube of this number, which will be the perfect cube before N.Find the root of the perfect cube after N, i.e. the ceil(cube root(N)).Then find the cube of this number, which will be the perfect cube after N.Check whether the cube of floor value is nearest to N or the ceil value.If the cube of floor value is nearest to N, print the difference with a -sign. Else print the difference between the cube of the ceil value and N with a + sign.
Get the number.
Find the cube root of the number and convert the result as an integer.
After converting the double value to integer, this will contain the root of the perfect cube before N, i.e. floor(cube root(N)).
Then find the cube of this number, which will be the perfect cube before N.
Find the root of the perfect cube after N, i.e. the ceil(cube root(N)).
Then find the cube of this number, which will be the perfect cube after N.
Check whether the cube of floor value is nearest to N or the ceil value.
If the cube of floor value is nearest to N, print the difference with a -sign. Else print the difference between the cube of the ceil value and N with a + sign.
Below is the implementation of the above approach:
C++
Java
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the Least numberint nearest(int n){ // Get the perfect cube // before and after N int prevCube = cbrt(n); int nextCube = prevCube + 1; prevCube = prevCube * prevCube * prevCube; nextCube = nextCube * nextCube * nextCube; // Check which is nearest to N int ans = (n - prevCube) < (nextCube - n) ? (prevCube - n) : (nextCube - n); // return the result return ans;} // Driver codeint main(){ int n = 25; cout << nearest(n) << endl; n = 27; cout << nearest(n) << endl; n = 40; cout << nearest(n) << endl; return 0;}
// Java implementation of the approach class GFG { // Function to return the Least number static int nearest(int n) { // Get the perfect cube // before and after N int prevCube = (int)Math.cbrt(n); int nextCube = prevCube + 1; prevCube = prevCube * prevCube * prevCube; nextCube = nextCube * nextCube * nextCube; // Check which is nearest to N int ans = (n - prevCube) < (nextCube - n) ? (prevCube - n) : (nextCube - n); // return the result return ans; } // Driver code public static void main (String[] args) { int n = 25; System.out.println(nearest(n)); n = 27; System.out.println(nearest(n)) ; n = 40; System.out.println(nearest(n)) ; } } // This code is contributed by Yash_R
2
0
-13
Yash_R
maths-perfect-cube
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 25805,
"s": 25777,
"text": "\n30 Mar, 2020"
},
{
"code": null,
"e": 26040,
"s": 25805,
"text": "Given a number N, Find the minimum number that needs to be added to or subtracted from N, to make it a perfect cube. If the number is to be added, print it with a + sign, else if the number is to be subtracted, print it with a – sign."
},
{
"code": null,
"e": 26050,
"s": 26040,
"text": "Examples:"
},
{
"code": null,
"e": 26208,
"s": 26050,
"text": "Input: N = 25Output: 2Nearest perfect cube before 25 = 8Nearest perfect cube after 25 = 27Therefore 2 needs to be added to 25 to get the closest perfect cube"
},
{
"code": null,
"e": 26377,
"s": 26208,
"text": "Input: N = 40Output: -13Nearest perfect cube before 40 = 25Nearest perfect cube after 40 = 64Therefore 13 needs to be subtracted from 40 to get the closest perfect cube"
},
{
"code": null,
"e": 26387,
"s": 26377,
"text": "Approach:"
},
{
"code": null,
"e": 27053,
"s": 26387,
"text": "Get the number.Find the cube root of the number and convert the result as an integer.After converting the double value to integer, this will contain the root of the perfect cube before N, i.e. floor(cube root(N)).Then find the cube of this number, which will be the perfect cube before N.Find the root of the perfect cube after N, i.e. the ceil(cube root(N)).Then find the cube of this number, which will be the perfect cube after N.Check whether the cube of floor value is nearest to N or the ceil value.If the cube of floor value is nearest to N, print the difference with a -sign. Else print the difference between the cube of the ceil value and N with a + sign."
},
{
"code": null,
"e": 27069,
"s": 27053,
"text": "Get the number."
},
{
"code": null,
"e": 27140,
"s": 27069,
"text": "Find the cube root of the number and convert the result as an integer."
},
{
"code": null,
"e": 27269,
"s": 27140,
"text": "After converting the double value to integer, this will contain the root of the perfect cube before N, i.e. floor(cube root(N))."
},
{
"code": null,
"e": 27345,
"s": 27269,
"text": "Then find the cube of this number, which will be the perfect cube before N."
},
{
"code": null,
"e": 27417,
"s": 27345,
"text": "Find the root of the perfect cube after N, i.e. the ceil(cube root(N))."
},
{
"code": null,
"e": 27492,
"s": 27417,
"text": "Then find the cube of this number, which will be the perfect cube after N."
},
{
"code": null,
"e": 27565,
"s": 27492,
"text": "Check whether the cube of floor value is nearest to N or the ceil value."
},
{
"code": null,
"e": 27726,
"s": 27565,
"text": "If the cube of floor value is nearest to N, print the difference with a -sign. Else print the difference between the cube of the ceil value and N with a + sign."
},
{
"code": null,
"e": 27777,
"s": 27726,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27781,
"s": 27777,
"text": "C++"
},
{
"code": null,
"e": 27786,
"s": 27781,
"text": "Java"
},
{
"code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the Least numberint nearest(int n){ // Get the perfect cube // before and after N int prevCube = cbrt(n); int nextCube = prevCube + 1; prevCube = prevCube * prevCube * prevCube; nextCube = nextCube * nextCube * nextCube; // Check which is nearest to N int ans = (n - prevCube) < (nextCube - n) ? (prevCube - n) : (nextCube - n); // return the result return ans;} // Driver codeint main(){ int n = 25; cout << nearest(n) << endl; n = 27; cout << nearest(n) << endl; n = 40; cout << nearest(n) << endl; return 0;}",
"e": 28502,
"s": 27786,
"text": null
},
{
"code": "// Java implementation of the approach class GFG { // Function to return the Least number static int nearest(int n) { // Get the perfect cube // before and after N int prevCube = (int)Math.cbrt(n); int nextCube = prevCube + 1; prevCube = prevCube * prevCube * prevCube; nextCube = nextCube * nextCube * nextCube; // Check which is nearest to N int ans = (n - prevCube) < (nextCube - n) ? (prevCube - n) : (nextCube - n); // return the result return ans; } // Driver code public static void main (String[] args) { int n = 25; System.out.println(nearest(n)); n = 27; System.out.println(nearest(n)) ; n = 40; System.out.println(nearest(n)) ; } } // This code is contributed by Yash_R",
"e": 29404,
"s": 28502,
"text": null
},
{
"code": null,
"e": 29413,
"s": 29404,
"text": "2\n0\n-13\n"
},
{
"code": null,
"e": 29420,
"s": 29413,
"text": "Yash_R"
},
{
"code": null,
"e": 29439,
"s": 29420,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 29452,
"s": 29439,
"text": "Mathematical"
},
{
"code": null,
"e": 29471,
"s": 29452,
"text": "School Programming"
},
{
"code": null,
"e": 29484,
"s": 29471,
"text": "Mathematical"
},
{
"code": null,
"e": 29582,
"s": 29484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29606,
"s": 29582,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 29649,
"s": 29606,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29663,
"s": 29649,
"text": "Prime Numbers"
},
{
"code": null,
"e": 29705,
"s": 29663,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 29727,
"s": 29705,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 29745,
"s": 29727,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29761,
"s": 29745,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29780,
"s": 29761,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29805,
"s": 29780,
"text": "Reverse a string in Java"
}
] |
Maths Commands in LaTeX - GeeksforGeeks | 20 Jun, 2020
LATEX is a document preparation system for producing professional-looking documents. LaTeX is widely used for the communication and publication of scientific documents in many fields, including mathematics, statistics, computer science, engineering, physics, etc. It also has a prominent role in the preparation and publication of books and articles that contain complex multilingual materials, such as Sanskrit and Greek.
So in this post we have discussed the most used TEX commands used for Maths.
Fractions:Instead of writing fractions as A / B we will use below syntaxSyntax :\frac{numerator}{denominator}
Example –\frac{a+1}{b+1}
OUTPUT:Nth power:Instead of writing powers as x ^ n which is not clear as if it is xor or power so we will use below syntaxSyntax:x^y
Example –x^2
OUTPUT:Nth root:Instead of writing roots as x^(1/N) which is not clear as if it is xor or root so we will use below syntaxSyntax:\sqrt[N]{27}
Example –\sqrt[3]{27}
OUTPUT:MatricesInstead of writing matrices as [[1, x, x^2], [1, y, y^2][1, z, z^2]] which is not very clear use below syntaxSyntax:\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
Example –\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
OUTPUT:Definitions by cases (piecewise function) is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: f(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\
n+1, & \text{if $n$ is odd}
\end{cases}
Example – f(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\
n+1, & \text{if $n$ is odd}
\end{cases}
OUTPUT:System of equations is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: \left\{
\begin{array}{c}
a_1x+b_1y+c_1z=d_1 \\
a_2x+b_2y+c_2z=d_2 \\
a_3x+b_3y+c_3z=d_3
\end{array}
\right.
Example – \left\{
\begin{array}{c}
a_1x+b_1y+c_1z=d_1 \\
a_2x+b_2y+c_2z=d_2 \\
a_3x+b_3y+c_3z=d_3
\end{array}
\right.
OUTPUT:Summation is the addition of a sequence of any kind of numbers, called addends or summands; the result is their sum or total.Syntax:\sum_{i=0}^n i^2
Example –\sum_{i=0}^n i^2
OUTPUT:subscriptsis a character that is set slightly below the normal line of type.Syntax:\log_2 x
Example –\log_2 x
OUTPUT:floor is the function that takes as input a real number and gives as output the greatest integer less than or equal to, denoted.Syntax:\lfloor n \rfloor
Example –\lfloor 2.2 \rfloor
OUTPUT:ceil function maps to the least integer greater than or equal to, denoted.Syntax:\lceil n \rcei
Example –\lceil 2.5 \rceil
OUTPUT:Some Combined examples :Example –Use\sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}for Example –Use\left(\frac{\sqrt x}{y^3}\right)for Example –Use\Biggl(\biggl(\Bigl(\bigl((n)\bigr)\Bigr)\biggr)\Biggr)for Example –Use\sqrt[3]{\frac xy}for
Fractions:Instead of writing fractions as A / B we will use below syntaxSyntax :\frac{numerator}{denominator}
Example –\frac{a+1}{b+1}
OUTPUT:
\frac{numerator}{denominator}
Example –
\frac{a+1}{b+1}
OUTPUT:
Nth power:Instead of writing powers as x ^ n which is not clear as if it is xor or power so we will use below syntaxSyntax:x^y
Example –x^2
OUTPUT:
x^y
Example –
x^2
OUTPUT:
Nth root:Instead of writing roots as x^(1/N) which is not clear as if it is xor or root so we will use below syntaxSyntax:\sqrt[N]{27}
Example –\sqrt[3]{27}
OUTPUT:
\sqrt[N]{27}
Example –
\sqrt[3]{27}
OUTPUT:
MatricesInstead of writing matrices as [[1, x, x^2], [1, y, y^2][1, z, z^2]] which is not very clear use below syntaxSyntax:\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
Example –\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
OUTPUT:
\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
Example –
\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
OUTPUT:
Definitions by cases (piecewise function) is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: f(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\
n+1, & \text{if $n$ is odd}
\end{cases}
Example – f(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\
n+1, & \text{if $n$ is odd}
\end{cases}
OUTPUT:
Syntax:
f(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\
n+1, & \text{if $n$ is odd}
\end{cases}
Example –
f(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\
n+1, & \text{if $n$ is odd}
\end{cases}
OUTPUT:
System of equations is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: \left\{
\begin{array}{c}
a_1x+b_1y+c_1z=d_1 \\
a_2x+b_2y+c_2z=d_2 \\
a_3x+b_3y+c_3z=d_3
\end{array}
\right.
Example – \left\{
\begin{array}{c}
a_1x+b_1y+c_1z=d_1 \\
a_2x+b_2y+c_2z=d_2 \\
a_3x+b_3y+c_3z=d_3
\end{array}
\right.
OUTPUT:
Syntax:
\left\{
\begin{array}{c}
a_1x+b_1y+c_1z=d_1 \\
a_2x+b_2y+c_2z=d_2 \\
a_3x+b_3y+c_3z=d_3
\end{array}
\right.
Example –
\left\{
\begin{array}{c}
a_1x+b_1y+c_1z=d_1 \\
a_2x+b_2y+c_2z=d_2 \\
a_3x+b_3y+c_3z=d_3
\end{array}
\right.
OUTPUT:
Summation is the addition of a sequence of any kind of numbers, called addends or summands; the result is their sum or total.Syntax:\sum_{i=0}^n i^2
Example –\sum_{i=0}^n i^2
OUTPUT:
Syntax:
\sum_{i=0}^n i^2
Example –
\sum_{i=0}^n i^2
OUTPUT:
subscriptsis a character that is set slightly below the normal line of type.Syntax:\log_2 x
Example –\log_2 x
OUTPUT:
Syntax:
\log_2 x
Example –
\log_2 x
OUTPUT:
floor is the function that takes as input a real number and gives as output the greatest integer less than or equal to, denoted.Syntax:\lfloor n \rfloor
Example –\lfloor 2.2 \rfloor
OUTPUT:
Syntax:
\lfloor n \rfloor
Example –
\lfloor 2.2 \rfloor
OUTPUT:
ceil function maps to the least integer greater than or equal to, denoted.Syntax:\lceil n \rcei
Example –\lceil 2.5 \rceil
OUTPUT:
Syntax:
\lceil n \rcei
Example –
\lceil 2.5 \rceil
OUTPUT:
Some Combined examples :Example –Use\sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}for Example –Use\left(\frac{\sqrt x}{y^3}\right)for Example –Use\Biggl(\biggl(\Bigl(\bigl((n)\bigr)\Bigr)\biggr)\Biggr)for Example –Use\sqrt[3]{\frac xy}for
Use\sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}for Example –
\sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}
for
Example –
Use\left(\frac{\sqrt x}{y^3}\right)for Example –
\left(\frac{\sqrt x}{y^3}\right)
for
Example –
Use\Biggl(\biggl(\Bigl(\bigl((n)\bigr)\Bigr)\biggr)\Biggr)for Example –
\Biggl(\biggl(\Bigl(\bigl((n)\bigr)\Bigr)\biggr)\Biggr)
for
Example –
Use\sqrt[3]{\frac xy}for
\sqrt[3]{\frac xy}
for
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Newton's Divided Difference Interpolation Formula
Discrete Mathematics | Hasse Diagrams
Difference between Propositional Logic and Predicate Logic
Mathematics | Graph Isomorphisms and Connectivity
Mathematics | Euler and Hamiltonian Paths
Graph measurements: length, distance, diameter, eccentricity, radius, center
Mathematics | Graph Theory Basics - Set 1
Number of Possible Super Keys in DBMS | [
{
"code": null,
"e": 25732,
"s": 25704,
"text": "\n20 Jun, 2020"
},
{
"code": null,
"e": 26155,
"s": 25732,
"text": "LATEX is a document preparation system for producing professional-looking documents. LaTeX is widely used for the communication and publication of scientific documents in many fields, including mathematics, statistics, computer science, engineering, physics, etc. It also has a prominent role in the preparation and publication of books and articles that contain complex multilingual materials, such as Sanskrit and Greek."
},
{
"code": null,
"e": 26232,
"s": 26155,
"text": "So in this post we have discussed the most used TEX commands used for Maths."
},
{
"code": null,
"e": 28657,
"s": 26232,
"text": "Fractions:Instead of writing fractions as A / B we will use below syntaxSyntax :\\frac{numerator}{denominator}\nExample –\\frac{a+1}{b+1}\nOUTPUT:Nth power:Instead of writing powers as x ^ n which is not clear as if it is xor or power so we will use below syntaxSyntax:x^y\nExample –x^2\nOUTPUT:Nth root:Instead of writing roots as x^(1/N) which is not clear as if it is xor or root so we will use below syntaxSyntax:\\sqrt[N]{27}\nExample –\\sqrt[3]{27}\nOUTPUT:MatricesInstead of writing matrices as [[1, x, x^2], [1, y, y^2][1, z, z^2]] which is not very clear use below syntaxSyntax:\\begin{matrix}\n 1 & x & x^2 \\\\\n 1 & y & y^2 \\\\\n 1 & z & z^2 \\\\\n\\end{matrix}\nExample –\\begin{matrix}\n 1 & x & x^2 \\\\\n 1 & y & y^2 \\\\\n 1 & z & z^2 \\\\\n\\end{matrix}\nOUTPUT:Definitions by cases (piecewise function) is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: f(n) =\n\\begin{cases}\nn/2, & \\text{if $n$ is even} \\\\\nn+1, & \\text{if $n$ is odd}\n\\end{cases}\nExample – f(n) =\n\\begin{cases}\nn/2, & \\text{if $n$ is even} \\\\\nn+1, & \\text{if $n$ is odd}\n\\end{cases}\nOUTPUT:System of equations is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: \\left\\{ \n\\begin{array}{c}\na_1x+b_1y+c_1z=d_1 \\\\ \na_2x+b_2y+c_2z=d_2 \\\\ \na_3x+b_3y+c_3z=d_3\n\\end{array}\n\\right. \nExample – \\left\\{ \n\\begin{array}{c}\na_1x+b_1y+c_1z=d_1 \\\\ \na_2x+b_2y+c_2z=d_2 \\\\ \na_3x+b_3y+c_3z=d_3\n\\end{array}\n\\right. \nOUTPUT:Summation is the addition of a sequence of any kind of numbers, called addends or summands; the result is their sum or total.Syntax:\\sum_{i=0}^n i^2\nExample –\\sum_{i=0}^n i^2\nOUTPUT:subscriptsis a character that is set slightly below the normal line of type.Syntax:\\log_2 x\nExample –\\log_2 x\nOUTPUT:floor is the function that takes as input a real number and gives as output the greatest integer less than or equal to, denoted.Syntax:\\lfloor n \\rfloor\nExample –\\lfloor 2.2 \\rfloor\nOUTPUT:ceil function maps to the least integer greater than or equal to, denoted.Syntax:\\lceil n \\rcei\nExample –\\lceil 2.5 \\rceil\nOUTPUT:Some Combined examples :Example –Use\\sum_{i=0}^n i^2 = \\frac{(n^2+n)(2n+1)}{6}for Example –Use\\left(\\frac{\\sqrt x}{y^3}\\right)for Example –Use\\Biggl(\\biggl(\\Bigl(\\bigl((n)\\bigr)\\Bigr)\\biggr)\\Biggr)for Example –Use\\sqrt[3]{\\frac xy}for "
},
{
"code": null,
"e": 28800,
"s": 28657,
"text": "Fractions:Instead of writing fractions as A / B we will use below syntaxSyntax :\\frac{numerator}{denominator}\nExample –\\frac{a+1}{b+1}\nOUTPUT:"
},
{
"code": null,
"e": 28831,
"s": 28800,
"text": "\\frac{numerator}{denominator}\n"
},
{
"code": null,
"e": 28841,
"s": 28831,
"text": "Example –"
},
{
"code": null,
"e": 28858,
"s": 28841,
"text": "\\frac{a+1}{b+1}\n"
},
{
"code": null,
"e": 28866,
"s": 28858,
"text": "OUTPUT:"
},
{
"code": null,
"e": 29014,
"s": 28866,
"text": "Nth power:Instead of writing powers as x ^ n which is not clear as if it is xor or power so we will use below syntaxSyntax:x^y\nExample –x^2\nOUTPUT:"
},
{
"code": null,
"e": 29019,
"s": 29014,
"text": "x^y\n"
},
{
"code": null,
"e": 29029,
"s": 29019,
"text": "Example –"
},
{
"code": null,
"e": 29034,
"s": 29029,
"text": "x^2\n"
},
{
"code": null,
"e": 29042,
"s": 29034,
"text": "OUTPUT:"
},
{
"code": null,
"e": 29207,
"s": 29042,
"text": "Nth root:Instead of writing roots as x^(1/N) which is not clear as if it is xor or root so we will use below syntaxSyntax:\\sqrt[N]{27}\nExample –\\sqrt[3]{27}\nOUTPUT:"
},
{
"code": null,
"e": 29221,
"s": 29207,
"text": "\\sqrt[N]{27}\n"
},
{
"code": null,
"e": 29231,
"s": 29221,
"text": "Example –"
},
{
"code": null,
"e": 29245,
"s": 29231,
"text": "\\sqrt[3]{27}\n"
},
{
"code": null,
"e": 29253,
"s": 29245,
"text": "OUTPUT:"
},
{
"code": null,
"e": 29564,
"s": 29253,
"text": "MatricesInstead of writing matrices as [[1, x, x^2], [1, y, y^2][1, z, z^2]] which is not very clear use below syntaxSyntax:\\begin{matrix}\n 1 & x & x^2 \\\\\n 1 & y & y^2 \\\\\n 1 & z & z^2 \\\\\n\\end{matrix}\nExample –\\begin{matrix}\n 1 & x & x^2 \\\\\n 1 & y & y^2 \\\\\n 1 & z & z^2 \\\\\n\\end{matrix}\nOUTPUT:"
},
{
"code": null,
"e": 29650,
"s": 29564,
"text": "\\begin{matrix}\n 1 & x & x^2 \\\\\n 1 & y & y^2 \\\\\n 1 & z & z^2 \\\\\n\\end{matrix}\n"
},
{
"code": null,
"e": 29660,
"s": 29650,
"text": "Example –"
},
{
"code": null,
"e": 29746,
"s": 29660,
"text": "\\begin{matrix}\n 1 & x & x^2 \\\\\n 1 & y & y^2 \\\\\n 1 & z & z^2 \\\\\n\\end{matrix}\n"
},
{
"code": null,
"e": 29754,
"s": 29746,
"text": "OUTPUT:"
},
{
"code": null,
"e": 30152,
"s": 29754,
"text": "Definitions by cases (piecewise function) is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: f(n) =\n\\begin{cases}\nn/2, & \\text{if $n$ is even} \\\\\nn+1, & \\text{if $n$ is odd}\n\\end{cases}\nExample – f(n) =\n\\begin{cases}\nn/2, & \\text{if $n$ is even} \\\\\nn+1, & \\text{if $n$ is odd}\n\\end{cases}\nOUTPUT:"
},
{
"code": null,
"e": 30160,
"s": 30152,
"text": "Syntax:"
},
{
"code": null,
"e": 30256,
"s": 30160,
"text": " f(n) =\n\\begin{cases}\nn/2, & \\text{if $n$ is even} \\\\\nn+1, & \\text{if $n$ is odd}\n\\end{cases}\n"
},
{
"code": null,
"e": 30266,
"s": 30256,
"text": "Example –"
},
{
"code": null,
"e": 30362,
"s": 30266,
"text": " f(n) =\n\\begin{cases}\nn/2, & \\text{if $n$ is even} \\\\\nn+1, & \\text{if $n$ is odd}\n\\end{cases}\n"
},
{
"code": null,
"e": 30370,
"s": 30362,
"text": "OUTPUT:"
},
{
"code": null,
"e": 30782,
"s": 30370,
"text": "System of equations is a function defined by multiple sub-functions, each sub-function applying to a certain interval of the main function’s domain, a sub-domain.Syntax: \\left\\{ \n\\begin{array}{c}\na_1x+b_1y+c_1z=d_1 \\\\ \na_2x+b_2y+c_2z=d_2 \\\\ \na_3x+b_3y+c_3z=d_3\n\\end{array}\n\\right. \nExample – \\left\\{ \n\\begin{array}{c}\na_1x+b_1y+c_1z=d_1 \\\\ \na_2x+b_2y+c_2z=d_2 \\\\ \na_3x+b_3y+c_3z=d_3\n\\end{array}\n\\right. \nOUTPUT:"
},
{
"code": null,
"e": 30790,
"s": 30782,
"text": "Syntax:"
},
{
"code": null,
"e": 30904,
"s": 30790,
"text": " \\left\\{ \n\\begin{array}{c}\na_1x+b_1y+c_1z=d_1 \\\\ \na_2x+b_2y+c_2z=d_2 \\\\ \na_3x+b_3y+c_3z=d_3\n\\end{array}\n\\right. \n"
},
{
"code": null,
"e": 30914,
"s": 30904,
"text": "Example –"
},
{
"code": null,
"e": 31028,
"s": 30914,
"text": " \\left\\{ \n\\begin{array}{c}\na_1x+b_1y+c_1z=d_1 \\\\ \na_2x+b_2y+c_2z=d_2 \\\\ \na_3x+b_3y+c_3z=d_3\n\\end{array}\n\\right. \n"
},
{
"code": null,
"e": 31036,
"s": 31028,
"text": "OUTPUT:"
},
{
"code": null,
"e": 31219,
"s": 31036,
"text": "Summation is the addition of a sequence of any kind of numbers, called addends or summands; the result is their sum or total.Syntax:\\sum_{i=0}^n i^2\nExample –\\sum_{i=0}^n i^2\nOUTPUT:"
},
{
"code": null,
"e": 31227,
"s": 31219,
"text": "Syntax:"
},
{
"code": null,
"e": 31245,
"s": 31227,
"text": "\\sum_{i=0}^n i^2\n"
},
{
"code": null,
"e": 31255,
"s": 31245,
"text": "Example –"
},
{
"code": null,
"e": 31273,
"s": 31255,
"text": "\\sum_{i=0}^n i^2\n"
},
{
"code": null,
"e": 31281,
"s": 31273,
"text": "OUTPUT:"
},
{
"code": null,
"e": 31399,
"s": 31281,
"text": "subscriptsis a character that is set slightly below the normal line of type.Syntax:\\log_2 x\nExample –\\log_2 x\nOUTPUT:"
},
{
"code": null,
"e": 31407,
"s": 31399,
"text": "Syntax:"
},
{
"code": null,
"e": 31417,
"s": 31407,
"text": "\\log_2 x\n"
},
{
"code": null,
"e": 31427,
"s": 31417,
"text": "Example –"
},
{
"code": null,
"e": 31437,
"s": 31427,
"text": "\\log_2 x\n"
},
{
"code": null,
"e": 31445,
"s": 31437,
"text": "OUTPUT:"
},
{
"code": null,
"e": 31635,
"s": 31445,
"text": "floor is the function that takes as input a real number and gives as output the greatest integer less than or equal to, denoted.Syntax:\\lfloor n \\rfloor\nExample –\\lfloor 2.2 \\rfloor\nOUTPUT:"
},
{
"code": null,
"e": 31643,
"s": 31635,
"text": "Syntax:"
},
{
"code": null,
"e": 31662,
"s": 31643,
"text": "\\lfloor n \\rfloor\n"
},
{
"code": null,
"e": 31672,
"s": 31662,
"text": "Example –"
},
{
"code": null,
"e": 31693,
"s": 31672,
"text": "\\lfloor 2.2 \\rfloor\n"
},
{
"code": null,
"e": 31701,
"s": 31693,
"text": "OUTPUT:"
},
{
"code": null,
"e": 31832,
"s": 31701,
"text": "ceil function maps to the least integer greater than or equal to, denoted.Syntax:\\lceil n \\rcei\nExample –\\lceil 2.5 \\rceil\nOUTPUT:"
},
{
"code": null,
"e": 31840,
"s": 31832,
"text": "Syntax:"
},
{
"code": null,
"e": 31856,
"s": 31840,
"text": "\\lceil n \\rcei\n"
},
{
"code": null,
"e": 31866,
"s": 31856,
"text": "Example –"
},
{
"code": null,
"e": 31885,
"s": 31866,
"text": "\\lceil 2.5 \\rceil\n"
},
{
"code": null,
"e": 31893,
"s": 31885,
"text": "OUTPUT:"
},
{
"code": null,
"e": 32129,
"s": 31893,
"text": "Some Combined examples :Example –Use\\sum_{i=0}^n i^2 = \\frac{(n^2+n)(2n+1)}{6}for Example –Use\\left(\\frac{\\sqrt x}{y^3}\\right)for Example –Use\\Biggl(\\biggl(\\Bigl(\\bigl((n)\\bigr)\\Bigr)\\biggr)\\Biggr)for Example –Use\\sqrt[3]{\\frac xy}for "
},
{
"code": null,
"e": 32188,
"s": 32129,
"text": "Use\\sum_{i=0}^n i^2 = \\frac{(n^2+n)(2n+1)}{6}for Example –"
},
{
"code": null,
"e": 32231,
"s": 32188,
"text": "\\sum_{i=0}^n i^2 = \\frac{(n^2+n)(2n+1)}{6}"
},
{
"code": null,
"e": 32236,
"s": 32231,
"text": "for "
},
{
"code": null,
"e": 32246,
"s": 32236,
"text": "Example –"
},
{
"code": null,
"e": 32295,
"s": 32246,
"text": "Use\\left(\\frac{\\sqrt x}{y^3}\\right)for Example –"
},
{
"code": null,
"e": 32328,
"s": 32295,
"text": "\\left(\\frac{\\sqrt x}{y^3}\\right)"
},
{
"code": null,
"e": 32333,
"s": 32328,
"text": "for "
},
{
"code": null,
"e": 32343,
"s": 32333,
"text": "Example –"
},
{
"code": null,
"e": 32415,
"s": 32343,
"text": "Use\\Biggl(\\biggl(\\Bigl(\\bigl((n)\\bigr)\\Bigr)\\biggr)\\Biggr)for Example –"
},
{
"code": null,
"e": 32471,
"s": 32415,
"text": "\\Biggl(\\biggl(\\Bigl(\\bigl((n)\\bigr)\\Bigr)\\biggr)\\Biggr)"
},
{
"code": null,
"e": 32476,
"s": 32471,
"text": "for "
},
{
"code": null,
"e": 32486,
"s": 32476,
"text": "Example –"
},
{
"code": null,
"e": 32512,
"s": 32486,
"text": "Use\\sqrt[3]{\\frac xy}for "
},
{
"code": null,
"e": 32531,
"s": 32512,
"text": "\\sqrt[3]{\\frac xy}"
},
{
"code": null,
"e": 32536,
"s": 32531,
"text": "for "
},
{
"code": null,
"e": 32560,
"s": 32536,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 32658,
"s": 32560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32679,
"s": 32658,
"text": "Activation Functions"
},
{
"code": null,
"e": 32744,
"s": 32679,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 32794,
"s": 32744,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 32832,
"s": 32794,
"text": "Discrete Mathematics | Hasse Diagrams"
},
{
"code": null,
"e": 32891,
"s": 32832,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 32941,
"s": 32891,
"text": "Mathematics | Graph Isomorphisms and Connectivity"
},
{
"code": null,
"e": 32983,
"s": 32941,
"text": "Mathematics | Euler and Hamiltonian Paths"
},
{
"code": null,
"e": 33060,
"s": 32983,
"text": "Graph measurements: length, distance, diameter, eccentricity, radius, center"
},
{
"code": null,
"e": 33102,
"s": 33060,
"text": "Mathematics | Graph Theory Basics - Set 1"
}
] |
Advantages and Disadvantages of Subnetting - GeeksforGeeks | 27 Sep, 2019
Subnetting: Dividing a network into many small Networks is known as Subnetting.Subnetting is useful in many ways like:
It provides security to one network from another network. eg) In an Organisation, code of the Developer department must not be accessed by another department.It may be possible that a particular subnet might need higher network priority than others. For example, a Sales department need to host webcasts or video conferences.In the case of Small networks, maintenance is easy.
It provides security to one network from another network. eg) In an Organisation, code of the Developer department must not be accessed by another department.
It may be possible that a particular subnet might need higher network priority than others. For example, a Sales department need to host webcasts or video conferences.
In the case of Small networks, maintenance is easy.
Along with these advantages, Subnetting also has some disadvantages:
In case of the single network, only three steps are required in order to reach a Process i.e Source Host to Destination Network, Destination Network to Destination Host and then Destination Host to Process.But in the case of Subnetting four steps are required for Inter-Network Communication. i.e Source Host to Destination Network, Destination Network to proper Subnet, then Subnet to Host and finally Host to Process.Hence, it increases Time complexity. In the case of Subnet, more time is required for communication or data transfer.In the case of Single Network only two IP addresses are wasted to represent Network Id and Broadcast address but in case of Subnetting two IP addresses are wasted for each Subnet.Example: If a Network has four Subnets, it means 8 IP addresses are going to waste.Network Id for S1: 200.1.2.0
Broadcast address of S1: 200.1.2.63
Network Id for S2: 200.1.2.64
Broadcast address of S2: 200.1.2.127
Network Id for S3: 200.1.2.128
Broadcast address of S3: 200.1.2.191
Network Id for S4: 200.1.2.192
Direct Broadcast address of S4: 200.1.2.255Hence, we can say that Network size will also decrease. We can’t use our Network completely.Cost of the overall Network also increases. Subnetting requires internal routers, Switches, Hubs, Bridges etc. which are very costly.Subnetting and network management require an experienced network administrator. This adds to the overall cost as well.
In case of the single network, only three steps are required in order to reach a Process i.e Source Host to Destination Network, Destination Network to Destination Host and then Destination Host to Process.But in the case of Subnetting four steps are required for Inter-Network Communication. i.e Source Host to Destination Network, Destination Network to proper Subnet, then Subnet to Host and finally Host to Process.Hence, it increases Time complexity. In the case of Subnet, more time is required for communication or data transfer.
But in the case of Subnetting four steps are required for Inter-Network Communication. i.e Source Host to Destination Network, Destination Network to proper Subnet, then Subnet to Host and finally Host to Process.
Hence, it increases Time complexity. In the case of Subnet, more time is required for communication or data transfer.
In the case of Single Network only two IP addresses are wasted to represent Network Id and Broadcast address but in case of Subnetting two IP addresses are wasted for each Subnet.Example: If a Network has four Subnets, it means 8 IP addresses are going to waste.Network Id for S1: 200.1.2.0
Broadcast address of S1: 200.1.2.63
Network Id for S2: 200.1.2.64
Broadcast address of S2: 200.1.2.127
Network Id for S3: 200.1.2.128
Broadcast address of S3: 200.1.2.191
Network Id for S4: 200.1.2.192
Direct Broadcast address of S4: 200.1.2.255Hence, we can say that Network size will also decrease. We can’t use our Network completely.
Network Id for S1: 200.1.2.0
Broadcast address of S1: 200.1.2.63
Network Id for S2: 200.1.2.64
Broadcast address of S2: 200.1.2.127
Network Id for S3: 200.1.2.128
Broadcast address of S3: 200.1.2.191
Network Id for S4: 200.1.2.192
Direct Broadcast address of S4: 200.1.2.255
Hence, we can say that Network size will also decrease. We can’t use our Network completely.
Cost of the overall Network also increases. Subnetting requires internal routers, Switches, Hubs, Bridges etc. which are very costly.
Subnetting and network management require an experienced network administrator. This adds to the overall cost as well.
Stranger1
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Data encryption standard (DES) | Set 1
Types of Network Topology
Socket Programming in Python
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Cache Memory in Computer Organization | [
{
"code": null,
"e": 25689,
"s": 25661,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 25808,
"s": 25689,
"text": "Subnetting: Dividing a network into many small Networks is known as Subnetting.Subnetting is useful in many ways like:"
},
{
"code": null,
"e": 26185,
"s": 25808,
"text": "It provides security to one network from another network. eg) In an Organisation, code of the Developer department must not be accessed by another department.It may be possible that a particular subnet might need higher network priority than others. For example, a Sales department need to host webcasts or video conferences.In the case of Small networks, maintenance is easy."
},
{
"code": null,
"e": 26344,
"s": 26185,
"text": "It provides security to one network from another network. eg) In an Organisation, code of the Developer department must not be accessed by another department."
},
{
"code": null,
"e": 26512,
"s": 26344,
"text": "It may be possible that a particular subnet might need higher network priority than others. For example, a Sales department need to host webcasts or video conferences."
},
{
"code": null,
"e": 26564,
"s": 26512,
"text": "In the case of Small networks, maintenance is easy."
},
{
"code": null,
"e": 26633,
"s": 26564,
"text": "Along with these advantages, Subnetting also has some disadvantages:"
},
{
"code": null,
"e": 28052,
"s": 26633,
"text": "In case of the single network, only three steps are required in order to reach a Process i.e Source Host to Destination Network, Destination Network to Destination Host and then Destination Host to Process.But in the case of Subnetting four steps are required for Inter-Network Communication. i.e Source Host to Destination Network, Destination Network to proper Subnet, then Subnet to Host and finally Host to Process.Hence, it increases Time complexity. In the case of Subnet, more time is required for communication or data transfer.In the case of Single Network only two IP addresses are wasted to represent Network Id and Broadcast address but in case of Subnetting two IP addresses are wasted for each Subnet.Example: If a Network has four Subnets, it means 8 IP addresses are going to waste.Network Id for S1: 200.1.2.0\nBroadcast address of S1: 200.1.2.63\n\nNetwork Id for S2: 200.1.2.64\nBroadcast address of S2: 200.1.2.127\n\nNetwork Id for S3: 200.1.2.128\nBroadcast address of S3: 200.1.2.191\n\nNetwork Id for S4: 200.1.2.192\nDirect Broadcast address of S4: 200.1.2.255Hence, we can say that Network size will also decrease. We can’t use our Network completely.Cost of the overall Network also increases. Subnetting requires internal routers, Switches, Hubs, Bridges etc. which are very costly.Subnetting and network management require an experienced network administrator. This adds to the overall cost as well."
},
{
"code": null,
"e": 28589,
"s": 28052,
"text": "In case of the single network, only three steps are required in order to reach a Process i.e Source Host to Destination Network, Destination Network to Destination Host and then Destination Host to Process.But in the case of Subnetting four steps are required for Inter-Network Communication. i.e Source Host to Destination Network, Destination Network to proper Subnet, then Subnet to Host and finally Host to Process.Hence, it increases Time complexity. In the case of Subnet, more time is required for communication or data transfer."
},
{
"code": null,
"e": 28803,
"s": 28589,
"text": "But in the case of Subnetting four steps are required for Inter-Network Communication. i.e Source Host to Destination Network, Destination Network to proper Subnet, then Subnet to Host and finally Host to Process."
},
{
"code": null,
"e": 28921,
"s": 28803,
"text": "Hence, it increases Time complexity. In the case of Subnet, more time is required for communication or data transfer."
},
{
"code": null,
"e": 29553,
"s": 28921,
"text": "In the case of Single Network only two IP addresses are wasted to represent Network Id and Broadcast address but in case of Subnetting two IP addresses are wasted for each Subnet.Example: If a Network has four Subnets, it means 8 IP addresses are going to waste.Network Id for S1: 200.1.2.0\nBroadcast address of S1: 200.1.2.63\n\nNetwork Id for S2: 200.1.2.64\nBroadcast address of S2: 200.1.2.127\n\nNetwork Id for S3: 200.1.2.128\nBroadcast address of S3: 200.1.2.191\n\nNetwork Id for S4: 200.1.2.192\nDirect Broadcast address of S4: 200.1.2.255Hence, we can say that Network size will also decrease. We can’t use our Network completely."
},
{
"code": null,
"e": 29831,
"s": 29553,
"text": "Network Id for S1: 200.1.2.0\nBroadcast address of S1: 200.1.2.63\n\nNetwork Id for S2: 200.1.2.64\nBroadcast address of S2: 200.1.2.127\n\nNetwork Id for S3: 200.1.2.128\nBroadcast address of S3: 200.1.2.191\n\nNetwork Id for S4: 200.1.2.192\nDirect Broadcast address of S4: 200.1.2.255"
},
{
"code": null,
"e": 29924,
"s": 29831,
"text": "Hence, we can say that Network size will also decrease. We can’t use our Network completely."
},
{
"code": null,
"e": 30058,
"s": 29924,
"text": "Cost of the overall Network also increases. Subnetting requires internal routers, Switches, Hubs, Bridges etc. which are very costly."
},
{
"code": null,
"e": 30177,
"s": 30058,
"text": "Subnetting and network management require an experienced network administrator. This adds to the overall cost as well."
},
{
"code": null,
"e": 30187,
"s": 30177,
"text": "Stranger1"
},
{
"code": null,
"e": 30205,
"s": 30187,
"text": "Computer Networks"
},
{
"code": null,
"e": 30213,
"s": 30205,
"text": "GATE CS"
},
{
"code": null,
"e": 30231,
"s": 30213,
"text": "Computer Networks"
},
{
"code": null,
"e": 30329,
"s": 30231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30359,
"s": 30329,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 30397,
"s": 30359,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 30436,
"s": 30397,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 30462,
"s": 30436,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 30491,
"s": 30462,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 30515,
"s": 30491,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 30542,
"s": 30515,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 30563,
"s": 30542,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 30612,
"s": 30563,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
SYSDATETIME() Function in SQL Server - GeeksforGeeks | 21 Jan, 2021
SYSDATETIME() :
This function in SQL Server is used to return the computer’s date and time in which the SQL Server is operating at present.
Features :
This function is used to find the computer’s date and time in which the SQL Server is operating.
This function comes under Date Functions.
This function doesn’t accept any parameter.
This function returns the output in ‘YYYY-MM-DD hh:mm:ss.mmm’ format.
Syntax :
SYSDATETIME()
Parameter :
This method doesn’t accept any parameter.
Returns :
It returns the computer’s date and time in which the SQL Server is operating in a ‘YYYY-MM-DD hh:mm:ss.mmm’ format.
Example-1 :
Using SYSDATETIME() function and getting the output.
SELECT SYSDATETIME();
Output :
2021-01-03 17:49:28.0575187
Here, the output will vary each time the code is compiled as this method returns the current date and time.
Example-2 :
Using SYSDATETIME() as a default value in the below example and getting the output.
CREATE TABLE system_date_time
(
id_num INT IDENTITY,
message VARCHAR(150) NOT NULL,
generated_at DATETIME NOT NULL
DEFAULT SYSDATETIME(),
PRIMARY KEY(id_num)
);
INSERT INTO system_date_time(message)
VALUES('Its the first message.');
INSERT INTO system_date_time(message)
VALUES('system_date_time');
SELECT
id_num,
message,
generated_at
FROM
system_date_time;
Output :
|id_num | message | generated_at
-------------------------------------------------------------
1 | 1 | Its the first message.| 03.01.2021 18:53:56
-------------------------------------------------------------
2 | 2 | system_date_time | 03.01.2021 18:53:56
Here, firstly you need to create a table then insert values into it then generate the required output using the SYSDATETIME() function as a default value.
Note: For running the above code use SQL server compiler, you can also use an online compiler.
Example-3 :
Using CONVERT() function in order to translate the output of the SYSDATETIME() function into the current date only.
SELECT CONVERT(DATE, SYSDATETIME());
Output :
2021-01-07
Here, the output may vary every time you run the code as it returns the current date.
Example-4 :
Using CONVERT() function in order to translate the output of the SYSDATETIME() function into the current time only.
SELECT CONVERT(TIME, SYSDATETIME());
Output :
06:20:12.2400986
Here, the output may vary every time you run the code as it returns the current time.
Application :
This function is used to return the current date and time of the computer in which the SQL server is operating.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n21 Jan, 2021"
},
{
"code": null,
"e": 25529,
"s": 25513,
"text": "SYSDATETIME() :"
},
{
"code": null,
"e": 25653,
"s": 25529,
"text": "This function in SQL Server is used to return the computer’s date and time in which the SQL Server is operating at present."
},
{
"code": null,
"e": 25664,
"s": 25653,
"text": "Features :"
},
{
"code": null,
"e": 25761,
"s": 25664,
"text": "This function is used to find the computer’s date and time in which the SQL Server is operating."
},
{
"code": null,
"e": 25803,
"s": 25761,
"text": "This function comes under Date Functions."
},
{
"code": null,
"e": 25847,
"s": 25803,
"text": "This function doesn’t accept any parameter."
},
{
"code": null,
"e": 25917,
"s": 25847,
"text": "This function returns the output in ‘YYYY-MM-DD hh:mm:ss.mmm’ format."
},
{
"code": null,
"e": 25926,
"s": 25917,
"text": "Syntax :"
},
{
"code": null,
"e": 25940,
"s": 25926,
"text": "SYSDATETIME()"
},
{
"code": null,
"e": 25952,
"s": 25940,
"text": "Parameter :"
},
{
"code": null,
"e": 25994,
"s": 25952,
"text": "This method doesn’t accept any parameter."
},
{
"code": null,
"e": 26004,
"s": 25994,
"text": "Returns :"
},
{
"code": null,
"e": 26120,
"s": 26004,
"text": "It returns the computer’s date and time in which the SQL Server is operating in a ‘YYYY-MM-DD hh:mm:ss.mmm’ format."
},
{
"code": null,
"e": 26132,
"s": 26120,
"text": "Example-1 :"
},
{
"code": null,
"e": 26185,
"s": 26132,
"text": "Using SYSDATETIME() function and getting the output."
},
{
"code": null,
"e": 26207,
"s": 26185,
"text": "SELECT SYSDATETIME();"
},
{
"code": null,
"e": 26216,
"s": 26207,
"text": "Output :"
},
{
"code": null,
"e": 26244,
"s": 26216,
"text": "2021-01-03 17:49:28.0575187"
},
{
"code": null,
"e": 26352,
"s": 26244,
"text": "Here, the output will vary each time the code is compiled as this method returns the current date and time."
},
{
"code": null,
"e": 26364,
"s": 26352,
"text": "Example-2 :"
},
{
"code": null,
"e": 26448,
"s": 26364,
"text": "Using SYSDATETIME() as a default value in the below example and getting the output."
},
{
"code": null,
"e": 26858,
"s": 26448,
"text": "CREATE TABLE system_date_time\n(\n id_num INT IDENTITY,\n message VARCHAR(150) NOT NULL,\n generated_at DATETIME NOT NULL\n DEFAULT SYSDATETIME(),\n PRIMARY KEY(id_num)\n);\nINSERT INTO system_date_time(message)\nVALUES('Its the first message.');\n\nINSERT INTO system_date_time(message)\nVALUES('system_date_time');\n\nSELECT\n id_num,\n message,\n generated_at\nFROM\n system_date_time;"
},
{
"code": null,
"e": 26867,
"s": 26858,
"text": "Output :"
},
{
"code": null,
"e": 27157,
"s": 26867,
"text": " |id_num | message | generated_at \n------------------------------------------------------------- \n1 | 1 | Its the first message.| 03.01.2021 18:53:56\n-------------------------------------------------------------\n2 | 2 | system_date_time | 03.01.2021 18:53:56"
},
{
"code": null,
"e": 27312,
"s": 27157,
"text": "Here, firstly you need to create a table then insert values into it then generate the required output using the SYSDATETIME() function as a default value."
},
{
"code": null,
"e": 27407,
"s": 27312,
"text": "Note: For running the above code use SQL server compiler, you can also use an online compiler."
},
{
"code": null,
"e": 27419,
"s": 27407,
"text": "Example-3 :"
},
{
"code": null,
"e": 27535,
"s": 27419,
"text": "Using CONVERT() function in order to translate the output of the SYSDATETIME() function into the current date only."
},
{
"code": null,
"e": 27572,
"s": 27535,
"text": "SELECT CONVERT(DATE, SYSDATETIME());"
},
{
"code": null,
"e": 27581,
"s": 27572,
"text": "Output :"
},
{
"code": null,
"e": 27592,
"s": 27581,
"text": "2021-01-07"
},
{
"code": null,
"e": 27678,
"s": 27592,
"text": "Here, the output may vary every time you run the code as it returns the current date."
},
{
"code": null,
"e": 27690,
"s": 27678,
"text": "Example-4 :"
},
{
"code": null,
"e": 27806,
"s": 27690,
"text": "Using CONVERT() function in order to translate the output of the SYSDATETIME() function into the current time only."
},
{
"code": null,
"e": 27843,
"s": 27806,
"text": "SELECT CONVERT(TIME, SYSDATETIME());"
},
{
"code": null,
"e": 27852,
"s": 27843,
"text": "Output :"
},
{
"code": null,
"e": 27869,
"s": 27852,
"text": "06:20:12.2400986"
},
{
"code": null,
"e": 27955,
"s": 27869,
"text": "Here, the output may vary every time you run the code as it returns the current time."
},
{
"code": null,
"e": 27969,
"s": 27955,
"text": "Application :"
},
{
"code": null,
"e": 28081,
"s": 27969,
"text": "This function is used to return the current date and time of the computer in which the SQL server is operating."
},
{
"code": null,
"e": 28090,
"s": 28081,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 28101,
"s": 28090,
"text": "SQL-Server"
},
{
"code": null,
"e": 28105,
"s": 28101,
"text": "SQL"
},
{
"code": null,
"e": 28109,
"s": 28105,
"text": "SQL"
},
{
"code": null,
"e": 28207,
"s": 28109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28273,
"s": 28207,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28330,
"s": 28273,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28362,
"s": 28330,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28377,
"s": 28362,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28413,
"s": 28377,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28491,
"s": 28413,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28508,
"s": 28491,
"text": "SQL using Python"
},
{
"code": null,
"e": 28574,
"s": 28508,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28636,
"s": 28574,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Lex program to check whether the input is digit or not - GeeksforGeeks | 30 Apr, 2019
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Prerequisite: Flex (Fast lexical Analyzer Generator).
Given an input, the task is to check if the input is digit or not.
Examples:
Input: 28
Output: digit
Input: a
Output: not a digit.
Input: 21ab
Output: not a digit.
Below is the implementation:
/* Lex program to check whether input is digit or not. */%{#include<stdio.h>#include<stdlib.h>%}/* Rule Section */%%^[0-9]* printf("digit");^[^0-9]|[0-9]*[a-zA-Z] printf("not a digit");. ;%%int main(){ // The function that starts the analysis yylex(); return 0;}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Symbol Table in Compiler
Code Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Intermediate Code Generation in Compiler Design
Introduction of Compiler Design
Types of Parsers in Compiler Design
Ambiguous Grammar
Difference between Compiler and Interpreter
Peephole Optimization in Compiler Design
S - attributed and L - attributed SDTs in Syntax directed translation | [
{
"code": null,
"e": 25915,
"s": 25887,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 26111,
"s": 25915,
"text": "Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language."
},
{
"code": null,
"e": 26165,
"s": 26111,
"text": "Prerequisite: Flex (Fast lexical Analyzer Generator)."
},
{
"code": null,
"e": 26232,
"s": 26165,
"text": "Given an input, the task is to check if the input is digit or not."
},
{
"code": null,
"e": 26242,
"s": 26232,
"text": "Examples:"
},
{
"code": null,
"e": 26335,
"s": 26242,
"text": "Input: 28\nOutput: digit\n\nInput: a\nOutput: not a digit. \n\nInput: 21ab\nOutput: not a digit. \n"
},
{
"code": null,
"e": 26364,
"s": 26335,
"text": "Below is the implementation:"
},
{
"code": "/* Lex program to check whether input is digit or not. */%{#include<stdio.h>#include<stdlib.h>%}/* Rule Section */%%^[0-9]* printf(\"digit\");^[^0-9]|[0-9]*[a-zA-Z] printf(\"not a digit\");. ;%%int main(){ // The function that starts the analysis yylex(); return 0;}",
"e": 26646,
"s": 26364,
"text": null
},
{
"code": null,
"e": 26654,
"s": 26646,
"text": "Output:"
},
{
"code": null,
"e": 26666,
"s": 26654,
"text": "Lex program"
},
{
"code": null,
"e": 26682,
"s": 26666,
"text": "Compiler Design"
},
{
"code": null,
"e": 26780,
"s": 26682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26805,
"s": 26780,
"text": "Symbol Table in Compiler"
},
{
"code": null,
"e": 26842,
"s": 26805,
"text": "Code Optimization in Compiler Design"
},
{
"code": null,
"e": 26900,
"s": 26842,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 26948,
"s": 26900,
"text": "Intermediate Code Generation in Compiler Design"
},
{
"code": null,
"e": 26980,
"s": 26948,
"text": "Introduction of Compiler Design"
},
{
"code": null,
"e": 27016,
"s": 26980,
"text": "Types of Parsers in Compiler Design"
},
{
"code": null,
"e": 27034,
"s": 27016,
"text": "Ambiguous Grammar"
},
{
"code": null,
"e": 27078,
"s": 27034,
"text": "Difference between Compiler and Interpreter"
},
{
"code": null,
"e": 27119,
"s": 27078,
"text": "Peephole Optimization in Compiler Design"
}
] |
Quantile Regression. When performing regression analysis, It... | by Steven Dye | Towards Data Science | When performing regression analysis, It isn’t enough to come up with a numerical prediction to a problem, you also need to express how confident you are in that prediction. For example, if you’re looking at the price for a home in a particular market and your model predicts a house will sell for $262,458.45, how confident can you be that your model’s prediction is exactly right? Hopefully your gut says that there is an infinitesimally small chance that this is true, but maybe there’s a chance that your model is close to the actual answer. We need a way to predict a range of values while having a certain amount of confidence in that range.
Enter quantile regression. Unlike regular linear regression which uses the method of least squares to calculate the conditional mean of the target across different values of the features, quantile regression estimates the conditional median of the target. Quantile regression is an extension of linear regression that is used when the conditions of linear regression are not met (i.e., linearity, homoscedasticity, independence, or normality).
Traditionally, the linear regression model for calculating the mean takes the form
where p is equal to the number of features in the equation and n is the number of data points. The best linear regression line is found by minimizing the mean square error, which is found with the equation
Now for quantile regression, you’re not limited to just finding the median, but you can calculate any quantile (percentage) for a particular value in the features variables. For example, if we were to find the 25th quantile for the price of a particular home, that would mean that there is a 25% chance the actual price of the house is below the prediction, while there is a 75% chance that the price is above.
Taking a similar structure to the linear regression model, the quantile regression model equation for the τth quantile is
This means that instead of being constants, the beta coefficients are now functions with a dependency on the quantile. Finding the values for these betas at a particular quantile value involves almost the same process as it does for regular linear quantization, except now we have to reduce the median absolute deviation.
Here the function ρ is the check function which gives asymmetric weights to the error depending on the quantile and the overall sign of the error. Mathematically, ρ takes the form
In this case, u is the error of a single data point and the max function returns the largest value in the parentheses. This means that if the error is positive, then the check function multiples the error by τ, and if the error is negative, then the check function multiplies the error by (1- τ).
For example, if you want the median of the 10th percentile, that means you want 90% of the errors to be positive and 10% to be negative. In order to find the smallest MAD while having this statement be true, weights have to added to the errors. In the case of the the 10th quantile, a weight of 0.9 is added the negative weights while a weight of 0.1 is added to the positive ones.
Let’s look at quantile regression in action. Let’s examine the python statsmodels example for QuantReg, which takes a look at the relationship between income and expenditures on food for a sample of working class Belgian households in 1857, and see what kind of statistical analysis we can do.
import statsmodels.api as smimport statsmodels.formula.api as smfdata = sm.datasets.engel.load_pandas().datadata.head()
mod = smf.quantreg('foodexp ~ income', data)res = mod.fit(q=.5)print(res.summary())
As you can see, you can create a regression line for a particular quantile and perform a statistical analysis on it the same way that you can with a regular linear regression model.
Here is a link to a paper written by SAS about Quantile Regression if you want to learn more. Other sources are provided below. | [
{
"code": null,
"e": 819,
"s": 172,
"text": "When performing regression analysis, It isn’t enough to come up with a numerical prediction to a problem, you also need to express how confident you are in that prediction. For example, if you’re looking at the price for a home in a particular market and your model predicts a house will sell for $262,458.45, how confident can you be that your model’s prediction is exactly right? Hopefully your gut says that there is an infinitesimally small chance that this is true, but maybe there’s a chance that your model is close to the actual answer. We need a way to predict a range of values while having a certain amount of confidence in that range."
},
{
"code": null,
"e": 1263,
"s": 819,
"text": "Enter quantile regression. Unlike regular linear regression which uses the method of least squares to calculate the conditional mean of the target across different values of the features, quantile regression estimates the conditional median of the target. Quantile regression is an extension of linear regression that is used when the conditions of linear regression are not met (i.e., linearity, homoscedasticity, independence, or normality)."
},
{
"code": null,
"e": 1346,
"s": 1263,
"text": "Traditionally, the linear regression model for calculating the mean takes the form"
},
{
"code": null,
"e": 1552,
"s": 1346,
"text": "where p is equal to the number of features in the equation and n is the number of data points. The best linear regression line is found by minimizing the mean square error, which is found with the equation"
},
{
"code": null,
"e": 1963,
"s": 1552,
"text": "Now for quantile regression, you’re not limited to just finding the median, but you can calculate any quantile (percentage) for a particular value in the features variables. For example, if we were to find the 25th quantile for the price of a particular home, that would mean that there is a 25% chance the actual price of the house is below the prediction, while there is a 75% chance that the price is above."
},
{
"code": null,
"e": 2085,
"s": 1963,
"text": "Taking a similar structure to the linear regression model, the quantile regression model equation for the τth quantile is"
},
{
"code": null,
"e": 2407,
"s": 2085,
"text": "This means that instead of being constants, the beta coefficients are now functions with a dependency on the quantile. Finding the values for these betas at a particular quantile value involves almost the same process as it does for regular linear quantization, except now we have to reduce the median absolute deviation."
},
{
"code": null,
"e": 2587,
"s": 2407,
"text": "Here the function ρ is the check function which gives asymmetric weights to the error depending on the quantile and the overall sign of the error. Mathematically, ρ takes the form"
},
{
"code": null,
"e": 2884,
"s": 2587,
"text": "In this case, u is the error of a single data point and the max function returns the largest value in the parentheses. This means that if the error is positive, then the check function multiples the error by τ, and if the error is negative, then the check function multiplies the error by (1- τ)."
},
{
"code": null,
"e": 3266,
"s": 2884,
"text": "For example, if you want the median of the 10th percentile, that means you want 90% of the errors to be positive and 10% to be negative. In order to find the smallest MAD while having this statement be true, weights have to added to the errors. In the case of the the 10th quantile, a weight of 0.9 is added the negative weights while a weight of 0.1 is added to the positive ones."
},
{
"code": null,
"e": 3560,
"s": 3266,
"text": "Let’s look at quantile regression in action. Let’s examine the python statsmodels example for QuantReg, which takes a look at the relationship between income and expenditures on food for a sample of working class Belgian households in 1857, and see what kind of statistical analysis we can do."
},
{
"code": null,
"e": 3680,
"s": 3560,
"text": "import statsmodels.api as smimport statsmodels.formula.api as smfdata = sm.datasets.engel.load_pandas().datadata.head()"
},
{
"code": null,
"e": 3764,
"s": 3680,
"text": "mod = smf.quantreg('foodexp ~ income', data)res = mod.fit(q=.5)print(res.summary())"
},
{
"code": null,
"e": 3946,
"s": 3764,
"text": "As you can see, you can create a regression line for a particular quantile and perform a statistical analysis on it the same way that you can with a regular linear regression model."
}
] |
HTML <input> disabled Attribute - GeeksforGeeks | 04 Jan, 2019
The disabled attribute for <input> element in HTML is used to specify that the input field is disabled. A disabled input is un-clickable and unusable. It is a boolean attribute. The disabled <input> elements are not submitted in the form.
Syntax:
<input disabled>
Example:
<!DOCTYPE html> <html> <head> <title>HTML input disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML input disabled Attribute</h2> <label>Input: <!--A disabled input--> <input type="text" name="value" value = "This input field is disabled" disabled> </label> </body> </html>
Output:
Supported Browsers: The browser supported by <input> disabled attribute are listed below:
Apple Safari 1.0
Google Chrome 1.0
Firefox 1.0
Opera 1.0
Internet Explorer 6.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 ?
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": 23805,
"s": 23777,
"text": "\n04 Jan, 2019"
},
{
"code": null,
"e": 24044,
"s": 23805,
"text": "The disabled attribute for <input> element in HTML is used to specify that the input field is disabled. A disabled input is un-clickable and unusable. It is a boolean attribute. The disabled <input> elements are not submitted in the form."
},
{
"code": null,
"e": 24052,
"s": 24044,
"text": "Syntax:"
},
{
"code": null,
"e": 24070,
"s": 24052,
"text": "<input disabled>\n"
},
{
"code": null,
"e": 24079,
"s": 24070,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML input disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML input disabled Attribute</h2> <label>Input: <!--A disabled input--> <input type=\"text\" name=\"value\" value = \"This input field is disabled\" disabled> </label> </body> </html> ",
"e": 24533,
"s": 24079,
"text": null
},
{
"code": null,
"e": 24541,
"s": 24533,
"text": "Output:"
},
{
"code": null,
"e": 24631,
"s": 24541,
"text": "Supported Browsers: The browser supported by <input> disabled attribute are listed below:"
},
{
"code": null,
"e": 24648,
"s": 24631,
"text": "Apple Safari 1.0"
},
{
"code": null,
"e": 24666,
"s": 24648,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 24678,
"s": 24666,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 24688,
"s": 24678,
"text": "Opera 1.0"
},
{
"code": null,
"e": 24710,
"s": 24688,
"text": "Internet Explorer 6.0"
},
{
"code": null,
"e": 24847,
"s": 24710,
"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": 24863,
"s": 24847,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 24868,
"s": 24863,
"text": "HTML"
},
{
"code": null,
"e": 24885,
"s": 24868,
"text": "Web Technologies"
},
{
"code": null,
"e": 24890,
"s": 24885,
"text": "HTML"
},
{
"code": null,
"e": 24988,
"s": 24890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25038,
"s": 24988,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25100,
"s": 25038,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25160,
"s": 25100,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 25208,
"s": 25160,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25269,
"s": 25208,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 25311,
"s": 25269,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 25344,
"s": 25311,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 25387,
"s": 25344,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25449,
"s": 25387,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
abstract keyword in C# | The abstract keyword in C# is used for abstract classes. An abstract class in C# includes abstract and nonabstract methods. You cannot instantiate an abstract class.
Example of an abstract class Vehicle and abstract method display() −
public abstract class Vehicle {
public abstract void display();
}
The abstract class has derived classes: Bus, Car, and Motorcycle. The following is an implementation of the Car derived class −
public class Car : Vehicle {
public override void display() {
Console.WriteLine("Car");
}
}
The following is an example of abstract classes in C# −
Live Demo
using System;
public abstract class Vehicle {
public abstract void display();
}
public class Bus : Vehicle {
public override void display() {
Console.WriteLine("Bus");
}
}
public class Car : Vehicle {
public override void display() {
Console.WriteLine("Car");
}
}
public class Motorcycle : Vehicle {
public override void display() {
Console.WriteLine("Motorcycle");
}
}
public class MyClass {
public static void Main() {
Vehicle v;
v = new Bus();
v.display();
v = new Car();
v.display();
v = new Motorcycle();
v.display();
}
}
Bus
Car
Motorcycle | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "The abstract keyword in C# is used for abstract classes. An abstract class in C# includes abstract and nonabstract methods. You cannot instantiate an abstract class."
},
{
"code": null,
"e": 1297,
"s": 1228,
"text": "Example of an abstract class Vehicle and abstract method display() −"
},
{
"code": null,
"e": 1366,
"s": 1297,
"text": "public abstract class Vehicle {\n public abstract void display();\n}"
},
{
"code": null,
"e": 1494,
"s": 1366,
"text": "The abstract class has derived classes: Bus, Car, and Motorcycle. The following is an implementation of the Car derived class −"
},
{
"code": null,
"e": 1598,
"s": 1494,
"text": "public class Car : Vehicle {\n public override void display() {\n Console.WriteLine(\"Car\");\n }\n}"
},
{
"code": null,
"e": 1654,
"s": 1598,
"text": "The following is an example of abstract classes in C# −"
},
{
"code": null,
"e": 1664,
"s": 1654,
"text": "Live Demo"
},
{
"code": null,
"e": 2278,
"s": 1664,
"text": "using System;\npublic abstract class Vehicle {\n public abstract void display();\n}\npublic class Bus : Vehicle {\n public override void display() {\n Console.WriteLine(\"Bus\");\n }\n}\npublic class Car : Vehicle {\n public override void display() {\n Console.WriteLine(\"Car\");\n }\n}\npublic class Motorcycle : Vehicle {\n public override void display() {\n Console.WriteLine(\"Motorcycle\");\n }\n}\npublic class MyClass {\n public static void Main() {\n Vehicle v;\n v = new Bus();\n v.display();\n v = new Car();\n v.display();\n v = new Motorcycle();\n v.display();\n }\n}"
},
{
"code": null,
"e": 2297,
"s": 2278,
"text": "Bus\nCar\nMotorcycle"
}
] |
How to Build your own website using Django in Python | Django is a Python web framework that is both free and open source.
It’s very fast.
It’s very fast.
Comes with a lot of pre-existing features like user authentication, site maps, RSS feeds.
Comes with a lot of pre-existing features like user authentication, site maps, RSS feeds.
It is very secure and prevents a lot of security mistakes like SQL Injection, cross−site scripting, clickjacking etc.
It is very secure and prevents a lot of security mistakes like SQL Injection, cross−site scripting, clickjacking etc.
It is very scalable and thus can be used even when the network traffic is exceedingly high.
It is very scalable and thus can be used even when the network traffic is exceedingly high.
Now that you know why we would be using Django to build our web application. Let us start setting up the ground work for it.
While building our web application, we will be using various packages that we wouldn’t require outside of our workspace for the website. In order to ensure we use a dedicated space for the website, we create a virtual environment for it.
To do this, we will be using the virtualenv package. Let us install it first,
Python −m pip install virtualenv
Now, create a folder for our website say Django-intro. Once the folder is created, it’s time to set up the virtual environment inside it. To do so, launch your terminal and `cd` your way to the project directory and use the command
virtualenv env
This should create a folder with the name env. In order to enter this virtual environment, you’ll have to use the command
source env/bin/activate
If you have the name of your environment with brackets around it, then you have successfully entered the virtual environment.
Firstly, make sure you have Python installed, version 3.6 or above.
Next up, install Django using Pip.
Python −m pip install Django
Verifying your Django installation.
python −m Django version
And, that’s it! You are now done with the initial phase of getting your website running. Let us now jump into creating our first application for the website!
Let us now obtain the skeleton required to get started. To do this, run the following command when inside the virtual environment.
django−admin startproject Django−intro−app
This should create a basic skeleton for the Django app.
If you enter the Django−intro−app folder, you can see that it has a manage.py file and another Directory with the same name Django−intro−app and settings.py, urls.py, and wsgi.py files.
Settings.py contains all the various settings for your project.
Settings.py contains all the various settings for your project.
Urls.py contains all the different routes for the website.
Urls.py contains all the different routes for the website.
Application we built is called Django−intro−app.
Application we built is called Django−intro−app.
Every subsequent app we build for the website will be within the main folder and have its own name.
Every subsequent app we build for the website will be within the main folder and have its own name.
Now that you understand the main framework of the entire Django workspace, let us create an application.
First, `cd` to the project directory −> Django−intro−app.
Python manage.py startapp first−app
This should now create a directory called first-app which contains admin.py, apps.py, models.py, tests.py and views.py files within the folder.
Next up we need to make sure the first-app application is recognised by Django. To do this, head over to Django−intro−app/settings.py and add first−app into the INSTALLED_APPS section.
This should now look like,
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'howdy'
]
And, that’s it! You have now created a Django application. In order to test out our web−application, let us run it using Django’s web server.
To do this, head to the project directory and use the command
Python manage.py runserver
If you have done everything like mentioned above, your website should be running at http://127.0.0.1:8000/. Open the link and checkout your very own Django webpage.
You have now learnt to set up a virtual environment to work your Python projects and Django applications.
You have created your very own Django application. Obviously, this is not the end. You can create your very own templates for the website using Html, CSS and JS. Modify URLS, link various pages and do a lot more with Django!
For more details and information about the Django series check out their very own documentation at https://www.djangoproject.com/. | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Django is a Python web framework that is both free and open source."
},
{
"code": null,
"e": 1146,
"s": 1130,
"text": "It’s very fast."
},
{
"code": null,
"e": 1162,
"s": 1146,
"text": "It’s very fast."
},
{
"code": null,
"e": 1252,
"s": 1162,
"text": "Comes with a lot of pre-existing features like user authentication, site maps, RSS feeds."
},
{
"code": null,
"e": 1342,
"s": 1252,
"text": "Comes with a lot of pre-existing features like user authentication, site maps, RSS feeds."
},
{
"code": null,
"e": 1460,
"s": 1342,
"text": "It is very secure and prevents a lot of security mistakes like SQL Injection, cross−site scripting, clickjacking etc."
},
{
"code": null,
"e": 1578,
"s": 1460,
"text": "It is very secure and prevents a lot of security mistakes like SQL Injection, cross−site scripting, clickjacking etc."
},
{
"code": null,
"e": 1670,
"s": 1578,
"text": "It is very scalable and thus can be used even when the network traffic is exceedingly high."
},
{
"code": null,
"e": 1762,
"s": 1670,
"text": "It is very scalable and thus can be used even when the network traffic is exceedingly high."
},
{
"code": null,
"e": 1887,
"s": 1762,
"text": "Now that you know why we would be using Django to build our web application. Let us start setting up the ground work for it."
},
{
"code": null,
"e": 2125,
"s": 1887,
"text": "While building our web application, we will be using various packages that we wouldn’t require outside of our workspace for the website. In order to ensure we use a dedicated space for the website, we create a virtual environment for it."
},
{
"code": null,
"e": 2203,
"s": 2125,
"text": "To do this, we will be using the virtualenv package. Let us install it first,"
},
{
"code": null,
"e": 2236,
"s": 2203,
"text": "Python −m pip install virtualenv"
},
{
"code": null,
"e": 2468,
"s": 2236,
"text": "Now, create a folder for our website say Django-intro. Once the folder is created, it’s time to set up the virtual environment inside it. To do so, launch your terminal and `cd` your way to the project directory and use the command"
},
{
"code": null,
"e": 2483,
"s": 2468,
"text": "virtualenv env"
},
{
"code": null,
"e": 2605,
"s": 2483,
"text": "This should create a folder with the name env. In order to enter this virtual environment, you’ll have to use the command"
},
{
"code": null,
"e": 2629,
"s": 2605,
"text": "source env/bin/activate"
},
{
"code": null,
"e": 2755,
"s": 2629,
"text": "If you have the name of your environment with brackets around it, then you have successfully entered the virtual environment."
},
{
"code": null,
"e": 2823,
"s": 2755,
"text": "Firstly, make sure you have Python installed, version 3.6 or above."
},
{
"code": null,
"e": 2858,
"s": 2823,
"text": "Next up, install Django using Pip."
},
{
"code": null,
"e": 2887,
"s": 2858,
"text": "Python −m pip install Django"
},
{
"code": null,
"e": 2923,
"s": 2887,
"text": "Verifying your Django installation."
},
{
"code": null,
"e": 2948,
"s": 2923,
"text": "python −m Django version"
},
{
"code": null,
"e": 3106,
"s": 2948,
"text": "And, that’s it! You are now done with the initial phase of getting your website running. Let us now jump into creating our first application for the website!"
},
{
"code": null,
"e": 3237,
"s": 3106,
"text": "Let us now obtain the skeleton required to get started. To do this, run the following command when inside the virtual environment."
},
{
"code": null,
"e": 3280,
"s": 3237,
"text": "django−admin startproject Django−intro−app"
},
{
"code": null,
"e": 3336,
"s": 3280,
"text": "This should create a basic skeleton for the Django app."
},
{
"code": null,
"e": 3522,
"s": 3336,
"text": "If you enter the Django−intro−app folder, you can see that it has a manage.py file and another Directory with the same name Django−intro−app and settings.py, urls.py, and wsgi.py files."
},
{
"code": null,
"e": 3586,
"s": 3522,
"text": "Settings.py contains all the various settings for your project."
},
{
"code": null,
"e": 3650,
"s": 3586,
"text": "Settings.py contains all the various settings for your project."
},
{
"code": null,
"e": 3709,
"s": 3650,
"text": "Urls.py contains all the different routes for the website."
},
{
"code": null,
"e": 3768,
"s": 3709,
"text": "Urls.py contains all the different routes for the website."
},
{
"code": null,
"e": 3817,
"s": 3768,
"text": "Application we built is called Django−intro−app."
},
{
"code": null,
"e": 3866,
"s": 3817,
"text": "Application we built is called Django−intro−app."
},
{
"code": null,
"e": 3966,
"s": 3866,
"text": "Every subsequent app we build for the website will be within the main folder and have its own name."
},
{
"code": null,
"e": 4066,
"s": 3966,
"text": "Every subsequent app we build for the website will be within the main folder and have its own name."
},
{
"code": null,
"e": 4171,
"s": 4066,
"text": "Now that you understand the main framework of the entire Django workspace, let us create an application."
},
{
"code": null,
"e": 4229,
"s": 4171,
"text": "First, `cd` to the project directory −> Django−intro−app."
},
{
"code": null,
"e": 4265,
"s": 4229,
"text": "Python manage.py startapp first−app"
},
{
"code": null,
"e": 4409,
"s": 4265,
"text": "This should now create a directory called first-app which contains admin.py, apps.py, models.py, tests.py and views.py files within the folder."
},
{
"code": null,
"e": 4594,
"s": 4409,
"text": "Next up we need to make sure the first-app application is recognised by Django. To do this, head over to Django−intro−app/settings.py and add first−app into the INSTALLED_APPS section."
},
{
"code": null,
"e": 4621,
"s": 4594,
"text": "This should now look like,"
},
{
"code": null,
"e": 4833,
"s": 4621,
"text": "INSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'howdy'\n]"
},
{
"code": null,
"e": 4975,
"s": 4833,
"text": "And, that’s it! You have now created a Django application. In order to test out our web−application, let us run it using Django’s web server."
},
{
"code": null,
"e": 5037,
"s": 4975,
"text": "To do this, head to the project directory and use the command"
},
{
"code": null,
"e": 5064,
"s": 5037,
"text": "Python manage.py runserver"
},
{
"code": null,
"e": 5229,
"s": 5064,
"text": "If you have done everything like mentioned above, your website should be running at http://127.0.0.1:8000/. Open the link and checkout your very own Django webpage."
},
{
"code": null,
"e": 5335,
"s": 5229,
"text": "You have now learnt to set up a virtual environment to work your Python projects and Django applications."
},
{
"code": null,
"e": 5560,
"s": 5335,
"text": "You have created your very own Django application. Obviously, this is not the end. You can create your very own templates for the website using Html, CSS and JS. Modify URLS, link various pages and do a lot more with Django!"
},
{
"code": null,
"e": 5691,
"s": 5560,
"text": "For more details and information about the Django series check out their very own documentation at https://www.djangoproject.com/."
}
] |
Convert IP address to integer and vice versa - GeeksforGeeks | 01 Nov, 2020
We will use the ipaddress module for this purpose. ipaddress is a module that helps in the creation, manipulation and operation on IPv4 and IPv6 addresses and networks.
The motivation of converting IP Addresses to integers and vice versa is that other modules that use IP addresses (such as socket) usually won’t accept objects from ipaddress module directly. Instead, they must be converted to string or an integer that the other module will accept.
Syntax: ipaddress.ip_address(address)
Parameter: Passing IP address in form of integer or string. Integers value less than 2**32 are considered as IPv4 addresses.
Returns: IPv4Address or IPv6Address object is returned depending on the IP address passed as argument. If address passed does not represent a valid IPv4 or IPv6 address, a ValueError is raised.
Program to convert integers to IP Address :
Python3
# importing the moduleimport ipaddress # converting int to IPv4 addressprint(ipaddress.ip_address(3221225000))print(ipaddress.ip_address(123)) # converting int to IPv6 addressprint(ipaddress.ip_address(42540766400282592856903984001653826561))
Output:
191.255.254.40
0.0.0.123
2001:db7:dc75:365:220a:7c84:d796:6401
For converting IP addresses to integers:
Python3
# importing the moduleimport ipaddress # converting IPv4 address to intaddr1 = ipaddress.ip_address('191.255.254.40')addr2 = ipaddress.ip_address('0.0.0.123')print(int(addr1))print(int(addr2)) # converting IPv6 address to intaddr3 = ipaddress.ip_address('2001:db7:dc75:365:220a:7c84:d796:6401')print(int(addr3))
Output:
3221225000
123
42540766400282592856903984001653826561
python-modules
python-utility
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Nov, 2020"
},
{
"code": null,
"e": 24461,
"s": 24292,
"text": "We will use the ipaddress module for this purpose. ipaddress is a module that helps in the creation, manipulation and operation on IPv4 and IPv6 addresses and networks."
},
{
"code": null,
"e": 24743,
"s": 24461,
"text": "The motivation of converting IP Addresses to integers and vice versa is that other modules that use IP addresses (such as socket) usually won’t accept objects from ipaddress module directly. Instead, they must be converted to string or an integer that the other module will accept."
},
{
"code": null,
"e": 24781,
"s": 24743,
"text": "Syntax: ipaddress.ip_address(address)"
},
{
"code": null,
"e": 24906,
"s": 24781,
"text": "Parameter: Passing IP address in form of integer or string. Integers value less than 2**32 are considered as IPv4 addresses."
},
{
"code": null,
"e": 25100,
"s": 24906,
"text": "Returns: IPv4Address or IPv6Address object is returned depending on the IP address passed as argument. If address passed does not represent a valid IPv4 or IPv6 address, a ValueError is raised."
},
{
"code": null,
"e": 25145,
"s": 25100,
"text": "Program to convert integers to IP Address : "
},
{
"code": null,
"e": 25153,
"s": 25145,
"text": "Python3"
},
{
"code": "# importing the moduleimport ipaddress # converting int to IPv4 addressprint(ipaddress.ip_address(3221225000))print(ipaddress.ip_address(123)) # converting int to IPv6 addressprint(ipaddress.ip_address(42540766400282592856903984001653826561))",
"e": 25398,
"s": 25153,
"text": null
},
{
"code": null,
"e": 25406,
"s": 25398,
"text": "Output:"
},
{
"code": null,
"e": 25469,
"s": 25406,
"text": "191.255.254.40\n0.0.0.123\n2001:db7:dc75:365:220a:7c84:d796:6401"
},
{
"code": null,
"e": 25511,
"s": 25469,
"text": "For converting IP addresses to integers: "
},
{
"code": null,
"e": 25519,
"s": 25511,
"text": "Python3"
},
{
"code": "# importing the moduleimport ipaddress # converting IPv4 address to intaddr1 = ipaddress.ip_address('191.255.254.40')addr2 = ipaddress.ip_address('0.0.0.123')print(int(addr1))print(int(addr2)) # converting IPv6 address to intaddr3 = ipaddress.ip_address('2001:db7:dc75:365:220a:7c84:d796:6401')print(int(addr3))",
"e": 25833,
"s": 25519,
"text": null
},
{
"code": null,
"e": 25841,
"s": 25833,
"text": "Output:"
},
{
"code": null,
"e": 25895,
"s": 25841,
"text": "3221225000\n123\n42540766400282592856903984001653826561"
},
{
"code": null,
"e": 25910,
"s": 25895,
"text": "python-modules"
},
{
"code": null,
"e": 25925,
"s": 25910,
"text": "python-utility"
},
{
"code": null,
"e": 25949,
"s": 25925,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 25956,
"s": 25949,
"text": "Python"
},
{
"code": null,
"e": 25975,
"s": 25956,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26073,
"s": 25975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26105,
"s": 26073,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26161,
"s": 26105,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26203,
"s": 26161,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26245,
"s": 26203,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26267,
"s": 26245,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26306,
"s": 26267,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26337,
"s": 26306,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26392,
"s": 26337,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26421,
"s": 26392,
"text": "Create a directory in Python"
}
] |
Object detection using Mask R-CNN on a custom dataset | by Renu Khandelwal | Towards Data Science | In this article we will implement Mask R-CNN for detecting objects from a custom dataset
Computer vision : A journey from CNN to Mask R-CC and YOLO Part 1
Computer vision : A journey from CNN to Mask R-CNN and YOLO Part 2
Instance segmentation using Mask R-CNN
Transfer Learning
Transfer Learning using ResNet50
Kangaroo data set is used in the article
Mask R-CNN is a deep neural network for instance segmentation. The model is divided into two parts
Region proposal network (RPN) to proposes candidate object bounding boxes.
Binary mask classifier to generate mask for every class
Mask R-CNN have a branch for classification and bounding box regression. It uses
ResNet101 architecture to extract features from image.
Region Proposal Network(RPN) to generate Region of Interests(RoI)
For this we use MatterPort Mask R-CNN.
Step 1: Clone the Mask R-CNN repository
git clone https://github.com/matterport/Mask_RCNN.gitcd Mask_RCNN$ python setup.py install
Step 2: Download the pre-trained weights for COCO model from MatterPort.
Place the file in the Mask_RCNN folder with name “mask_rcnn_coco.h5”
Step 3: Import the required libraries
from mrcnn.config import Configfrom mrcnn import model as modellibfrom mrcnn import visualizeimport mrcnnfrom mrcnn.utils import Datasetfrom mrcnn.model import MaskRCNNimport numpy as npfrom numpy import zerosfrom numpy import asarrayimport colorsysimport argparseimport imutilsimport randomimport cv2import osimport timefrom matplotlib import pyplotfrom matplotlib.patches import Rectanglefrom keras.models import load_model%matplotlib inlinefrom os import listdirfrom xml.etree import ElementTree
Step 4: We Create a myMaskRCNNConfig class for training on the Kangaroo dataset. It is derived from the base Mask R-CNN Config class and overrides some values.
class myMaskRCNNConfig(Config): # give the configuration a recognizable name NAME = "MaskRCNN_config" # set the number of GPUs to use along with the number of images # per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # number of classes (we would normally add +1 for the background) # kangaroo + BG NUM_CLASSES = 1+1 # Number of training steps per epoch STEPS_PER_EPOCH = 131 # Learning rate LEARNING_RATE=0.006 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.9 # setting Max ground truth instances MAX_GT_INSTANCES=10
Step 5: Create an instance of the myMaskRCNNConfig class
config = myMaskRCNNConfig()
Let’s display all the config values.
config.display()
Step 6: Build the custom kangaroo data set.
Dataset class provides a consistent way to work with any dataset. We will create our new datasets for kangaroo dataset to train without having to change the code of the model.
Dataset class also supports loading multiple data sets at the same time,. This is very helpful when the you want to detect different objects and they are all not available in one data set.
In load_dataset method, we iterate through all the files in the image and annotations folders to add the class, images and annotations to create the dataset using add_class and add_image methods.
extract_boxes method extracts each of the bounding box from the annotation file. Annotation files are xml files using pascal VOC format. It returns the box, it’s height and width
load_mask method generates the masks for every object in the image. It returns one mask per instance and class ids, a 1D array of class id for the instance masks
image_reference method returns the path of the image
class KangarooDataset(Dataset): # load the dataset definitions def load_dataset(self, dataset_dir, is_train=True): # Add classes. We have only one class to add. self.add_class("dataset", 1, "kangaroo") # define data locations for images and annotations images_dir = dataset_dir + '\\images\\' annotations_dir = dataset_dir + '\\annots\\' # Iterate through all files in the folder to #add class, images and annotaions for filename in listdir(images_dir): # extract image id image_id = filename[:-4] # skip bad images if image_id in ['00090']: continue # skip all images after 150 if we are building the train set if is_train and int(image_id) >= 150: continue # skip all images before 150 if we are building the test/val set if not is_train and int(image_id) < 150: continue # setting image file img_path = images_dir + filename # setting annotations file ann_path = annotations_dir + image_id + '.xml' # adding images and annotations to dataset self.add_image('dataset', image_id=image_id, path=img_path, annotation=ann_path)# extract bounding boxes from an annotation file def extract_boxes(self, filename): # load and parse the file tree = ElementTree.parse(filename) # get the root of the document root = tree.getroot() # extract each bounding box boxes = list() for box in root.findall('.//bndbox'): xmin = int(box.find('xmin').text) ymin = int(box.find('ymin').text) xmax = int(box.find('xmax').text) ymax = int(box.find('ymax').text) coors = [xmin, ymin, xmax, ymax] boxes.append(coors) # extract image dimensions width = int(root.find('.//size/width').text) height = int(root.find('.//size/height').text) return boxes, width, height# load the masks for an image """Generate instance masks for an image. Returns: masks: A bool array of shape [height, width, instance count] with one mask per instance. class_ids: a 1D array of class IDs of the instance masks. """ def load_mask(self, image_id): # get details of image info = self.image_info[image_id] # define anntation file location path = info['annotation'] # load XML boxes, w, h = self.extract_boxes(path) # create one array for all masks, each on a different channel masks = zeros([h, w, len(boxes)], dtype='uint8') # create masks class_ids = list() for i in range(len(boxes)): box = boxes[i] row_s, row_e = box[1], box[3] col_s, col_e = box[0], box[2] masks[row_s:row_e, col_s:col_e, i] = 1 class_ids.append(self.class_names.index('kangaroo')) return masks, asarray(class_ids, dtype='int32')# load an image reference """Return the path of the image.""" def image_reference(self, image_id): info = self.image_info[image_id] print(info) return info['path']
Step 7: Prepare the train and test set
# prepare train settrain_set = KangarooDataset()train_set.load_dataset(‘..\\Kangaroo\\kangaroo-master\\kangaroo-master’, is_train=True)train_set.prepare()print(‘Train: %d’ % len(train_set.image_ids))# prepare test/val settest_set = KangarooDataset()test_set.load_dataset(‘..\\Kangaroo\\kangaroo-master\\kangaroo-master’, is_train=False)test_set.prepare()print(‘Test: %d’ % len(test_set.image_ids))
Step 8 :Initialize Mask R-CNN model for “training” using the Config instance that we created
print("Loading Mask R-CNN model...")model = modellib.MaskRCNN(mode="training", config=config, model_dir='./')
Step 9: Load the pre-trained weights for the Mask R-CNN from COCO data set excluding the last few layers
We exclude the last few layers from training for ResNet101. Excluding the last layers is to match the number of classes in the new data set.
#load the weights for COCOmodel.load_weights('.\\Mask_RCNN\\mask_rcnn_coco.h5', by_name=True, exclude=["mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask"])
We can increase the speed of learning for head layers by increasing the learning rate
Also we can increase the epochs to anywhere from 100–500 and see the difference in the accuracy of the object detection. I have used only 5 epochs as I trained it on a CPU.
## train heads with higher lr to speedup the learningmodel.train(train_set, test_set, learning_rate=2*config.LEARNING_RATE, epochs=5, layers=’heads’)history = model.keras_model.history.history
Step 11: Save the trained weights for custom data set
import timemodel_path = '..\\Kangaroo\\kangaroo-master\\kangaroo-master\\mask_rcnn_' + '.' + str(time.time()) + '.h5'model.keras_model.save_weights(model_path)
Step 12: Detecting objects in the image with masks and bounding box from the trained model
Create the model in the inference mode. Load the weights for the model from the data set that we trained the model on.
Load the image that we want to detect the bounding boxes, classes and confidence percentage
from keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_array#Loading the model in the inference modemodel = modellib.MaskRCNN(mode="inference", config=config, model_dir='./')# loading the trained weights o the custom datasetmodel.load_weights(model_path, by_name=True)img = load_img("..\\Kangaroo\\kangaroo-master\\kangaroo-master\\images\\00042.jpg")img = img_to_array(img)# detecting objects in the imageresult= model.detect([img])
Finally displaying the results
image_id = 20image, image_meta, gt_class_id, gt_bbox, gt_mask = modellib.load_image_gt(test_set, config, image_id, use_mini_mask=False)info = test_set.image_info[image_id]print("image ID: {}.{} ({}) {}".format(info["source"], info["id"], image_id, test_set.image_reference(image_id)))# Run object detectionresults = model.detect([image], verbose=1)# Display resultsr = results[0]visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], test_set.class_names, r['scores'], title="Predictions") | [
{
"code": null,
"e": 261,
"s": 172,
"text": "In this article we will implement Mask R-CNN for detecting objects from a custom dataset"
},
{
"code": null,
"e": 327,
"s": 261,
"text": "Computer vision : A journey from CNN to Mask R-CC and YOLO Part 1"
},
{
"code": null,
"e": 394,
"s": 327,
"text": "Computer vision : A journey from CNN to Mask R-CNN and YOLO Part 2"
},
{
"code": null,
"e": 433,
"s": 394,
"text": "Instance segmentation using Mask R-CNN"
},
{
"code": null,
"e": 451,
"s": 433,
"text": "Transfer Learning"
},
{
"code": null,
"e": 484,
"s": 451,
"text": "Transfer Learning using ResNet50"
},
{
"code": null,
"e": 525,
"s": 484,
"text": "Kangaroo data set is used in the article"
},
{
"code": null,
"e": 624,
"s": 525,
"text": "Mask R-CNN is a deep neural network for instance segmentation. The model is divided into two parts"
},
{
"code": null,
"e": 699,
"s": 624,
"text": "Region proposal network (RPN) to proposes candidate object bounding boxes."
},
{
"code": null,
"e": 755,
"s": 699,
"text": "Binary mask classifier to generate mask for every class"
},
{
"code": null,
"e": 836,
"s": 755,
"text": "Mask R-CNN have a branch for classification and bounding box regression. It uses"
},
{
"code": null,
"e": 891,
"s": 836,
"text": "ResNet101 architecture to extract features from image."
},
{
"code": null,
"e": 957,
"s": 891,
"text": "Region Proposal Network(RPN) to generate Region of Interests(RoI)"
},
{
"code": null,
"e": 996,
"s": 957,
"text": "For this we use MatterPort Mask R-CNN."
},
{
"code": null,
"e": 1036,
"s": 996,
"text": "Step 1: Clone the Mask R-CNN repository"
},
{
"code": null,
"e": 1127,
"s": 1036,
"text": "git clone https://github.com/matterport/Mask_RCNN.gitcd Mask_RCNN$ python setup.py install"
},
{
"code": null,
"e": 1200,
"s": 1127,
"text": "Step 2: Download the pre-trained weights for COCO model from MatterPort."
},
{
"code": null,
"e": 1269,
"s": 1200,
"text": "Place the file in the Mask_RCNN folder with name “mask_rcnn_coco.h5”"
},
{
"code": null,
"e": 1307,
"s": 1269,
"text": "Step 3: Import the required libraries"
},
{
"code": null,
"e": 1806,
"s": 1307,
"text": "from mrcnn.config import Configfrom mrcnn import model as modellibfrom mrcnn import visualizeimport mrcnnfrom mrcnn.utils import Datasetfrom mrcnn.model import MaskRCNNimport numpy as npfrom numpy import zerosfrom numpy import asarrayimport colorsysimport argparseimport imutilsimport randomimport cv2import osimport timefrom matplotlib import pyplotfrom matplotlib.patches import Rectanglefrom keras.models import load_model%matplotlib inlinefrom os import listdirfrom xml.etree import ElementTree"
},
{
"code": null,
"e": 1966,
"s": 1806,
"text": "Step 4: We Create a myMaskRCNNConfig class for training on the Kangaroo dataset. It is derived from the base Mask R-CNN Config class and overrides some values."
},
{
"code": null,
"e": 2567,
"s": 1966,
"text": "class myMaskRCNNConfig(Config): # give the configuration a recognizable name NAME = \"MaskRCNN_config\" # set the number of GPUs to use along with the number of images # per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # number of classes (we would normally add +1 for the background) # kangaroo + BG NUM_CLASSES = 1+1 # Number of training steps per epoch STEPS_PER_EPOCH = 131 # Learning rate LEARNING_RATE=0.006 # Skip detections with < 90% confidence DETECTION_MIN_CONFIDENCE = 0.9 # setting Max ground truth instances MAX_GT_INSTANCES=10"
},
{
"code": null,
"e": 2624,
"s": 2567,
"text": "Step 5: Create an instance of the myMaskRCNNConfig class"
},
{
"code": null,
"e": 2652,
"s": 2624,
"text": "config = myMaskRCNNConfig()"
},
{
"code": null,
"e": 2689,
"s": 2652,
"text": "Let’s display all the config values."
},
{
"code": null,
"e": 2706,
"s": 2689,
"text": "config.display()"
},
{
"code": null,
"e": 2750,
"s": 2706,
"text": "Step 6: Build the custom kangaroo data set."
},
{
"code": null,
"e": 2926,
"s": 2750,
"text": "Dataset class provides a consistent way to work with any dataset. We will create our new datasets for kangaroo dataset to train without having to change the code of the model."
},
{
"code": null,
"e": 3115,
"s": 2926,
"text": "Dataset class also supports loading multiple data sets at the same time,. This is very helpful when the you want to detect different objects and they are all not available in one data set."
},
{
"code": null,
"e": 3311,
"s": 3115,
"text": "In load_dataset method, we iterate through all the files in the image and annotations folders to add the class, images and annotations to create the dataset using add_class and add_image methods."
},
{
"code": null,
"e": 3490,
"s": 3311,
"text": "extract_boxes method extracts each of the bounding box from the annotation file. Annotation files are xml files using pascal VOC format. It returns the box, it’s height and width"
},
{
"code": null,
"e": 3652,
"s": 3490,
"text": "load_mask method generates the masks for every object in the image. It returns one mask per instance and class ids, a 1D array of class id for the instance masks"
},
{
"code": null,
"e": 3705,
"s": 3652,
"text": "image_reference method returns the path of the image"
},
{
"code": null,
"e": 7070,
"s": 3705,
"text": "class KangarooDataset(Dataset): # load the dataset definitions def load_dataset(self, dataset_dir, is_train=True): # Add classes. We have only one class to add. self.add_class(\"dataset\", 1, \"kangaroo\") # define data locations for images and annotations images_dir = dataset_dir + '\\\\images\\\\' annotations_dir = dataset_dir + '\\\\annots\\\\' # Iterate through all files in the folder to #add class, images and annotaions for filename in listdir(images_dir): # extract image id image_id = filename[:-4] # skip bad images if image_id in ['00090']: continue # skip all images after 150 if we are building the train set if is_train and int(image_id) >= 150: continue # skip all images before 150 if we are building the test/val set if not is_train and int(image_id) < 150: continue # setting image file img_path = images_dir + filename # setting annotations file ann_path = annotations_dir + image_id + '.xml' # adding images and annotations to dataset self.add_image('dataset', image_id=image_id, path=img_path, annotation=ann_path)# extract bounding boxes from an annotation file def extract_boxes(self, filename): # load and parse the file tree = ElementTree.parse(filename) # get the root of the document root = tree.getroot() # extract each bounding box boxes = list() for box in root.findall('.//bndbox'): xmin = int(box.find('xmin').text) ymin = int(box.find('ymin').text) xmax = int(box.find('xmax').text) ymax = int(box.find('ymax').text) coors = [xmin, ymin, xmax, ymax] boxes.append(coors) # extract image dimensions width = int(root.find('.//size/width').text) height = int(root.find('.//size/height').text) return boxes, width, height# load the masks for an image \"\"\"Generate instance masks for an image. Returns: masks: A bool array of shape [height, width, instance count] with one mask per instance. class_ids: a 1D array of class IDs of the instance masks. \"\"\" def load_mask(self, image_id): # get details of image info = self.image_info[image_id] # define anntation file location path = info['annotation'] # load XML boxes, w, h = self.extract_boxes(path) # create one array for all masks, each on a different channel masks = zeros([h, w, len(boxes)], dtype='uint8') # create masks class_ids = list() for i in range(len(boxes)): box = boxes[i] row_s, row_e = box[1], box[3] col_s, col_e = box[0], box[2] masks[row_s:row_e, col_s:col_e, i] = 1 class_ids.append(self.class_names.index('kangaroo')) return masks, asarray(class_ids, dtype='int32')# load an image reference \"\"\"Return the path of the image.\"\"\" def image_reference(self, image_id): info = self.image_info[image_id] print(info) return info['path']"
},
{
"code": null,
"e": 7109,
"s": 7070,
"text": "Step 7: Prepare the train and test set"
},
{
"code": null,
"e": 7507,
"s": 7109,
"text": "# prepare train settrain_set = KangarooDataset()train_set.load_dataset(‘..\\\\Kangaroo\\\\kangaroo-master\\\\kangaroo-master’, is_train=True)train_set.prepare()print(‘Train: %d’ % len(train_set.image_ids))# prepare test/val settest_set = KangarooDataset()test_set.load_dataset(‘..\\\\Kangaroo\\\\kangaroo-master\\\\kangaroo-master’, is_train=False)test_set.prepare()print(‘Test: %d’ % len(test_set.image_ids))"
},
{
"code": null,
"e": 7600,
"s": 7507,
"text": "Step 8 :Initialize Mask R-CNN model for “training” using the Config instance that we created"
},
{
"code": null,
"e": 7710,
"s": 7600,
"text": "print(\"Loading Mask R-CNN model...\")model = modellib.MaskRCNN(mode=\"training\", config=config, model_dir='./')"
},
{
"code": null,
"e": 7815,
"s": 7710,
"text": "Step 9: Load the pre-trained weights for the Mask R-CNN from COCO data set excluding the last few layers"
},
{
"code": null,
"e": 7956,
"s": 7815,
"text": "We exclude the last few layers from training for ResNet101. Excluding the last layers is to match the number of classes in the new data set."
},
{
"code": null,
"e": 8166,
"s": 7956,
"text": "#load the weights for COCOmodel.load_weights('.\\\\Mask_RCNN\\\\mask_rcnn_coco.h5', by_name=True, exclude=[\"mrcnn_class_logits\", \"mrcnn_bbox_fc\", \"mrcnn_bbox\", \"mrcnn_mask\"])"
},
{
"code": null,
"e": 8252,
"s": 8166,
"text": "We can increase the speed of learning for head layers by increasing the learning rate"
},
{
"code": null,
"e": 8425,
"s": 8252,
"text": "Also we can increase the epochs to anywhere from 100–500 and see the difference in the accuracy of the object detection. I have used only 5 epochs as I trained it on a CPU."
},
{
"code": null,
"e": 8618,
"s": 8425,
"text": "## train heads with higher lr to speedup the learningmodel.train(train_set, test_set, learning_rate=2*config.LEARNING_RATE, epochs=5, layers=’heads’)history = model.keras_model.history.history"
},
{
"code": null,
"e": 8672,
"s": 8618,
"text": "Step 11: Save the trained weights for custom data set"
},
{
"code": null,
"e": 8833,
"s": 8672,
"text": "import timemodel_path = '..\\\\Kangaroo\\\\kangaroo-master\\\\kangaroo-master\\\\mask_rcnn_' + '.' + str(time.time()) + '.h5'model.keras_model.save_weights(model_path)"
},
{
"code": null,
"e": 8924,
"s": 8833,
"text": "Step 12: Detecting objects in the image with masks and bounding box from the trained model"
},
{
"code": null,
"e": 9043,
"s": 8924,
"text": "Create the model in the inference mode. Load the weights for the model from the data set that we trained the model on."
},
{
"code": null,
"e": 9135,
"s": 9043,
"text": "Load the image that we want to detect the bounding boxes, classes and confidence percentage"
},
{
"code": null,
"e": 9605,
"s": 9135,
"text": "from keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_array#Loading the model in the inference modemodel = modellib.MaskRCNN(mode=\"inference\", config=config, model_dir='./')# loading the trained weights o the custom datasetmodel.load_weights(model_path, by_name=True)img = load_img(\"..\\\\Kangaroo\\\\kangaroo-master\\\\kangaroo-master\\\\images\\\\00042.jpg\")img = img_to_array(img)# detecting objects in the imageresult= model.detect([img])"
},
{
"code": null,
"e": 9636,
"s": 9605,
"text": "Finally displaying the results"
}
] |
Predicting Horse Racing Results with Deep Learning | by Victor Sim | Towards Data Science | I am interested in the application of machine learning in different fields, where analysis of large amounts of data is necessary to come to accurate conclusions. One such field is sports analytics. Unlike other forms of gambling, the environment and the actors within it are sure to have an effect on the result, making it a problem that can be solved with machine learning.
I wanted to try to implementing deep learning in this field and so I looked online for datasets about sports. Eventually, I found a dataset on Hong Kong horse racing that contained 6000+ races. Unlike other games like basketball and football that are more complex, horse racing is just 14 horses racing against each otehr. This means that there are far fewer variables to take into account.
The model should be able to predict which horse will win, when given data about the race and the horse (sex,age,type).
With the theoretical concept in mind, this is the code that I used:
import osos.getcwd()
This script gets the current working directory that the programming is running this. I run this function so I can copy a template of the path, so as to easily describe the path to the dataset.
os.chdir('Desktop\\Files\\Data')
After that, I move to the directory where the file is stored.
import pandas as pddf = pd.read_csv('races.csv')
The dataset consists of two csv files, the races and runs csv. The races csv contains information about each race and the runs csv contains information about each of the horses that participate in each race. The goal is to encode all non-numerical data, and concatenate both of these csv files into one big dataframe. This will make it easier to get the model to train the model.
df = pd.read_csv('races.csv')df = df.drop('date',axis = 1)df = df.drop('going',axis = 1)df = df.drop('surface',axis = 1)df = df.drop('prize',axis = 1)df = df.drop('race_no',axis = 1)for column in df.columns: if 'sec' in column or 'time' in column or 'place' in column or 'win' in column: df = df.drop(column,axis = 1)df
This script removes all the unnecessary information from the dataset. Here is the dataset after removing all the unnecessary information:
df2 = pd.read_csv('runs.csv')
This script opens the second csv file, that contains all the information on the horses that participated in the race.
df2 = pd.read_csv('runs.csv')df2 = df2.drop('horse_id',axis = 1)df2 = df2.drop('result',axis = 1)df2 = df2.drop('horse_gear',axis = 1)df2 = df2.drop('win_odds',axis = 1)df2 = df2.drop('place_odds',axis = 1)df2 = df2.drop('trainer_id',axis = 1)df2 = df2.drop('jockey_id',axis = 1)df2['race_id'] = df2['race_id'] for column in df2.columns: if 'time' in column or 'behind' in column or 'position' in column: df2 = df2.drop(column,axis = 1) df2
This script removes all the unnecessary data from the csv file. Here is the dataset after that:
import warningswarnings.filterwarnings('ignore')import numpy as nptrue_df = []for i in range(len(df['race_id'])): matches = list(df2[df2['race_id']==i].drop(['race_id'],axis=1).drop(['horse_no'],axis=1).drop(['won'],axis=1).values) horse_no = len(matches) matches.insert(0,df[df['race_id']==i].values[0]) matches = flatten(matches) true_df.append(matches)
This script concatenates both CSV files together: For every race, it finds all the horses that participated in the race. This data is flattened an added to information about the race. The result of this is that you end up with a dataframe, with each row being a race. Each row has 104 values, containing information about the race and each of the horses in the race.
true_df = pd.DataFrame(true_df)true_df
After that, we can convert the list into a dataframe. Here is the full dataframe:
All the NaN values are there because some races have 14 horses, while others only have 12 horses. For those 12 horses races, the other values are filled with zeros.
winners = []for i in range(len(df['race_id'])): try: winner = df2[df2['race_id']==i][df2['won']==1]['horse_no'].values[0] except: print(df2[df2['race_id']==i][df2['won']==1]) winner = 1 winners.append(winner)
I then collect all the results from each race, and add this data to the end of every row.
true_df['winners'] = winnerstrue_df = pd.DataFrame(true_df).fillna(0)true_df.to_csv('Desktop\\Files\\Data\\insert_data.csv',index=False)
I then replace all instances of NaN and None with 0, so it does not have influence on the model’s training. The data frame is then saved as a csv file.
import osos.chdir('C:\\Users\\v_sim\\Desktop\\Files\\Data')import pandas as pddf = pd.read_csv('insert_data.csv')winners = df['winners'].valuesdf = df.drop('winners',axis=1).fillna(0)df = df.drop('0',axis = 1)
After saving the data frame as a csv file, this script opens the csv files, records the winners of each race, and then removes them from the dataframe. This is so that the rest of the data can be directly converted to the X-values.
def create_dict(array): array = array.astype(str) unique = np.unique(array) encode_dictionary = dict() decode_dictionary = dict() for i in range(len(unique)): encode_dictionary[unique[i]] = i decode_dictionary[i] = unique[i] return encode_dictionary,decode_dictionarydef encode_df(df): columns = df.columns dtypes = df.dtypes for i in range(len(columns)): if dtypes[i] == 'object': encode,decode = create_dict(df[columns[i]].values) df[columns[i]] = df[columns[i]].map(encode) return dfdf = encode_df(df)df = df.fillna(0)
This script contains two functions: One that encodes information within a list, and another that applies the function for columns in a dataframe, where the data is non-numerical.
X = df.values.reshape(len(X),103,1)y = np.array(y)
This function defines the X and y values, based on the operations applied on the initial dataset.
from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import Flatten,BatchNormalizationfrom keras.layers import Dropoutfrom keras.layers.convolutional import Conv1Dfrom keras.layers.convolutional import MaxPooling1Dfrom keras.optimizers import Adamimport kerasmodel = Sequential()model.add(Conv1D(filters=256, kernel_size=2, activation='relu', input_shape=(103,1)))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Conv1D(filters=512, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Conv1D(filters=1024, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Flatten())model.add(Dense(64,activation = 'relu'))model.add(Dense(128,activation = 'relu'))model.add(Dense(256,activation = 'relu'))model.add(BatchNormalization())model.add(Dense(14, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])
This is the model that I ended up going with. It is a typical convolutional network that is used for image classification. I adapted it for 1 dimensional arrays, and for multi-class classification.
from keras.models import Sequential, load_model, model_from_jsonfrom keras import callbacks, optimizerssymbol = 'horse_racing'h5 = symbol + '_best_model' + '.h5'checkpoint = callbacks.ModelCheckpoint(h5, monitor='loss', verbose=0, save_best_only=True, save_weights_only=True, mode='auto', period=1)callback = [checkpoint]json = symbol + '_best_model' + '.json'model_json = model.to_json()with open(json, "w") as json_file: json_file.write(model_json)model.fit(X,y,epochs = 5000,callbacks = callback,validation_split = 0.1)
This script trains the model, with the checkpoint callback, so that the weights of the best iteration of the model can be saved and reloaded. This prevents the waste of computational resources.
After training the model for a while, I the model had a 92% accuracy on training data, but the accuracy on validation data was relatively poor.
from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import Flatten,BatchNormalizationfrom keras.layers import Dropoutfrom keras.layers.convolutional import Conv1Dfrom keras.layers.convolutional import MaxPooling1Dfrom keras.optimizers import Adamimport kerasmodel = Sequential()model.add(Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(103,1)))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=128, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=256, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=512, kernel_size=2, activation='relu', input_shape=(103,1)))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=1024, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=2048, kernel_size=2, activation='relu'))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Flatten())model.add(Dense(64,activation = 'relu'))model.add(Dense(128,activation = 'relu'))model.add(Dense(256,activation = 'relu'))model.add(Dropout(0.3))model.add(BatchNormalization())model.add(Dense(14, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])
This model is the model that I used to combat this: The model is much deeper and also much wider. The model is deeper so that more complex patterns can be found and it is wider so that it works better with dropout.
This project is just a basic implementation of machine learning for sports analytics, just for the fun of it. I think that it was reasonably successful, but overfitting on the data is still a problem.
If you want to see more of my content, click this link. | [
{
"code": null,
"e": 547,
"s": 172,
"text": "I am interested in the application of machine learning in different fields, where analysis of large amounts of data is necessary to come to accurate conclusions. One such field is sports analytics. Unlike other forms of gambling, the environment and the actors within it are sure to have an effect on the result, making it a problem that can be solved with machine learning."
},
{
"code": null,
"e": 938,
"s": 547,
"text": "I wanted to try to implementing deep learning in this field and so I looked online for datasets about sports. Eventually, I found a dataset on Hong Kong horse racing that contained 6000+ races. Unlike other games like basketball and football that are more complex, horse racing is just 14 horses racing against each otehr. This means that there are far fewer variables to take into account."
},
{
"code": null,
"e": 1057,
"s": 938,
"text": "The model should be able to predict which horse will win, when given data about the race and the horse (sex,age,type)."
},
{
"code": null,
"e": 1125,
"s": 1057,
"text": "With the theoretical concept in mind, this is the code that I used:"
},
{
"code": null,
"e": 1146,
"s": 1125,
"text": "import osos.getcwd()"
},
{
"code": null,
"e": 1339,
"s": 1146,
"text": "This script gets the current working directory that the programming is running this. I run this function so I can copy a template of the path, so as to easily describe the path to the dataset."
},
{
"code": null,
"e": 1372,
"s": 1339,
"text": "os.chdir('Desktop\\\\Files\\\\Data')"
},
{
"code": null,
"e": 1434,
"s": 1372,
"text": "After that, I move to the directory where the file is stored."
},
{
"code": null,
"e": 1483,
"s": 1434,
"text": "import pandas as pddf = pd.read_csv('races.csv')"
},
{
"code": null,
"e": 1863,
"s": 1483,
"text": "The dataset consists of two csv files, the races and runs csv. The races csv contains information about each race and the runs csv contains information about each of the horses that participate in each race. The goal is to encode all non-numerical data, and concatenate both of these csv files into one big dataframe. This will make it easier to get the model to train the model."
},
{
"code": null,
"e": 2193,
"s": 1863,
"text": "df = pd.read_csv('races.csv')df = df.drop('date',axis = 1)df = df.drop('going',axis = 1)df = df.drop('surface',axis = 1)df = df.drop('prize',axis = 1)df = df.drop('race_no',axis = 1)for column in df.columns: if 'sec' in column or 'time' in column or 'place' in column or 'win' in column: df = df.drop(column,axis = 1)df"
},
{
"code": null,
"e": 2331,
"s": 2193,
"text": "This script removes all the unnecessary information from the dataset. Here is the dataset after removing all the unnecessary information:"
},
{
"code": null,
"e": 2361,
"s": 2331,
"text": "df2 = pd.read_csv('runs.csv')"
},
{
"code": null,
"e": 2479,
"s": 2361,
"text": "This script opens the second csv file, that contains all the information on the horses that participated in the race."
},
{
"code": null,
"e": 2937,
"s": 2479,
"text": "df2 = pd.read_csv('runs.csv')df2 = df2.drop('horse_id',axis = 1)df2 = df2.drop('result',axis = 1)df2 = df2.drop('horse_gear',axis = 1)df2 = df2.drop('win_odds',axis = 1)df2 = df2.drop('place_odds',axis = 1)df2 = df2.drop('trainer_id',axis = 1)df2 = df2.drop('jockey_id',axis = 1)df2['race_id'] = df2['race_id'] for column in df2.columns: if 'time' in column or 'behind' in column or 'position' in column: df2 = df2.drop(column,axis = 1) df2"
},
{
"code": null,
"e": 3033,
"s": 2937,
"text": "This script removes all the unnecessary data from the csv file. Here is the dataset after that:"
},
{
"code": null,
"e": 3404,
"s": 3033,
"text": "import warningswarnings.filterwarnings('ignore')import numpy as nptrue_df = []for i in range(len(df['race_id'])): matches = list(df2[df2['race_id']==i].drop(['race_id'],axis=1).drop(['horse_no'],axis=1).drop(['won'],axis=1).values) horse_no = len(matches) matches.insert(0,df[df['race_id']==i].values[0]) matches = flatten(matches) true_df.append(matches)"
},
{
"code": null,
"e": 3771,
"s": 3404,
"text": "This script concatenates both CSV files together: For every race, it finds all the horses that participated in the race. This data is flattened an added to information about the race. The result of this is that you end up with a dataframe, with each row being a race. Each row has 104 values, containing information about the race and each of the horses in the race."
},
{
"code": null,
"e": 3810,
"s": 3771,
"text": "true_df = pd.DataFrame(true_df)true_df"
},
{
"code": null,
"e": 3892,
"s": 3810,
"text": "After that, we can convert the list into a dataframe. Here is the full dataframe:"
},
{
"code": null,
"e": 4057,
"s": 3892,
"text": "All the NaN values are there because some races have 14 horses, while others only have 12 horses. For those 12 horses races, the other values are filled with zeros."
},
{
"code": null,
"e": 4296,
"s": 4057,
"text": "winners = []for i in range(len(df['race_id'])): try: winner = df2[df2['race_id']==i][df2['won']==1]['horse_no'].values[0] except: print(df2[df2['race_id']==i][df2['won']==1]) winner = 1 winners.append(winner)"
},
{
"code": null,
"e": 4386,
"s": 4296,
"text": "I then collect all the results from each race, and add this data to the end of every row."
},
{
"code": null,
"e": 4523,
"s": 4386,
"text": "true_df['winners'] = winnerstrue_df = pd.DataFrame(true_df).fillna(0)true_df.to_csv('Desktop\\\\Files\\\\Data\\\\insert_data.csv',index=False)"
},
{
"code": null,
"e": 4675,
"s": 4523,
"text": "I then replace all instances of NaN and None with 0, so it does not have influence on the model’s training. The data frame is then saved as a csv file."
},
{
"code": null,
"e": 4885,
"s": 4675,
"text": "import osos.chdir('C:\\\\Users\\\\v_sim\\\\Desktop\\\\Files\\\\Data')import pandas as pddf = pd.read_csv('insert_data.csv')winners = df['winners'].valuesdf = df.drop('winners',axis=1).fillna(0)df = df.drop('0',axis = 1)"
},
{
"code": null,
"e": 5117,
"s": 4885,
"text": "After saving the data frame as a csv file, this script opens the csv files, records the winners of each race, and then removes them from the dataframe. This is so that the rest of the data can be directly converted to the X-values."
},
{
"code": null,
"e": 5712,
"s": 5117,
"text": "def create_dict(array): array = array.astype(str) unique = np.unique(array) encode_dictionary = dict() decode_dictionary = dict() for i in range(len(unique)): encode_dictionary[unique[i]] = i decode_dictionary[i] = unique[i] return encode_dictionary,decode_dictionarydef encode_df(df): columns = df.columns dtypes = df.dtypes for i in range(len(columns)): if dtypes[i] == 'object': encode,decode = create_dict(df[columns[i]].values) df[columns[i]] = df[columns[i]].map(encode) return dfdf = encode_df(df)df = df.fillna(0)"
},
{
"code": null,
"e": 5891,
"s": 5712,
"text": "This script contains two functions: One that encodes information within a list, and another that applies the function for columns in a dataframe, where the data is non-numerical."
},
{
"code": null,
"e": 5942,
"s": 5891,
"text": "X = df.values.reshape(len(X),103,1)y = np.array(y)"
},
{
"code": null,
"e": 6040,
"s": 5942,
"text": "This function defines the X and y values, based on the operations applied on the initial dataset."
},
{
"code": null,
"e": 7067,
"s": 6040,
"text": "from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import Flatten,BatchNormalizationfrom keras.layers import Dropoutfrom keras.layers.convolutional import Conv1Dfrom keras.layers.convolutional import MaxPooling1Dfrom keras.optimizers import Adamimport kerasmodel = Sequential()model.add(Conv1D(filters=256, kernel_size=2, activation='relu', input_shape=(103,1)))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Conv1D(filters=512, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Conv1D(filters=1024, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Flatten())model.add(Dense(64,activation = 'relu'))model.add(Dense(128,activation = 'relu'))model.add(Dense(256,activation = 'relu'))model.add(BatchNormalization())model.add(Dense(14, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])"
},
{
"code": null,
"e": 7265,
"s": 7067,
"text": "This is the model that I ended up going with. It is a typical convolutional network that is used for image classification. I adapted it for 1 dimensional arrays, and for multi-class classification."
},
{
"code": null,
"e": 8019,
"s": 7265,
"text": "from keras.models import Sequential, load_model, model_from_jsonfrom keras import callbacks, optimizerssymbol = 'horse_racing'h5 = symbol + '_best_model' + '.h5'checkpoint = callbacks.ModelCheckpoint(h5, monitor='loss', verbose=0, save_best_only=True, save_weights_only=True, mode='auto', period=1)callback = [checkpoint]json = symbol + '_best_model' + '.json'model_json = model.to_json()with open(json, \"w\") as json_file: json_file.write(model_json)model.fit(X,y,epochs = 5000,callbacks = callback,validation_split = 0.1)"
},
{
"code": null,
"e": 8213,
"s": 8019,
"text": "This script trains the model, with the checkpoint callback, so that the weights of the best iteration of the model can be saved and reloaded. This prevents the waste of computational resources."
},
{
"code": null,
"e": 8357,
"s": 8213,
"text": "After training the model for a while, I the model had a 92% accuracy on training data, but the accuracy on validation data was relatively poor."
},
{
"code": null,
"e": 9923,
"s": 8357,
"text": "from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import Flatten,BatchNormalizationfrom keras.layers import Dropoutfrom keras.layers.convolutional import Conv1Dfrom keras.layers.convolutional import MaxPooling1Dfrom keras.optimizers import Adamimport kerasmodel = Sequential()model.add(Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(103,1)))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=128, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=256, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=512, kernel_size=2, activation='relu', input_shape=(103,1)))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=1024, kernel_size=2, activation='relu'))model.add(MaxPooling1D(pool_size=2))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Conv1D(filters=2048, kernel_size=2, activation='relu'))model.add(BatchNormalization())model.add(Dropout(0.3))model.add(Flatten())model.add(Dense(64,activation = 'relu'))model.add(Dense(128,activation = 'relu'))model.add(Dense(256,activation = 'relu'))model.add(Dropout(0.3))model.add(BatchNormalization())model.add(Dense(14, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])"
},
{
"code": null,
"e": 10138,
"s": 9923,
"text": "This model is the model that I used to combat this: The model is much deeper and also much wider. The model is deeper so that more complex patterns can be found and it is wider so that it works better with dropout."
},
{
"code": null,
"e": 10339,
"s": 10138,
"text": "This project is just a basic implementation of machine learning for sports analytics, just for the fun of it. I think that it was reasonably successful, but overfitting on the data is still a problem."
}
] |
Android | Creating multiple Screen app - GeeksforGeeks | 06 Nov, 2021
This article shows how to create an android application to move from one activity to another.
Below are the steps for Creating a Simple Android Application to move from one activity to another activity.
STEP-1: Create new project and your project screen looks like given below.
STEP-2: You will have xml and activity java file, path of both file given below.
STEP-3: Open your xml file and add the Button because after clicking this button we will move to second activity as shown below. Add TextView for Message. Assign ID to Button and TextView .
STEP-4: Now we have to create another activity (SecondActivity) to move from one activity to another. Create second activity and go to the android project > File >new > Activity > Empty Activity
STEP-5: Now open your second xml file, path of this file is same as first xml file. Add TextView for messages and add 2 Button one is for next activity and second for previous activity. assign ID to Textview and both Button. Second Activity is shown below:
STEP-6: Now, we have to create third activity same as second activity and path of this file is also same as another.(“Now, you can create many activity like this”) Here we add TextView for message and one Button for goto previous activity. It will be shown below
STEP-7: Now, open up the your first activity java file. define the Button (next_button or can be previous_button) and TextView variable, use findViewById() to get the Button and TextView.
STEP-8: We need to add the click listener to the all buttons (next_button or can be previous_button).
STEP-9: When the button has been clicked inside the onclicklistener method, create an Intent to start an activity called another activity.
STEP-10: Repeat step 7, 8, 9 for every activity.
STEP-11: Now run the app and click the button you can go to second activity.In First Activity here only one Button and TextView
Complete code of OneActivity.java or activity_oneactivity.xml of Firstactivity is below.
Filename: activity_oneactivity.xml
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Oneactivity" tools:layout_editor_absoluteY="81dp"> <TextView android:id="@+id/question1_id" android:layout_marginTop="60dp" android:layout_marginLeft="30dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textStyle="bold" android:textColor="@android:color/background_dark" /> <!-- add button after click this we can goto another activity--> <Button android:id="@+id/first_activity_button" android:layout_width="150dp" android:layout_height="40dp" android:layout_marginTop="200dp" android:layout_marginLeft="90dp" android:text="Next" android:textStyle="bold" android:textColor="@android:color/background_dark" android:textSize="15sp" /> </RelativeLayout>
Filename: OneActivity.java
Java
// Each new activity has its own layout and Java files,package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; public class Oneactivity extends AppCompatActivity { // define the global variable TextView question1; // Add button Move to Activity Button next_Activity_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_oneactivity); // by ID we can use each component which id is assign in xml file // use findViewById() to get the Button next_Activity_button = (Button)findViewById(R.id.first_activity_button); question1 = (TextView)findViewById(R.id.question1_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question1.setText("Q 1 - How to pass the data between activities in Android?\n" + "\n" + "Ans- Intent"); // Add_button add clicklistener next_Activity_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called SecondActivity with the following code: Intent intent = new Intent(Oneactivity.this, SecondActivity.class); // start the activity connect to the specified class startActivity(intent); } }); }}
Note: Here we will add Next Button and previous Button and textView for the message.
Complete code of SecondActivity.java or activity_second.xml of Second Activity is below.
Filename: activity_second.xml
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="org.geeksforgeeks.navedmalik.multiplescreenapp.SecondActivity"> <TextView android:id="@+id/question2_id" android:layout_marginTop="60dp" android:layout_marginLeft="30dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textStyle="bold" android:textColor="@android:color/background_dark" /> <Button android:id="@+id/second_activity_next_button" android:layout_width="90dp" android:layout_height="40dp" android:layout_marginTop="200dp" android:layout_marginLeft="200dp" android:text="Next" android:textStyle="bold" android:textColor="@android:color/background_dark" android:textSize="15sp" /> <Button android:id="@+id/second_activity_previous_button" android:layout_width="110dp" android:layout_height="40dp" android:layout_marginTop="200dp" android:layout_marginLeft="50dp" android:text="previous" android:textStyle="bold" android:textColor="@android:color/background_dark" android:textSize="15sp" /> </RelativeLayout>
Filename:SecondActivity.java
Java
package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.content.Intent;import android.widget.TextView; public class SecondActivity extends AppCompatActivity { // define the global variable TextView question2; // Add button Move to next Activity and previous Activity Button next_button, previous_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // by ID we can use each component which id is assign in xml file // use findViewById() to get the both Button and textview next_button = (Button)findViewById(R.id.second_activity_next_button); previous_button = (Button)findViewById(R.id.second_activity_previous_button); question2 = (TextView)findViewById(R.id.question2_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question2.setText("Q 2 - What is ADB in android?\n" + "\n" + "Ans- Android Debug Bridge"); // Add_button add clicklistener next_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called ThirdActivity with the following code: Intent intent = new Intent(SecondActivity.this, ThirdActivity.class); // start the activity connect to the specified class startActivity(intent); } }); // Add_button add clicklistener previous_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called oneActivity with the following code: Intent intent = new Intent(SecondActivity.this, Oneactivity.class); // start the activity connect to the specified class startActivity(intent); } }); }}
Note: Here we add only Next Button and textView for message.
Complete code of ThirdActivity.java or activity_third.xml of Third Activity is below.
Filename: activity_third.xml
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="org.geeksforgeeks.navedmalik.multiplescreenapp.ThirdActivity"> <TextView android:id="@+id/question3_id" android:layout_marginTop="60dp" android:layout_marginLeft="30dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:textColor="@android:color/background_dark" /> <Button android:id="@+id/third_activity_previous_button" android:layout_width="110dp" android:layout_height="40dp" android:layout_marginTop="200dp" android:layout_marginLeft="100dp" android:text="previous" android:textStyle="bold" android:textColor="@android:color/background_dark" android:textSize="15sp" /> </RelativeLayout>
Filename: ThirdActivity.java
Java
package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.content.Intent;import android.widget.TextView; public class ThirdActivity extends AppCompatActivity { // define the global variable TextView question3; // Add button Move previous activity Button previous_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); // by ID we can use each component which id is assign in xml file // use findViewById() to get the Button and textview. previous_button = (Button)findViewById(R.id.third_activity_previous_button); question3 = (TextView)findViewById(R.id.question3_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question3.setText("Q 3 - How to store heavy structured data in android?\n" + "\n" + "Ans- SQlite database"); // Add_button add clicklistener previous_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called SecondActivity with the following code: Intent intent = new Intent(ThirdActivity.this, SecondActivity.class); // start the activity connect to the specified class startActivity(intent); } }); }}
Output:
vartika02
kalrap615
android
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 24513,
"s": 24485,
"text": "\n06 Nov, 2021"
},
{
"code": null,
"e": 24607,
"s": 24513,
"text": "This article shows how to create an android application to move from one activity to another."
},
{
"code": null,
"e": 24716,
"s": 24607,
"text": "Below are the steps for Creating a Simple Android Application to move from one activity to another activity."
},
{
"code": null,
"e": 24791,
"s": 24716,
"text": "STEP-1: Create new project and your project screen looks like given below."
},
{
"code": null,
"e": 24872,
"s": 24791,
"text": "STEP-2: You will have xml and activity java file, path of both file given below."
},
{
"code": null,
"e": 25062,
"s": 24872,
"text": "STEP-3: Open your xml file and add the Button because after clicking this button we will move to second activity as shown below. Add TextView for Message. Assign ID to Button and TextView ."
},
{
"code": null,
"e": 25258,
"s": 25062,
"text": "STEP-4: Now we have to create another activity (SecondActivity) to move from one activity to another. Create second activity and go to the android project > File >new > Activity > Empty Activity "
},
{
"code": null,
"e": 25515,
"s": 25258,
"text": "STEP-5: Now open your second xml file, path of this file is same as first xml file. Add TextView for messages and add 2 Button one is for next activity and second for previous activity. assign ID to Textview and both Button. Second Activity is shown below:"
},
{
"code": null,
"e": 25778,
"s": 25515,
"text": "STEP-6: Now, we have to create third activity same as second activity and path of this file is also same as another.(“Now, you can create many activity like this”) Here we add TextView for message and one Button for goto previous activity. It will be shown below"
},
{
"code": null,
"e": 25966,
"s": 25778,
"text": "STEP-7: Now, open up the your first activity java file. define the Button (next_button or can be previous_button) and TextView variable, use findViewById() to get the Button and TextView."
},
{
"code": null,
"e": 26068,
"s": 25966,
"text": "STEP-8: We need to add the click listener to the all buttons (next_button or can be previous_button)."
},
{
"code": null,
"e": 26207,
"s": 26068,
"text": "STEP-9: When the button has been clicked inside the onclicklistener method, create an Intent to start an activity called another activity."
},
{
"code": null,
"e": 26256,
"s": 26207,
"text": "STEP-10: Repeat step 7, 8, 9 for every activity."
},
{
"code": null,
"e": 26385,
"s": 26256,
"text": "STEP-11: Now run the app and click the button you can go to second activity.In First Activity here only one Button and TextView "
},
{
"code": null,
"e": 26475,
"s": 26385,
"text": "Complete code of OneActivity.java or activity_oneactivity.xml of Firstactivity is below. "
},
{
"code": null,
"e": 26510,
"s": 26475,
"text": "Filename: activity_oneactivity.xml"
},
{
"code": null,
"e": 26514,
"s": 26510,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Oneactivity\" tools:layout_editor_absoluteY=\"81dp\"> <TextView android:id=\"@+id/question1_id\" android:layout_marginTop=\"60dp\" android:layout_marginLeft=\"30dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"\" android:textStyle=\"bold\" android:textColor=\"@android:color/background_dark\" /> <!-- add button after click this we can goto another activity--> <Button android:id=\"@+id/first_activity_button\" android:layout_width=\"150dp\" android:layout_height=\"40dp\" android:layout_marginTop=\"200dp\" android:layout_marginLeft=\"90dp\" android:text=\"Next\" android:textStyle=\"bold\" android:textColor=\"@android:color/background_dark\" android:textSize=\"15sp\" /> </RelativeLayout>",
"e": 27673,
"s": 26514,
"text": null
},
{
"code": null,
"e": 27700,
"s": 27673,
"text": "Filename: OneActivity.java"
},
{
"code": null,
"e": 27705,
"s": 27700,
"text": "Java"
},
{
"code": "// Each new activity has its own layout and Java files,package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; public class Oneactivity extends AppCompatActivity { // define the global variable TextView question1; // Add button Move to Activity Button next_Activity_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_oneactivity); // by ID we can use each component which id is assign in xml file // use findViewById() to get the Button next_Activity_button = (Button)findViewById(R.id.first_activity_button); question1 = (TextView)findViewById(R.id.question1_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question1.setText(\"Q 1 - How to pass the data between activities in Android?\\n\" + \"\\n\" + \"Ans- Intent\"); // Add_button add clicklistener next_Activity_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called SecondActivity with the following code: Intent intent = new Intent(Oneactivity.this, SecondActivity.class); // start the activity connect to the specified class startActivity(intent); } }); }}",
"e": 29560,
"s": 27705,
"text": null
},
{
"code": null,
"e": 29645,
"s": 29560,
"text": "Note: Here we will add Next Button and previous Button and textView for the message."
},
{
"code": null,
"e": 29735,
"s": 29645,
"text": "Complete code of SecondActivity.java or activity_second.xml of Second Activity is below. "
},
{
"code": null,
"e": 29765,
"s": 29735,
"text": "Filename: activity_second.xml"
},
{
"code": null,
"e": 29769,
"s": 29765,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"org.geeksforgeeks.navedmalik.multiplescreenapp.SecondActivity\"> <TextView android:id=\"@+id/question2_id\" android:layout_marginTop=\"60dp\" android:layout_marginLeft=\"30dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"\" android:textStyle=\"bold\" android:textColor=\"@android:color/background_dark\" /> <Button android:id=\"@+id/second_activity_next_button\" android:layout_width=\"90dp\" android:layout_height=\"40dp\" android:layout_marginTop=\"200dp\" android:layout_marginLeft=\"200dp\" android:text=\"Next\" android:textStyle=\"bold\" android:textColor=\"@android:color/background_dark\" android:textSize=\"15sp\" /> <Button android:id=\"@+id/second_activity_previous_button\" android:layout_width=\"110dp\" android:layout_height=\"40dp\" android:layout_marginTop=\"200dp\" android:layout_marginLeft=\"50dp\" android:text=\"previous\" android:textStyle=\"bold\" android:textColor=\"@android:color/background_dark\" android:textSize=\"15sp\" /> </RelativeLayout>",
"e": 31253,
"s": 29769,
"text": null
},
{
"code": null,
"e": 31282,
"s": 31253,
"text": "Filename:SecondActivity.java"
},
{
"code": null,
"e": 31287,
"s": 31282,
"text": "Java"
},
{
"code": "package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.content.Intent;import android.widget.TextView; public class SecondActivity extends AppCompatActivity { // define the global variable TextView question2; // Add button Move to next Activity and previous Activity Button next_button, previous_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // by ID we can use each component which id is assign in xml file // use findViewById() to get the both Button and textview next_button = (Button)findViewById(R.id.second_activity_next_button); previous_button = (Button)findViewById(R.id.second_activity_previous_button); question2 = (TextView)findViewById(R.id.question2_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question2.setText(\"Q 2 - What is ADB in android?\\n\" + \"\\n\" + \"Ans- Android Debug Bridge\"); // Add_button add clicklistener next_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called ThirdActivity with the following code: Intent intent = new Intent(SecondActivity.this, ThirdActivity.class); // start the activity connect to the specified class startActivity(intent); } }); // Add_button add clicklistener previous_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called oneActivity with the following code: Intent intent = new Intent(SecondActivity.this, Oneactivity.class); // start the activity connect to the specified class startActivity(intent); } }); }}",
"e": 33848,
"s": 31287,
"text": null
},
{
"code": null,
"e": 33909,
"s": 33848,
"text": "Note: Here we add only Next Button and textView for message."
},
{
"code": null,
"e": 33996,
"s": 33909,
"text": "Complete code of ThirdActivity.java or activity_third.xml of Third Activity is below. "
},
{
"code": null,
"e": 34025,
"s": 33996,
"text": "Filename: activity_third.xml"
},
{
"code": null,
"e": 34029,
"s": 34025,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"org.geeksforgeeks.navedmalik.multiplescreenapp.ThirdActivity\"> <TextView android:id=\"@+id/question3_id\" android:layout_marginTop=\"60dp\" android:layout_marginLeft=\"30dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textStyle=\"bold\" android:textColor=\"@android:color/background_dark\" /> <Button android:id=\"@+id/third_activity_previous_button\" android:layout_width=\"110dp\" android:layout_height=\"40dp\" android:layout_marginTop=\"200dp\" android:layout_marginLeft=\"100dp\" android:text=\"previous\" android:textStyle=\"bold\" android:textColor=\"@android:color/background_dark\" android:textSize=\"15sp\" /> </RelativeLayout>",
"e": 35121,
"s": 34029,
"text": null
},
{
"code": null,
"e": 35150,
"s": 35121,
"text": "Filename: ThirdActivity.java"
},
{
"code": null,
"e": 35155,
"s": 35150,
"text": "Java"
},
{
"code": "package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.content.Intent;import android.widget.TextView; public class ThirdActivity extends AppCompatActivity { // define the global variable TextView question3; // Add button Move previous activity Button previous_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); // by ID we can use each component which id is assign in xml file // use findViewById() to get the Button and textview. previous_button = (Button)findViewById(R.id.third_activity_previous_button); question3 = (TextView)findViewById(R.id.question3_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question3.setText(\"Q 3 - How to store heavy structured data in android?\\n\" + \"\\n\" + \"Ans- SQlite database\"); // Add_button add clicklistener previous_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called SecondActivity with the following code: Intent intent = new Intent(ThirdActivity.this, SecondActivity.class); // start the activity connect to the specified class startActivity(intent); } }); }}",
"e": 36969,
"s": 35155,
"text": null
},
{
"code": null,
"e": 36978,
"s": 36969,
"text": "Output: "
},
{
"code": null,
"e": 36990,
"s": 36980,
"text": "vartika02"
},
{
"code": null,
"e": 37000,
"s": 36990,
"text": "kalrap615"
},
{
"code": null,
"e": 37008,
"s": 37000,
"text": "android"
},
{
"code": null,
"e": 37013,
"s": 37008,
"text": "Java"
},
{
"code": null,
"e": 37027,
"s": 37013,
"text": "Java Programs"
},
{
"code": null,
"e": 37032,
"s": 37027,
"text": "Java"
},
{
"code": null,
"e": 37130,
"s": 37032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37139,
"s": 37130,
"text": "Comments"
},
{
"code": null,
"e": 37152,
"s": 37139,
"text": "Old Comments"
},
{
"code": null,
"e": 37182,
"s": 37152,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 37214,
"s": 37182,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 37265,
"s": 37214,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 37284,
"s": 37265,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 37302,
"s": 37284,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 37330,
"s": 37302,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 37374,
"s": 37330,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 37400,
"s": 37374,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 37434,
"s": 37400,
"text": "Convert Double to Integer in Java"
}
] |
Private and final methods in C# | To set private methods, use the private access specifier.
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
For final methods, use the sealed modifier.
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("ClassTwo: DerivedClass");
}
}
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": 1120,
"s": 1062,
"text": "To set private methods, use the private access specifier."
},
{
"code": null,
"e": 1372,
"s": 1120,
"text": "Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members."
},
{
"code": null,
"e": 1416,
"s": 1372,
"text": "For final methods, use the sealed modifier."
},
{
"code": null,
"e": 1616,
"s": 1416,
"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": 1640,
"s": 1616,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1776,
"s": 1640,
"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": 1857,
"s": 1776,
"text": "ClassOne is our base class, whereas ClassTwo and ClassThree are derived classes."
},
{
"code": null,
"e": 2220,
"s": 1857,
"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(\"ClassTwo: DerivedClass\");\n }\n}\n\nclass ClassThree : ClassTwo {\n public override void display() {\n Console.WriteLine(\"ClassThree: Another Derived Class\");\n }\n}"
},
{
"code": null,
"e": 2383,
"s": 2220,
"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."
}
] |
Python - RSS Feed | RSS (Rich Site Summary) is a format for delivering regularly changing web content. Many news-related sites, weblogs and other online publishers syndicate their content as an RSS Feed to whoever wants it. In python we take help of the below package to read and process these feeds.
pip install feedparser
In the below example we get the structure of the feed so that we can analyze further about which parts of the feed we want to process.
import feedparser
NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")
entry = NewsFeed.entries[1]
print entry.keys()
When we run the above program, we get the following output −
['summary_detail', 'published_parsed', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'published', 'id']
In the below example we read the title and head of the rss feed.
import feedparser
NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")
print 'Number of RSS posts :', len(NewsFeed.entries)
entry = NewsFeed.entries[1]
print 'Post Title :',entry.title
When we run the above program we get the following output −
Number of RSS posts : 5
Post Title : Cong-JD(S) in SC over choice of pro tem speaker
Based on above entry structure we can derive the necessary details from the feed using python program as shown below. As entry is a dictionary we utilize its keys to produce the values needed.
import feedparser
NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")
entry = NewsFeed.entries[1]
print entry.published
print "******"
print entry.summary
print "------News Link--------"
print entry.link
When we run the above program we get the following output −
Fri, 18 May 2018 20:13:13 GMT
******
Controversy erupted on Friday over the appointment of BJP MLA K G Bopaiah as pro tem speaker for the assembly, with Congress and JD(S) claiming the move went against convention that the post should go to the most senior member of the House. The combine approached the SC to challenge the appointment. Hearing is scheduled for 10:30 am today.
------News Link--------
https://timesofindia.indiatimes.com/india/congress-jds-in-sc-over-bjp-mla-made-pro-tem-speaker-hearing-at-1030-am/articleshow/64228740.cms
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2608,
"s": 2326,
"text": "RSS (Rich Site Summary) is a format for delivering regularly changing web content. Many news-related sites, weblogs and other online publishers syndicate their content as an RSS Feed to whoever wants it. In python we take help of the below package to read and process these feeds. "
},
{
"code": null,
"e": 2631,
"s": 2608,
"text": "pip install feedparser"
},
{
"code": null,
"e": 2766,
"s": 2631,
"text": "In the below example we get the structure of the feed so that we can analyze further about which parts of the feed we want to process."
},
{
"code": null,
"e": 2922,
"s": 2766,
"text": "import feedparser\nNewsFeed = feedparser.parse(\"https://timesofindia.indiatimes.com/rssfeedstopstories.cms\")\nentry = NewsFeed.entries[1]\n\nprint entry.keys()"
},
{
"code": null,
"e": 2983,
"s": 2922,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 3109,
"s": 2983,
"text": "['summary_detail', 'published_parsed', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'published', 'id']\n"
},
{
"code": null,
"e": 3175,
"s": 3109,
"text": " In the below example we read the title and head of the rss feed."
},
{
"code": null,
"e": 3400,
"s": 3175,
"text": "import feedparser\n\nNewsFeed = feedparser.parse(\"https://timesofindia.indiatimes.com/rssfeedstopstories.cms\")\n\nprint 'Number of RSS posts :', len(NewsFeed.entries)\n\nentry = NewsFeed.entries[1]\nprint 'Post Title :',entry.title"
},
{
"code": null,
"e": 3460,
"s": 3400,
"text": "When we run the above program we get the following output −"
},
{
"code": null,
"e": 3546,
"s": 3460,
"text": "Number of RSS posts : 5\nPost Title : Cong-JD(S) in SC over choice of pro tem speaker\n"
},
{
"code": null,
"e": 3741,
"s": 3546,
"text": "Based on above entry structure we can derive the necessary details from the feed using python program as shown below. As entry is a dictionary we utilize its keys to produce the values needed. "
},
{
"code": null,
"e": 3986,
"s": 3741,
"text": "import feedparser\n\nNewsFeed = feedparser.parse(\"https://timesofindia.indiatimes.com/rssfeedstopstories.cms\")\n\nentry = NewsFeed.entries[1]\n\nprint entry.published\nprint \"******\"\nprint entry.summary\nprint \"------News Link--------\"\nprint entry.link"
},
{
"code": null,
"e": 4046,
"s": 3986,
"text": "When we run the above program we get the following output −"
},
{
"code": null,
"e": 4589,
"s": 4046,
"text": "Fri, 18 May 2018 20:13:13 GMT\n******\nControversy erupted on Friday over the appointment of BJP MLA K G Bopaiah as pro tem speaker for the assembly, with Congress and JD(S) claiming the move went against convention that the post should go to the most senior member of the House. The combine approached the SC to challenge the appointment. Hearing is scheduled for 10:30 am today.\n------News Link--------\nhttps://timesofindia.indiatimes.com/india/congress-jds-in-sc-over-bjp-mla-made-pro-tem-speaker-hearing-at-1030-am/articleshow/64228740.cms\n"
},
{
"code": null,
"e": 4626,
"s": 4589,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4642,
"s": 4626,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4675,
"s": 4642,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4694,
"s": 4675,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4729,
"s": 4694,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4751,
"s": 4729,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4785,
"s": 4751,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4813,
"s": 4785,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4848,
"s": 4813,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4862,
"s": 4848,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4895,
"s": 4862,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4912,
"s": 4895,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4919,
"s": 4912,
"text": " Print"
},
{
"code": null,
"e": 4930,
"s": 4919,
"text": " Add Notes"
}
] |
Normalization vs Standardization — Quantitative analysis | by Shay Geller | Towards Data Science | Every ML practitioner knows that feature scaling is an important issue (read more here).
The two most discussed scaling methods are Normalization and Standardization. Normalization typically means rescales the values into a range of [0,1]. Standardization typically means rescales data to have a mean of 0 and a standard deviation of 1 (unit variance).
In this blog, I conducted a few experiments and hope to answer questions like:
Should we always scale our features?Is there a single best scaling technique?How different scaling techniques affect different classifiers?Should we consider scaling technique as an important hyperparameter of our model?
Should we always scale our features?
Is there a single best scaling technique?
How different scaling techniques affect different classifiers?
Should we consider scaling technique as an important hyperparameter of our model?
I’ll analyze the empirical results of applying different scaling methods on features in multiple experiments settings.
0. Why are we here?
1. Out-of-the-box classifiers
2. Classifier + Scaling
3. Classifier + Scaling + PCA
4. Classifier + Scaling + PCA + Hyperparameter Tuning
5. All again on more datasets:
— 5.1 Rain in Australia dataset
— 5.2 Bank Marketing dataset
— 5.3 Income classification dataset
— 5.4 Income classification dataset
Conclusions
First, I was trying to understand what is the difference between Normalization and Standardization.So, I encountered this excellent blog by Sebastian Raschka that supplies a mathematical background that satisfied my curiosity. Please take 5 minutes to read this blog if you are not familiar with Normalization or Standardization concepts.There is also a great explanation of the need for scaling features when dealing with classifiers that trained using gradient descendent methods( like neural networks) by famous Hinton here.
Ok, we grabbed some math, that’s it? Not quite. When I checked the popular ML library Sklearn, I saw that there are lots of different scaling methods. There is a great visualization of the effect of different scalers on data with outliers. But they didn’t show how it affects classification tasks with different classifiers.
I saw a lot of ML pipelines tutorials that use StandardScaler (usually called Z-score Standardization) or MinMaxScaler (usually called min-max Normalization) to scale features. Why does no one use other scaling techniques for classification? Is it possible that StandardScaler or MinMaxScaler are the best scaling methods? I didn’t see any explanation in the tutorials about why or when to use each one of them, so I thought I’d investigate the performance of these techniques by running some experiments. This is what this notebook is all about
Like many Data Science projects, lets read some data and experiment with several out-of-the-box classifiers.
Sonar dataset. It contains 208 rows and 60 feature columns. It’s a classification task to discriminate between sonar signals bounced off a metal cylinder and those bounced off a roughly cylindrical rock.
It’s a balanced dataset:
sonar[60].value_counts() # 60 is the label column nameM 111R 97
All the features in this dataset are between 0 to 1, but it’s not ensured that 1 is the max value or 0 is the min value in each feature.
I chose this dataset because, from one hand, it is small, so I can experiment pretty fast. On the other hand, it’s a hard problem and none of the classifiers achieve anything close to 100% accuracy, so we can compare meaningful results.
We will experiment with more datasets in the last section.
Code
As a preprocessing step, I already calculated all the results (it takes some time). So we only load the results file and work with it.
The code that produces the results can be found in my GitHub:https://github.com/shaygeller/Normalization_vs_Standardization.git
I pick some of the most popular classification models from Sklearn, denoted as:
(MLP is Multi-Layer Perceptron, a neural network)
The scalers I used are denoted as:
*Do not confuse Normalizer, the last scaler in the list above with the min-max normalization technique I discussed before. The min-max normalization is the second in the list and named MinMaxScaler. The Normalizer class from Sklearn normalizes samples individually to unit norm. It is not column based but a row based normalization technique.
The same seed was used when needed for reproducibility.
I randomly split the data to train-test sets of 80%-20% respectively.
All results are accuracy scores on 10-fold random cross-validation splits from the train set.
I do not discuss the results on the test set here. Usually, the test set should be kept hidden, and all of our conclusions about our classifiers should be taken only from the cross-validation scores.
In part 4, I performed nested cross-validation. One inner cross-validation with 5 random splits for hyperparameter tuning, and another outer CV with 10 random splits to get the model’s score using the best parameters. Also in this part, all data taken only from the train set. A picture is worth a thousand words:
import osimport pandas as pdresults_file = "sonar_results.csv"results_df = pd.read_csv(os.path.join("..","data","processed",results_file)).dropna().round(3)results_df
import operatorresults_df.loc[operator.and_(results_df["Classifier_Name"].str.startswith("_"), ~results_df["Classifier_Name"].str.endswith("PCA"))].dropna()
Nice results. By looking at the CV_mean column, we can see that at the moment, MLP is leading. SVM has the worst performance.
Standard deviation is pretty much the same, so we can judge mainly by the mean score. All the results below will be the mean score of 10-fold cross-validation random splits.
Now, let’s see how different scaling methods change the scores for each classifier
import operatortemp = results_df.loc[~results_df["Classifier_Name"].str.endswith("PCA")].dropna()temp["model"] = results_df["Classifier_Name"].apply(lambda sen: sen.split("_")[1])temp["scaler"] = results_df["Classifier_Name"].apply(lambda sen: sen.split("_")[0])def df_style(val): return 'font-weight: 800'pivot_t = pd.pivot_table(temp, values='CV_mean', index=["scaler"], columns=['model'], aggfunc=np.sum)pivot_t_bold = pivot_t.style.applymap(df_style, subset=pd.IndexSlice[pivot_t["CART"].idxmax(),"CART"])for col in list(pivot_t): pivot_t_bold = pivot_t_bold.applymap(df_style, subset=pd.IndexSlice[pivot_t[col].idxmax(),col])pivot_t_bold
The first row, the one without index name, is the algorithm without applying any scaling method.
import operatorcols_max_vals = {}cols_max_row_names = {}for col in list(pivot_t): row_name = pivot_t[col].idxmax() cell_val = pivot_t[col].max() cols_max_vals[col] = cell_val cols_max_row_names[col] = row_name sorted_cols_max_vals = sorted(cols_max_vals.items(), key=lambda kv: kv[1], reverse=True)print("Best classifiers sorted:\n")counter = 1for model, score in sorted_cols_max_vals: print(str(counter) + ". " + model + " + " +cols_max_row_names[model] + " : " +str(score)) counter +=1
Best classifier from each model:
1. SVM + StandardScaler : 0.8492. MLP + PowerTransformer-Yeo-Johnson : 0.8393. KNN + MinMaxScaler : 0.8134. LR + QuantileTransformer-Uniform : 0.8085. NB + PowerTransformer-Yeo-Johnson : 0.7526. LDA + PowerTransformer-Yeo-Johnson : 0.7477. CART + QuantileTransformer-Uniform : 0.748. RF + Normalizer : 0.723
There is no single scaling method to rule them all.We can see that scaling improved the results. SVM, MLP, KNN, and NB got a significant boost from different scaling methods.Notice that NB, RF, LDA, CART are unaffected by some of the scaling methods. This is, of course, related to how each of the classifiers works. Trees are not affected by scaling because the splitting criterion first orders the values of each feature and then calculate the gini\entropy of the split. Some scaling methods keep this order, so no change to the accuracy score. NB is not affected because the model’s priors determined by the count in each class and not by the actual value. Linear Discriminant Analysis (LDA) finds it’s coefficients using the variation between the classes (check this), so the scaling doesn’t matter either.Some of the scaling methods, like QuantileTransformer-Uniform, doesn’t preserve the exact order of the values in each feature, hence the change in score even in the above classifiers that were agnostic to other scaling methods.
There is no single scaling method to rule them all.
We can see that scaling improved the results. SVM, MLP, KNN, and NB got a significant boost from different scaling methods.
Notice that NB, RF, LDA, CART are unaffected by some of the scaling methods. This is, of course, related to how each of the classifiers works. Trees are not affected by scaling because the splitting criterion first orders the values of each feature and then calculate the gini\entropy of the split. Some scaling methods keep this order, so no change to the accuracy score. NB is not affected because the model’s priors determined by the count in each class and not by the actual value. Linear Discriminant Analysis (LDA) finds it’s coefficients using the variation between the classes (check this), so the scaling doesn’t matter either.
Some of the scaling methods, like QuantileTransformer-Uniform, doesn’t preserve the exact order of the values in each feature, hence the change in score even in the above classifiers that were agnostic to other scaling methods.
We know that some well-known ML methods like PCA can benefit from scaling (blog). Let’s try adding PCA(n_components=4) to the pipeline and analyze the results.
import operatortemp = results_df.copy()temp["model"] = results_df["Classifier_Name"].apply(lambda sen: sen.split("_")[1])temp["scaler"] = results_df["Classifier_Name"].apply(lambda sen: sen.split("_")[0])def df_style(val): return 'font-weight: 800'pivot_t = pd.pivot_table(temp, values='CV_mean', index=["scaler"], columns=['model'], aggfunc=np.sum)pivot_t_bold = pivot_t.style.applymap(df_style, subset=pd.IndexSlice[pivot_t["CART"].idxmax(),"CART"])for col in list(pivot_t): pivot_t_bold = pivot_t_bold.applymap(df_style, subset=pd.IndexSlice[pivot_t[col].idxmax(),col])pivot_t_bold
Most of the time scaling methods improve models with PCA, but no specific scaling method is in charge. Let’s look at “QuantileTransformer-Uniform”, the method with most of the high scores. In LDA-PCA it improved the results from 0.704 to 0.783 (8% jump in accuracy!), but in RF-PCA it makes things worse, from 0.711 to 0.668 (4.35% drop in accuracy!) On the other hand, using RF-PCA with “QuantileTransformer-Normal”, improved the accuracy to 0.766 (5% jump in accuracy!)We can see that PCA only improve LDA and RF, so PCA is not a magic solution.It’s fine. We didn’t hypertune the n_components parameter, and even if we did, PCA doesn’t guarantee to improve predictions.We can see that StandardScaler and MinMaxScaler achieve best scores only in 4 out of 16 cases. So we should think carefully what scaling method to choose, even as a default one.
Most of the time scaling methods improve models with PCA, but no specific scaling method is in charge. Let’s look at “QuantileTransformer-Uniform”, the method with most of the high scores. In LDA-PCA it improved the results from 0.704 to 0.783 (8% jump in accuracy!), but in RF-PCA it makes things worse, from 0.711 to 0.668 (4.35% drop in accuracy!) On the other hand, using RF-PCA with “QuantileTransformer-Normal”, improved the accuracy to 0.766 (5% jump in accuracy!)
We can see that PCA only improve LDA and RF, so PCA is not a magic solution.It’s fine. We didn’t hypertune the n_components parameter, and even if we did, PCA doesn’t guarantee to improve predictions.
We can see that StandardScaler and MinMaxScaler achieve best scores only in 4 out of 16 cases. So we should think carefully what scaling method to choose, even as a default one.
We can conclude that even though PCA is a known component that benefits from scaling, no single scaling method always improved our results, and some of them even cause harm(RF-PCA with StandardScaler).
The dataset is also a great factor here. To better understand the consequences of scaling methods on PCA, we should experiment with more diverse datasets (class imbalanced, different scales of features and datasets with numerical and categorical features). I’m doing this analysis in section 5.
There are big differences in the accuracy score between different scaling methods for a given classifier. One can assume that when the hyperparameters are tuned, the difference between the scaling techniques will be minor and we can use StandardScaler or MinMaxScaler as used in many classification pipelines tutorials in the web. Let’s check that!
First, NB is not here, that’s because NB has no parameters to tune.
We can see that almost all the algorithms benefit from hyperparameter tuning compare to results from o previous step. An interesting exception is MLP that got worse results. It’s probably because neural networks can easily overfit the data (especially when the number of parameters is much bigger than the number of training samples), and we didn’t perform a careful early stopping to avoid it, nor applied any regularizations.
Yet, even when the hyperparameters are tuned, there are still big differences between the results using different scaling methods. If we would compare different scaling techniques to the broadly used StandardScaler technique, we can gain up to 7% improvement in accuracy (KNN column) when experiencing with other techniques.
The main conclusion from this step is that even though the hyperparameters are tuned, changing the scaling method can dramatically affect the results. So, we should consider the scaling method as a crucial hyperparameter of our model.
Part 5 contains a more in-depth analysis of more diverse datasets. If you don’t want to deep dive into it, feel free to jump to the conclusion section.
To get a better understanding and to derive more generalized conclusions, we should experiment with more datasets.
We will apply Classifier+Scaling+PCA like section 3 on several datasets with different characteristics and analyze the results. All datasets were taken from Kaggel.
For the sake of convenience, I selected only the numerical columns out of each dataset. In multivariate datasets (numeric and categorical features), there is an ongoing debate about how to scale the features.
I didn’t hypertune any parameters of the classifiers.
LinkClassification task: Predict is it’s going to rain?Metric: AccuracyDataset shape: (56420, 18)Counts for each class:No 43993Yes 12427
Here is a sample of 5 rows, we can’t show all the columns in one picture.
dataset.describe()
We will suspect that scaling will improve classification results due to the different scales of the features (check min max values in the above table, it even get worse on some of the rest of the features).
Results
Results analysis
We can see the StandardScaler never got the highest score, nor MinMaxScaler.
We can see differences of up to 20% between StandardScaler and other methods. (CART-PCA column)
We can see that scaling usually improved the results. Take for example SVM that jumped from 78% to 99%.
LinkClassification task: Predict has the client subscribed a term deposit?Metric: AUC ( The data is imbalanced)Dataset shape: (41188, 11)Counts for each class:no 36548yes 4640
Here is a sample of 5 rows, we can’t show all the columns in one picture.
dataset.describe()
Again, features in different scales.
Results
Results analysis
We can see that in this dataset, even though the features are on different scales, scaling when using PCA doesn’t always improve the results. However, the second-best score in each PCA column is pretty close to the best score. It might indicate that hypertune the number of components of the PCA and using scaling will improve the results over not scaling at all.
Again, there is no one single scaling method that stood out.
Another interesting result is that in most models, all the scaling methods didn’t affect that much (usually 1%–3% improvement). Let’s remember that this is an unbalanced dataset and we didn’t hypertune the parameters. Another reason is that the AUC score is already high (~90%), so it’s harder to see major improvements.
LinkClassification task: Predict if an object to be either a galaxy, star or quasar.Metric: Accuracy (multiclass)Dataset shape: (10000, 18)Counts for each class:GALAXY 4998STAR 4152QSO 850
Here is a sample of 5 rows, we can’t show all the columns in one picture.
dataset.describe()
Again, features in different scales.
Results
Results analysis
We can see that scaling highly improved the results. We could expect it because it contains features on different scales.
We can see that RobustScaler almost always wins when we use PCA. It might be due to the many outliers in this dataset that shift the PCA eigenvectors. On the other hand, those outliers don’t make such an effect when we do not use PCA. We should do some data exploration to check that.
There is up to 5% difference in accuracy if we will compare StandardScaler to the other scaling method. So it’s another indicator to the need for experiment with multiple scaling techniques.
PCA almost always benefit from scaling.
LinkClassification task: Predict if income is >50K, <=50K.Metric: AUC (imbalanced dataset)Dataset shape: (32561, 7)Counts for each class: <=50K 24720 >50K 7841
Here is a sample of 5 rows, we can’t show all the columns in one picture.
dataset.describe()
Again, features in different scales.
Results
Results analysis
Here again, we have an imbalanced dataset, but we can see that scaling do a good job in improving the results (up to 20%!). This is probably because the AUC score is lower (~80%) compared to the Bank Marketing dataset, so it’s easier to see major improvements.
Even though StandardScaler is not highlighted (I highlighted only the first best score in each column), in many columns, it achieves the same results as the best, but not always. From the running time results(no appeared here), I can tell you that running StandatdScaler is much faster than many of the other scalers. So if you are in a rush to get some results, it can be a good starting point. But if you want to squeeze every percent from your model, you might want to experience with multiple scaling methods.
Again, no single best scale method.
PCA almost always benefited from scaling
Experiment with multiple scaling methods can dramatically increase your score on classification tasks, even when you hyperparameters are tuned. So, you should consider the scaling method as an important hyperparameter of your model.
Scaling methods affect differently on different classifiers. Distance-based classifiers like SVM, KNN, and MLP(neural network) dramatically benefit from scaling. But even trees (CART, RF), that are agnostic to some of the scaling methods, can benefit from other methods.
Knowing the underlying math behind models\preprocessing methods is the best way to understand the results. (For example, how trees work and why some of the scaling methods didn’t affect them). It can also save you a lot of time if you know no to apply StandardScaler when your model is Random Forest.
Preprocessing methods like PCA that known to be benefited from scaling, do benefit from scaling. When it doesn’t, it might be due to a bad setup of the number of components parameter of PCA, outliers in the data or a bad choice of a scaling method.
If you find some mistakes or have proposals to improve the coverage or the validity of the experiments, please notify me. | [
{
"code": null,
"e": 135,
"s": 46,
"text": "Every ML practitioner knows that feature scaling is an important issue (read more here)."
},
{
"code": null,
"e": 399,
"s": 135,
"text": "The two most discussed scaling methods are Normalization and Standardization. Normalization typically means rescales the values into a range of [0,1]. Standardization typically means rescales data to have a mean of 0 and a standard deviation of 1 (unit variance)."
},
{
"code": null,
"e": 478,
"s": 399,
"text": "In this blog, I conducted a few experiments and hope to answer questions like:"
},
{
"code": null,
"e": 699,
"s": 478,
"text": "Should we always scale our features?Is there a single best scaling technique?How different scaling techniques affect different classifiers?Should we consider scaling technique as an important hyperparameter of our model?"
},
{
"code": null,
"e": 736,
"s": 699,
"text": "Should we always scale our features?"
},
{
"code": null,
"e": 778,
"s": 736,
"text": "Is there a single best scaling technique?"
},
{
"code": null,
"e": 841,
"s": 778,
"text": "How different scaling techniques affect different classifiers?"
},
{
"code": null,
"e": 923,
"s": 841,
"text": "Should we consider scaling technique as an important hyperparameter of our model?"
},
{
"code": null,
"e": 1042,
"s": 923,
"text": "I’ll analyze the empirical results of applying different scaling methods on features in multiple experiments settings."
},
{
"code": null,
"e": 1062,
"s": 1042,
"text": "0. Why are we here?"
},
{
"code": null,
"e": 1092,
"s": 1062,
"text": "1. Out-of-the-box classifiers"
},
{
"code": null,
"e": 1116,
"s": 1092,
"text": "2. Classifier + Scaling"
},
{
"code": null,
"e": 1146,
"s": 1116,
"text": "3. Classifier + Scaling + PCA"
},
{
"code": null,
"e": 1200,
"s": 1146,
"text": "4. Classifier + Scaling + PCA + Hyperparameter Tuning"
},
{
"code": null,
"e": 1231,
"s": 1200,
"text": "5. All again on more datasets:"
},
{
"code": null,
"e": 1263,
"s": 1231,
"text": "— 5.1 Rain in Australia dataset"
},
{
"code": null,
"e": 1292,
"s": 1263,
"text": "— 5.2 Bank Marketing dataset"
},
{
"code": null,
"e": 1328,
"s": 1292,
"text": "— 5.3 Income classification dataset"
},
{
"code": null,
"e": 1364,
"s": 1328,
"text": "— 5.4 Income classification dataset"
},
{
"code": null,
"e": 1376,
"s": 1364,
"text": "Conclusions"
},
{
"code": null,
"e": 1904,
"s": 1376,
"text": "First, I was trying to understand what is the difference between Normalization and Standardization.So, I encountered this excellent blog by Sebastian Raschka that supplies a mathematical background that satisfied my curiosity. Please take 5 minutes to read this blog if you are not familiar with Normalization or Standardization concepts.There is also a great explanation of the need for scaling features when dealing with classifiers that trained using gradient descendent methods( like neural networks) by famous Hinton here."
},
{
"code": null,
"e": 2229,
"s": 1904,
"text": "Ok, we grabbed some math, that’s it? Not quite. When I checked the popular ML library Sklearn, I saw that there are lots of different scaling methods. There is a great visualization of the effect of different scalers on data with outliers. But they didn’t show how it affects classification tasks with different classifiers."
},
{
"code": null,
"e": 2775,
"s": 2229,
"text": "I saw a lot of ML pipelines tutorials that use StandardScaler (usually called Z-score Standardization) or MinMaxScaler (usually called min-max Normalization) to scale features. Why does no one use other scaling techniques for classification? Is it possible that StandardScaler or MinMaxScaler are the best scaling methods? I didn’t see any explanation in the tutorials about why or when to use each one of them, so I thought I’d investigate the performance of these techniques by running some experiments. This is what this notebook is all about"
},
{
"code": null,
"e": 2884,
"s": 2775,
"text": "Like many Data Science projects, lets read some data and experiment with several out-of-the-box classifiers."
},
{
"code": null,
"e": 3088,
"s": 2884,
"text": "Sonar dataset. It contains 208 rows and 60 feature columns. It’s a classification task to discriminate between sonar signals bounced off a metal cylinder and those bounced off a roughly cylindrical rock."
},
{
"code": null,
"e": 3113,
"s": 3088,
"text": "It’s a balanced dataset:"
},
{
"code": null,
"e": 3184,
"s": 3113,
"text": "sonar[60].value_counts() # 60 is the label column nameM 111R 97"
},
{
"code": null,
"e": 3321,
"s": 3184,
"text": "All the features in this dataset are between 0 to 1, but it’s not ensured that 1 is the max value or 0 is the min value in each feature."
},
{
"code": null,
"e": 3558,
"s": 3321,
"text": "I chose this dataset because, from one hand, it is small, so I can experiment pretty fast. On the other hand, it’s a hard problem and none of the classifiers achieve anything close to 100% accuracy, so we can compare meaningful results."
},
{
"code": null,
"e": 3617,
"s": 3558,
"text": "We will experiment with more datasets in the last section."
},
{
"code": null,
"e": 3622,
"s": 3617,
"text": "Code"
},
{
"code": null,
"e": 3757,
"s": 3622,
"text": "As a preprocessing step, I already calculated all the results (it takes some time). So we only load the results file and work with it."
},
{
"code": null,
"e": 3885,
"s": 3757,
"text": "The code that produces the results can be found in my GitHub:https://github.com/shaygeller/Normalization_vs_Standardization.git"
},
{
"code": null,
"e": 3965,
"s": 3885,
"text": "I pick some of the most popular classification models from Sklearn, denoted as:"
},
{
"code": null,
"e": 4015,
"s": 3965,
"text": "(MLP is Multi-Layer Perceptron, a neural network)"
},
{
"code": null,
"e": 4050,
"s": 4015,
"text": "The scalers I used are denoted as:"
},
{
"code": null,
"e": 4393,
"s": 4050,
"text": "*Do not confuse Normalizer, the last scaler in the list above with the min-max normalization technique I discussed before. The min-max normalization is the second in the list and named MinMaxScaler. The Normalizer class from Sklearn normalizes samples individually to unit norm. It is not column based but a row based normalization technique."
},
{
"code": null,
"e": 4449,
"s": 4393,
"text": "The same seed was used when needed for reproducibility."
},
{
"code": null,
"e": 4519,
"s": 4449,
"text": "I randomly split the data to train-test sets of 80%-20% respectively."
},
{
"code": null,
"e": 4613,
"s": 4519,
"text": "All results are accuracy scores on 10-fold random cross-validation splits from the train set."
},
{
"code": null,
"e": 4813,
"s": 4613,
"text": "I do not discuss the results on the test set here. Usually, the test set should be kept hidden, and all of our conclusions about our classifiers should be taken only from the cross-validation scores."
},
{
"code": null,
"e": 5127,
"s": 4813,
"text": "In part 4, I performed nested cross-validation. One inner cross-validation with 5 random splits for hyperparameter tuning, and another outer CV with 10 random splits to get the model’s score using the best parameters. Also in this part, all data taken only from the train set. A picture is worth a thousand words:"
},
{
"code": null,
"e": 5294,
"s": 5127,
"text": "import osimport pandas as pdresults_file = \"sonar_results.csv\"results_df = pd.read_csv(os.path.join(\"..\",\"data\",\"processed\",results_file)).dropna().round(3)results_df"
},
{
"code": null,
"e": 5451,
"s": 5294,
"text": "import operatorresults_df.loc[operator.and_(results_df[\"Classifier_Name\"].str.startswith(\"_\"), ~results_df[\"Classifier_Name\"].str.endswith(\"PCA\"))].dropna()"
},
{
"code": null,
"e": 5577,
"s": 5451,
"text": "Nice results. By looking at the CV_mean column, we can see that at the moment, MLP is leading. SVM has the worst performance."
},
{
"code": null,
"e": 5751,
"s": 5577,
"text": "Standard deviation is pretty much the same, so we can judge mainly by the mean score. All the results below will be the mean score of 10-fold cross-validation random splits."
},
{
"code": null,
"e": 5834,
"s": 5751,
"text": "Now, let’s see how different scaling methods change the scores for each classifier"
},
{
"code": null,
"e": 6525,
"s": 5834,
"text": "import operatortemp = results_df.loc[~results_df[\"Classifier_Name\"].str.endswith(\"PCA\")].dropna()temp[\"model\"] = results_df[\"Classifier_Name\"].apply(lambda sen: sen.split(\"_\")[1])temp[\"scaler\"] = results_df[\"Classifier_Name\"].apply(lambda sen: sen.split(\"_\")[0])def df_style(val): return 'font-weight: 800'pivot_t = pd.pivot_table(temp, values='CV_mean', index=[\"scaler\"], columns=['model'], aggfunc=np.sum)pivot_t_bold = pivot_t.style.applymap(df_style, subset=pd.IndexSlice[pivot_t[\"CART\"].idxmax(),\"CART\"])for col in list(pivot_t): pivot_t_bold = pivot_t_bold.applymap(df_style, subset=pd.IndexSlice[pivot_t[col].idxmax(),col])pivot_t_bold"
},
{
"code": null,
"e": 6622,
"s": 6525,
"text": "The first row, the one without index name, is the algorithm without applying any scaling method."
},
{
"code": null,
"e": 7131,
"s": 6622,
"text": "import operatorcols_max_vals = {}cols_max_row_names = {}for col in list(pivot_t): row_name = pivot_t[col].idxmax() cell_val = pivot_t[col].max() cols_max_vals[col] = cell_val cols_max_row_names[col] = row_name sorted_cols_max_vals = sorted(cols_max_vals.items(), key=lambda kv: kv[1], reverse=True)print(\"Best classifiers sorted:\\n\")counter = 1for model, score in sorted_cols_max_vals: print(str(counter) + \". \" + model + \" + \" +cols_max_row_names[model] + \" : \" +str(score)) counter +=1"
},
{
"code": null,
"e": 7164,
"s": 7131,
"text": "Best classifier from each model:"
},
{
"code": null,
"e": 7472,
"s": 7164,
"text": "1. SVM + StandardScaler : 0.8492. MLP + PowerTransformer-Yeo-Johnson : 0.8393. KNN + MinMaxScaler : 0.8134. LR + QuantileTransformer-Uniform : 0.8085. NB + PowerTransformer-Yeo-Johnson : 0.7526. LDA + PowerTransformer-Yeo-Johnson : 0.7477. CART + QuantileTransformer-Uniform : 0.748. RF + Normalizer : 0.723"
},
{
"code": null,
"e": 8510,
"s": 7472,
"text": "There is no single scaling method to rule them all.We can see that scaling improved the results. SVM, MLP, KNN, and NB got a significant boost from different scaling methods.Notice that NB, RF, LDA, CART are unaffected by some of the scaling methods. This is, of course, related to how each of the classifiers works. Trees are not affected by scaling because the splitting criterion first orders the values of each feature and then calculate the gini\\entropy of the split. Some scaling methods keep this order, so no change to the accuracy score. NB is not affected because the model’s priors determined by the count in each class and not by the actual value. Linear Discriminant Analysis (LDA) finds it’s coefficients using the variation between the classes (check this), so the scaling doesn’t matter either.Some of the scaling methods, like QuantileTransformer-Uniform, doesn’t preserve the exact order of the values in each feature, hence the change in score even in the above classifiers that were agnostic to other scaling methods."
},
{
"code": null,
"e": 8562,
"s": 8510,
"text": "There is no single scaling method to rule them all."
},
{
"code": null,
"e": 8686,
"s": 8562,
"text": "We can see that scaling improved the results. SVM, MLP, KNN, and NB got a significant boost from different scaling methods."
},
{
"code": null,
"e": 9323,
"s": 8686,
"text": "Notice that NB, RF, LDA, CART are unaffected by some of the scaling methods. This is, of course, related to how each of the classifiers works. Trees are not affected by scaling because the splitting criterion first orders the values of each feature and then calculate the gini\\entropy of the split. Some scaling methods keep this order, so no change to the accuracy score. NB is not affected because the model’s priors determined by the count in each class and not by the actual value. Linear Discriminant Analysis (LDA) finds it’s coefficients using the variation between the classes (check this), so the scaling doesn’t matter either."
},
{
"code": null,
"e": 9551,
"s": 9323,
"text": "Some of the scaling methods, like QuantileTransformer-Uniform, doesn’t preserve the exact order of the values in each feature, hence the change in score even in the above classifiers that were agnostic to other scaling methods."
},
{
"code": null,
"e": 9711,
"s": 9551,
"text": "We know that some well-known ML methods like PCA can benefit from scaling (blog). Let’s try adding PCA(n_components=4) to the pipeline and analyze the results."
},
{
"code": null,
"e": 10344,
"s": 9711,
"text": "import operatortemp = results_df.copy()temp[\"model\"] = results_df[\"Classifier_Name\"].apply(lambda sen: sen.split(\"_\")[1])temp[\"scaler\"] = results_df[\"Classifier_Name\"].apply(lambda sen: sen.split(\"_\")[0])def df_style(val): return 'font-weight: 800'pivot_t = pd.pivot_table(temp, values='CV_mean', index=[\"scaler\"], columns=['model'], aggfunc=np.sum)pivot_t_bold = pivot_t.style.applymap(df_style, subset=pd.IndexSlice[pivot_t[\"CART\"].idxmax(),\"CART\"])for col in list(pivot_t): pivot_t_bold = pivot_t_bold.applymap(df_style, subset=pd.IndexSlice[pivot_t[col].idxmax(),col])pivot_t_bold"
},
{
"code": null,
"e": 11193,
"s": 10344,
"text": "Most of the time scaling methods improve models with PCA, but no specific scaling method is in charge. Let’s look at “QuantileTransformer-Uniform”, the method with most of the high scores. In LDA-PCA it improved the results from 0.704 to 0.783 (8% jump in accuracy!), but in RF-PCA it makes things worse, from 0.711 to 0.668 (4.35% drop in accuracy!) On the other hand, using RF-PCA with “QuantileTransformer-Normal”, improved the accuracy to 0.766 (5% jump in accuracy!)We can see that PCA only improve LDA and RF, so PCA is not a magic solution.It’s fine. We didn’t hypertune the n_components parameter, and even if we did, PCA doesn’t guarantee to improve predictions.We can see that StandardScaler and MinMaxScaler achieve best scores only in 4 out of 16 cases. So we should think carefully what scaling method to choose, even as a default one."
},
{
"code": null,
"e": 11665,
"s": 11193,
"text": "Most of the time scaling methods improve models with PCA, but no specific scaling method is in charge. Let’s look at “QuantileTransformer-Uniform”, the method with most of the high scores. In LDA-PCA it improved the results from 0.704 to 0.783 (8% jump in accuracy!), but in RF-PCA it makes things worse, from 0.711 to 0.668 (4.35% drop in accuracy!) On the other hand, using RF-PCA with “QuantileTransformer-Normal”, improved the accuracy to 0.766 (5% jump in accuracy!)"
},
{
"code": null,
"e": 11866,
"s": 11665,
"text": "We can see that PCA only improve LDA and RF, so PCA is not a magic solution.It’s fine. We didn’t hypertune the n_components parameter, and even if we did, PCA doesn’t guarantee to improve predictions."
},
{
"code": null,
"e": 12044,
"s": 11866,
"text": "We can see that StandardScaler and MinMaxScaler achieve best scores only in 4 out of 16 cases. So we should think carefully what scaling method to choose, even as a default one."
},
{
"code": null,
"e": 12246,
"s": 12044,
"text": "We can conclude that even though PCA is a known component that benefits from scaling, no single scaling method always improved our results, and some of them even cause harm(RF-PCA with StandardScaler)."
},
{
"code": null,
"e": 12541,
"s": 12246,
"text": "The dataset is also a great factor here. To better understand the consequences of scaling methods on PCA, we should experiment with more diverse datasets (class imbalanced, different scales of features and datasets with numerical and categorical features). I’m doing this analysis in section 5."
},
{
"code": null,
"e": 12890,
"s": 12541,
"text": "There are big differences in the accuracy score between different scaling methods for a given classifier. One can assume that when the hyperparameters are tuned, the difference between the scaling techniques will be minor and we can use StandardScaler or MinMaxScaler as used in many classification pipelines tutorials in the web. Let’s check that!"
},
{
"code": null,
"e": 12958,
"s": 12890,
"text": "First, NB is not here, that’s because NB has no parameters to tune."
},
{
"code": null,
"e": 13386,
"s": 12958,
"text": "We can see that almost all the algorithms benefit from hyperparameter tuning compare to results from o previous step. An interesting exception is MLP that got worse results. It’s probably because neural networks can easily overfit the data (especially when the number of parameters is much bigger than the number of training samples), and we didn’t perform a careful early stopping to avoid it, nor applied any regularizations."
},
{
"code": null,
"e": 13711,
"s": 13386,
"text": "Yet, even when the hyperparameters are tuned, there are still big differences between the results using different scaling methods. If we would compare different scaling techniques to the broadly used StandardScaler technique, we can gain up to 7% improvement in accuracy (KNN column) when experiencing with other techniques."
},
{
"code": null,
"e": 13946,
"s": 13711,
"text": "The main conclusion from this step is that even though the hyperparameters are tuned, changing the scaling method can dramatically affect the results. So, we should consider the scaling method as a crucial hyperparameter of our model."
},
{
"code": null,
"e": 14098,
"s": 13946,
"text": "Part 5 contains a more in-depth analysis of more diverse datasets. If you don’t want to deep dive into it, feel free to jump to the conclusion section."
},
{
"code": null,
"e": 14213,
"s": 14098,
"text": "To get a better understanding and to derive more generalized conclusions, we should experiment with more datasets."
},
{
"code": null,
"e": 14378,
"s": 14213,
"text": "We will apply Classifier+Scaling+PCA like section 3 on several datasets with different characteristics and analyze the results. All datasets were taken from Kaggel."
},
{
"code": null,
"e": 14587,
"s": 14378,
"text": "For the sake of convenience, I selected only the numerical columns out of each dataset. In multivariate datasets (numeric and categorical features), there is an ongoing debate about how to scale the features."
},
{
"code": null,
"e": 14641,
"s": 14587,
"text": "I didn’t hypertune any parameters of the classifiers."
},
{
"code": null,
"e": 14778,
"s": 14641,
"text": "LinkClassification task: Predict is it’s going to rain?Metric: AccuracyDataset shape: (56420, 18)Counts for each class:No 43993Yes 12427"
},
{
"code": null,
"e": 14852,
"s": 14778,
"text": "Here is a sample of 5 rows, we can’t show all the columns in one picture."
},
{
"code": null,
"e": 14871,
"s": 14852,
"text": "dataset.describe()"
},
{
"code": null,
"e": 15078,
"s": 14871,
"text": "We will suspect that scaling will improve classification results due to the different scales of the features (check min max values in the above table, it even get worse on some of the rest of the features)."
},
{
"code": null,
"e": 15086,
"s": 15078,
"text": "Results"
},
{
"code": null,
"e": 15103,
"s": 15086,
"text": "Results analysis"
},
{
"code": null,
"e": 15180,
"s": 15103,
"text": "We can see the StandardScaler never got the highest score, nor MinMaxScaler."
},
{
"code": null,
"e": 15276,
"s": 15180,
"text": "We can see differences of up to 20% between StandardScaler and other methods. (CART-PCA column)"
},
{
"code": null,
"e": 15380,
"s": 15276,
"text": "We can see that scaling usually improved the results. Take for example SVM that jumped from 78% to 99%."
},
{
"code": null,
"e": 15556,
"s": 15380,
"text": "LinkClassification task: Predict has the client subscribed a term deposit?Metric: AUC ( The data is imbalanced)Dataset shape: (41188, 11)Counts for each class:no 36548yes 4640"
},
{
"code": null,
"e": 15630,
"s": 15556,
"text": "Here is a sample of 5 rows, we can’t show all the columns in one picture."
},
{
"code": null,
"e": 15649,
"s": 15630,
"text": "dataset.describe()"
},
{
"code": null,
"e": 15686,
"s": 15649,
"text": "Again, features in different scales."
},
{
"code": null,
"e": 15694,
"s": 15686,
"text": "Results"
},
{
"code": null,
"e": 15711,
"s": 15694,
"text": "Results analysis"
},
{
"code": null,
"e": 16075,
"s": 15711,
"text": "We can see that in this dataset, even though the features are on different scales, scaling when using PCA doesn’t always improve the results. However, the second-best score in each PCA column is pretty close to the best score. It might indicate that hypertune the number of components of the PCA and using scaling will improve the results over not scaling at all."
},
{
"code": null,
"e": 16136,
"s": 16075,
"text": "Again, there is no one single scaling method that stood out."
},
{
"code": null,
"e": 16457,
"s": 16136,
"text": "Another interesting result is that in most models, all the scaling methods didn’t affect that much (usually 1%–3% improvement). Let’s remember that this is an unbalanced dataset and we didn’t hypertune the parameters. Another reason is that the AUC score is already high (~90%), so it’s harder to see major improvements."
},
{
"code": null,
"e": 16646,
"s": 16457,
"text": "LinkClassification task: Predict if an object to be either a galaxy, star or quasar.Metric: Accuracy (multiclass)Dataset shape: (10000, 18)Counts for each class:GALAXY 4998STAR 4152QSO 850"
},
{
"code": null,
"e": 16720,
"s": 16646,
"text": "Here is a sample of 5 rows, we can’t show all the columns in one picture."
},
{
"code": null,
"e": 16739,
"s": 16720,
"text": "dataset.describe()"
},
{
"code": null,
"e": 16776,
"s": 16739,
"text": "Again, features in different scales."
},
{
"code": null,
"e": 16784,
"s": 16776,
"text": "Results"
},
{
"code": null,
"e": 16801,
"s": 16784,
"text": "Results analysis"
},
{
"code": null,
"e": 16923,
"s": 16801,
"text": "We can see that scaling highly improved the results. We could expect it because it contains features on different scales."
},
{
"code": null,
"e": 17208,
"s": 16923,
"text": "We can see that RobustScaler almost always wins when we use PCA. It might be due to the many outliers in this dataset that shift the PCA eigenvectors. On the other hand, those outliers don’t make such an effect when we do not use PCA. We should do some data exploration to check that."
},
{
"code": null,
"e": 17399,
"s": 17208,
"text": "There is up to 5% difference in accuracy if we will compare StandardScaler to the other scaling method. So it’s another indicator to the need for experiment with multiple scaling techniques."
},
{
"code": null,
"e": 17439,
"s": 17399,
"text": "PCA almost always benefit from scaling."
},
{
"code": null,
"e": 17599,
"s": 17439,
"text": "LinkClassification task: Predict if income is >50K, <=50K.Metric: AUC (imbalanced dataset)Dataset shape: (32561, 7)Counts for each class: <=50K 24720 >50K 7841"
},
{
"code": null,
"e": 17673,
"s": 17599,
"text": "Here is a sample of 5 rows, we can’t show all the columns in one picture."
},
{
"code": null,
"e": 17692,
"s": 17673,
"text": "dataset.describe()"
},
{
"code": null,
"e": 17729,
"s": 17692,
"text": "Again, features in different scales."
},
{
"code": null,
"e": 17737,
"s": 17729,
"text": "Results"
},
{
"code": null,
"e": 17754,
"s": 17737,
"text": "Results analysis"
},
{
"code": null,
"e": 18015,
"s": 17754,
"text": "Here again, we have an imbalanced dataset, but we can see that scaling do a good job in improving the results (up to 20%!). This is probably because the AUC score is lower (~80%) compared to the Bank Marketing dataset, so it’s easier to see major improvements."
},
{
"code": null,
"e": 18529,
"s": 18015,
"text": "Even though StandardScaler is not highlighted (I highlighted only the first best score in each column), in many columns, it achieves the same results as the best, but not always. From the running time results(no appeared here), I can tell you that running StandatdScaler is much faster than many of the other scalers. So if you are in a rush to get some results, it can be a good starting point. But if you want to squeeze every percent from your model, you might want to experience with multiple scaling methods."
},
{
"code": null,
"e": 18565,
"s": 18529,
"text": "Again, no single best scale method."
},
{
"code": null,
"e": 18606,
"s": 18565,
"text": "PCA almost always benefited from scaling"
},
{
"code": null,
"e": 18839,
"s": 18606,
"text": "Experiment with multiple scaling methods can dramatically increase your score on classification tasks, even when you hyperparameters are tuned. So, you should consider the scaling method as an important hyperparameter of your model."
},
{
"code": null,
"e": 19110,
"s": 18839,
"text": "Scaling methods affect differently on different classifiers. Distance-based classifiers like SVM, KNN, and MLP(neural network) dramatically benefit from scaling. But even trees (CART, RF), that are agnostic to some of the scaling methods, can benefit from other methods."
},
{
"code": null,
"e": 19411,
"s": 19110,
"text": "Knowing the underlying math behind models\\preprocessing methods is the best way to understand the results. (For example, how trees work and why some of the scaling methods didn’t affect them). It can also save you a lot of time if you know no to apply StandardScaler when your model is Random Forest."
},
{
"code": null,
"e": 19660,
"s": 19411,
"text": "Preprocessing methods like PCA that known to be benefited from scaling, do benefit from scaling. When it doesn’t, it might be due to a bad setup of the number of components parameter of PCA, outliers in the data or a bad choice of a scaling method."
}
] |
Represent Int32 as a Hexadecimal String in C# | To represent Int32 as a Hexadecimal string in C#, use the ToString() method and set the base as the ToString() method’s second parameter i.e. 16 for Hexadecimal.
Int32 represents a 32-bit signed integer.
Firstly, set an Int32 variable.
int val = 9898;
Now, convert it to a hexadecimal string by including 16 as the second parameter.
Convert.ToString(val, 16)
Live Demo
using System;
class Demo {
static void Main() {
int val = 9898;
Console.WriteLine("Integer: "+val);
Console.Write("Hex String: "+Convert.ToString(val, 16));
}
}
Integer: 9898
Hex String: 26aa | [
{
"code": null,
"e": 1224,
"s": 1062,
"text": "To represent Int32 as a Hexadecimal string in C#, use the ToString() method and set the base as the ToString() method’s second parameter i.e. 16 for Hexadecimal."
},
{
"code": null,
"e": 1266,
"s": 1224,
"text": "Int32 represents a 32-bit signed integer."
},
{
"code": null,
"e": 1298,
"s": 1266,
"text": "Firstly, set an Int32 variable."
},
{
"code": null,
"e": 1314,
"s": 1298,
"text": "int val = 9898;"
},
{
"code": null,
"e": 1395,
"s": 1314,
"text": "Now, convert it to a hexadecimal string by including 16 as the second parameter."
},
{
"code": null,
"e": 1421,
"s": 1395,
"text": "Convert.ToString(val, 16)"
},
{
"code": null,
"e": 1432,
"s": 1421,
"text": " Live Demo"
},
{
"code": null,
"e": 1617,
"s": 1432,
"text": "using System;\nclass Demo {\n static void Main() {\n int val = 9898;\n Console.WriteLine(\"Integer: \"+val);\n Console.Write(\"Hex String: \"+Convert.ToString(val, 16));\n }\n}"
},
{
"code": null,
"e": 1648,
"s": 1617,
"text": "Integer: 9898\nHex String: 26aa"
}
] |
Rexx - DataTypes | In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory to store the value associated with that variable.
You may like to store information of various data types like String, Character, Wide Character, Integer, Floating Point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
Rexx offers a wide variety of built-in data types. Following is a list of data types which are defined in Rexx.
Integer − A string of numerics that does not contain a decimal point or exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -2147483648 and 2147483647, inclusive.
Integer − A string of numerics that does not contain a decimal point or exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -2147483648 and 2147483647, inclusive.
Big Integer − A string of numbers that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -9223372036854775808 and 2147483648, inclusive, or between 2147483648 and 9223372036854775807.
Big Integer − A string of numbers that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -9223372036854775808 and 2147483648, inclusive, or between 2147483648 and 9223372036854775807.
Decimal − It will be from one of the following formats −
A string of numerics that contains a decimal point but no exponent identifier. The p represents the precision and s represents the scale of the decimal number that the string represents. The first character can be a plus (+) or minus (-) sign.
A string of numerics that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented is less than -9223372036854775808 or greater than 9223372036854775807.
Decimal − It will be from one of the following formats −
A string of numerics that contains a decimal point but no exponent identifier. The p represents the precision and s represents the scale of the decimal number that the string represents. The first character can be a plus (+) or minus (-) sign.
A string of numerics that contains a decimal point but no exponent identifier. The p represents the precision and s represents the scale of the decimal number that the string represents. The first character can be a plus (+) or minus (-) sign.
A string of numerics that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented is less than -9223372036854775808 or greater than 9223372036854775807.
A string of numerics that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented is less than -9223372036854775808 or greater than 9223372036854775807.
Float − A string that represents a number in scientific notation. The string consists of a series of numerics followed by an exponent identifier (an E or e followed by an optional plus (+) or minus (-) sign and a series of numerics). The string can begin with a plus (+) or minus (-) sign.
Float − A string that represents a number in scientific notation. The string consists of a series of numerics followed by an exponent identifier (an E or e followed by an optional plus (+) or minus (-) sign and a series of numerics). The string can begin with a plus (+) or minus (-) sign.
String − A normal string of characters.
String − A normal string of characters.
Following are some examples of how each data type can be used. Again each data type will be discussed in detail in the subsequent chapters. This is just to get you up to speed with a brief description of the above mentioned data types.
An example of how the number data type can be used is shown in the following program. This program shows the addition of 2 Integers.
Example
/* Main program
The below program is used to add numbers
Call the add function */
add(5,6)
exit
add:
parse arg a,b
say a + b
The output of the above program will be −
11
The following program shows the capability of Rexx to handle big integers. This program shows how to add 2 big integers.
Example
/* Main program
The below program is used to add numbers
Call the add function */
add(500000000000,6000000000000000000000)
exit
add:
parse arg a,b
say a + b
The output of the above program will be −
6.00000000E+21
The following program shows the capability of Rexx to handle decimal numbers. This program shows how to add 2 decimal numbers.
Example
/* Main program
The below program is used to add numbers
Call the add function */
add(5.5,6.6)
exit
add:
parse arg a,b
say a + b
The output of the above program will be −
12.1
The following example show cases how a number can work as a float.
Example
/* Main program
The below program is used to add numbers
Call the add function */
add(12E2,14E4)
exit
add:
parse arg a,b
say a + b
The output of the above program will be −
141200
An example of how the Tuple data type can be used is shown in the following program.
Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Rexx which can be used to determine the size of the tuple.
Example
/* Main program */
display("hello")
exit
display:
parse arg a
say a
The output of the above program will be −
hello
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2640,
"s": 2339,
"text": "In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory to store the value associated with that variable."
},
{
"code": null,
"e": 2906,
"s": 2640,
"text": "You may like to store information of various data types like String, Character, Wide Character, Integer, Floating Point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory."
},
{
"code": null,
"e": 3018,
"s": 2906,
"text": "Rexx offers a wide variety of built-in data types. Following is a list of data types which are defined in Rexx."
},
{
"code": null,
"e": 3254,
"s": 3018,
"text": "Integer − A string of numerics that does not contain a decimal point or exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -2147483648 and 2147483647, inclusive."
},
{
"code": null,
"e": 3490,
"s": 3254,
"text": "Integer − A string of numerics that does not contain a decimal point or exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -2147483648 and 2147483647, inclusive."
},
{
"code": null,
"e": 3788,
"s": 3490,
"text": "Big Integer − A string of numbers that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -9223372036854775808 and 2147483648, inclusive, or between 2147483648 and 9223372036854775807."
},
{
"code": null,
"e": 4086,
"s": 3788,
"text": "Big Integer − A string of numbers that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented must be between -9223372036854775808 and 2147483648, inclusive, or between 2147483648 and 9223372036854775807."
},
{
"code": null,
"e": 4635,
"s": 4086,
"text": "Decimal − It will be from one of the following formats −\n\nA string of numerics that contains a decimal point but no exponent identifier. The p represents the precision and s represents the scale of the decimal number that the string represents. The first character can be a plus (+) or minus (-) sign.\nA string of numerics that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented is less than -9223372036854775808 or greater than 9223372036854775807.\n\n"
},
{
"code": null,
"e": 4692,
"s": 4635,
"text": "Decimal − It will be from one of the following formats −"
},
{
"code": null,
"e": 4936,
"s": 4692,
"text": "A string of numerics that contains a decimal point but no exponent identifier. The p represents the precision and s represents the scale of the decimal number that the string represents. The first character can be a plus (+) or minus (-) sign."
},
{
"code": null,
"e": 5180,
"s": 4936,
"text": "A string of numerics that contains a decimal point but no exponent identifier. The p represents the precision and s represents the scale of the decimal number that the string represents. The first character can be a plus (+) or minus (-) sign."
},
{
"code": null,
"e": 5425,
"s": 5180,
"text": "A string of numerics that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented is less than -9223372036854775808 or greater than 9223372036854775807."
},
{
"code": null,
"e": 5670,
"s": 5425,
"text": "A string of numerics that does not contain a decimal point or an exponent identifier. The first character can be a plus (+) or minus (-) sign. The number that is represented is less than -9223372036854775808 or greater than 9223372036854775807."
},
{
"code": null,
"e": 5960,
"s": 5670,
"text": "Float − A string that represents a number in scientific notation. The string consists of a series of numerics followed by an exponent identifier (an E or e followed by an optional plus (+) or minus (-) sign and a series of numerics). The string can begin with a plus (+) or minus (-) sign."
},
{
"code": null,
"e": 6250,
"s": 5960,
"text": "Float − A string that represents a number in scientific notation. The string consists of a series of numerics followed by an exponent identifier (an E or e followed by an optional plus (+) or minus (-) sign and a series of numerics). The string can begin with a plus (+) or minus (-) sign."
},
{
"code": null,
"e": 6290,
"s": 6250,
"text": "String − A normal string of characters."
},
{
"code": null,
"e": 6330,
"s": 6290,
"text": "String − A normal string of characters."
},
{
"code": null,
"e": 6566,
"s": 6330,
"text": "Following are some examples of how each data type can be used. Again each data type will be discussed in detail in the subsequent chapters. This is just to get you up to speed with a brief description of the above mentioned data types."
},
{
"code": null,
"e": 6699,
"s": 6566,
"text": "An example of how the number data type can be used is shown in the following program. This program shows the addition of 2 Integers."
},
{
"code": null,
"e": 6707,
"s": 6699,
"text": "Example"
},
{
"code": null,
"e": 6844,
"s": 6707,
"text": "/* Main program \nThe below program is used to add numbers \nCall the add function */ \nadd(5,6) \n\nexit \nadd: \n\nparse arg a,b \nsay a + b "
},
{
"code": null,
"e": 6886,
"s": 6844,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 6890,
"s": 6886,
"text": "11\n"
},
{
"code": null,
"e": 7011,
"s": 6890,
"text": "The following program shows the capability of Rexx to handle big integers. This program shows how to add 2 big integers."
},
{
"code": null,
"e": 7019,
"s": 7011,
"text": "Example"
},
{
"code": null,
"e": 7187,
"s": 7019,
"text": "/* Main program \nThe below program is used to add numbers \nCall the add function */ \nadd(500000000000,6000000000000000000000) \n\nexit \nadd: \n\nparse arg a,b \nsay a + b"
},
{
"code": null,
"e": 7229,
"s": 7187,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 7245,
"s": 7229,
"text": "6.00000000E+21\n"
},
{
"code": null,
"e": 7372,
"s": 7245,
"text": "The following program shows the capability of Rexx to handle decimal numbers. This program shows how to add 2 decimal numbers."
},
{
"code": null,
"e": 7380,
"s": 7372,
"text": "Example"
},
{
"code": null,
"e": 7521,
"s": 7380,
"text": "/* Main program \nThe below program is used to add numbers \nCall the add function */ \nadd(5.5,6.6) \n\nexit \nadd: \n\nparse arg a,b \nsay a + b "
},
{
"code": null,
"e": 7563,
"s": 7521,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 7570,
"s": 7563,
"text": "12.1 \n"
},
{
"code": null,
"e": 7637,
"s": 7570,
"text": "The following example show cases how a number can work as a float."
},
{
"code": null,
"e": 7645,
"s": 7637,
"text": "Example"
},
{
"code": null,
"e": 7787,
"s": 7645,
"text": "/* Main program \nThe below program is used to add numbers \nCall the add function */ \nadd(12E2,14E4) \n\nexit \nadd: \n\nparse arg a,b \nsay a + b"
},
{
"code": null,
"e": 7829,
"s": 7787,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 7837,
"s": 7829,
"text": "141200\n"
},
{
"code": null,
"e": 7922,
"s": 7837,
"text": "An example of how the Tuple data type can be used is shown in the following program."
},
{
"code": null,
"e": 8080,
"s": 7922,
"text": "Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Rexx which can be used to determine the size of the tuple."
},
{
"code": null,
"e": 8088,
"s": 8080,
"text": "Example"
},
{
"code": null,
"e": 8165,
"s": 8088,
"text": "/* Main program */ \ndisplay(\"hello\") \n\nexit \ndisplay: \n\nparse arg a \nsay a"
},
{
"code": null,
"e": 8207,
"s": 8165,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 8214,
"s": 8207,
"text": "hello\n"
},
{
"code": null,
"e": 8221,
"s": 8214,
"text": " Print"
},
{
"code": null,
"e": 8232,
"s": 8221,
"text": " Add Notes"
}
] |
Elasticsearch - IngestNode | Sometimes we need to transform a document before we index it. For instance, we want to remove a field from the document or rename a field and then index it. This is handled by Ingest node.
Every node in the cluster has the ability to ingest but it can also be customized to be
processed only by specific nodes.
There are two steps involved in the working of the ingest node −
Creating a pipeline
Creating a doc
First creating a pipeline which contains the processors and then executing the pipeline, as
shown below −
PUT _ingest/pipeline/int-converter
{
"description": "converts the content of the seq field to an integer",
"processors" : [
{
"convert" : {
"field" : "seq",
"type": "integer"
}
}
]
}
On running the above code, we get the following result −
{
"acknowledged" : true
}
Next we create a document using the pipeline converter.
PUT /logs/_doc/1?pipeline=int-converter
{
"seq":"21",
"name":"Tutorialspoint",
"Addrs":"Hyderabad"
}
On running the above code, we get the response as shown below −
{
"_index" : "logs",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
Next we search for the doc created above by using the GET command as shown below −
GET /logs/_doc/1
On running the above code, we get the following result −
{
"_index" : "logs",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"Addrs" : "Hyderabad",
"name" : "Tutorialspoint",
"seq" : 21
}
}
You can see above that 21 has become an integer.
Now we create a document without using the pipeline.
PUT /logs/_doc/2
{
"seq":"11",
"name":"Tutorix",
"Addrs":"Secunderabad"
}
GET /logs/_doc/2
On running the above code, we get the following result −
{
"_index" : "logs",
"_type" : "_doc",
"_id" : "2",
"_version" : 1,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"seq" : "11",
"name" : "Tutorix",
"Addrs" : "Secunderabad"
}
}
You can see above that 11 is a string without the pipeline being used.
14 Lectures
5 hours
Manuj Aggarwal
20 Lectures
1 hours
Faizan Tayyab
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2770,
"s": 2581,
"text": "Sometimes we need to transform a document before we index it. For instance, we want to remove a field from the document or rename a field and then index it. This is handled by Ingest node."
},
{
"code": null,
"e": 2892,
"s": 2770,
"text": "Every node in the cluster has the ability to ingest but it can also be customized to be\nprocessed only by specific nodes."
},
{
"code": null,
"e": 2957,
"s": 2892,
"text": "There are two steps involved in the working of the ingest node −"
},
{
"code": null,
"e": 2977,
"s": 2957,
"text": "Creating a pipeline"
},
{
"code": null,
"e": 2992,
"s": 2977,
"text": "Creating a doc"
},
{
"code": null,
"e": 3098,
"s": 2992,
"text": "First creating a pipeline which contains the processors and then executing the pipeline, as\nshown below −"
},
{
"code": null,
"e": 3344,
"s": 3098,
"text": "PUT _ingest/pipeline/int-converter\n{\n \"description\": \"converts the content of the seq field to an integer\",\n \"processors\" : [\n {\n \"convert\" : {\n \"field\" : \"seq\",\n \"type\": \"integer\"\n }\n }\n ]\n}"
},
{
"code": null,
"e": 3401,
"s": 3344,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 3431,
"s": 3401,
"text": "{\n \"acknowledged\" : true\n}\n"
},
{
"code": null,
"e": 3487,
"s": 3431,
"text": "Next we create a document using the pipeline converter."
},
{
"code": null,
"e": 3597,
"s": 3487,
"text": "PUT /logs/_doc/1?pipeline=int-converter\n{\n \"seq\":\"21\",\n \"name\":\"Tutorialspoint\",\n \"Addrs\":\"Hyderabad\"\n}"
},
{
"code": null,
"e": 3661,
"s": 3597,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 3895,
"s": 3661,
"text": "{\n \"_index\" : \"logs\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 0,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 3978,
"s": 3895,
"text": "Next we search for the doc created above by using the GET command as shown below −"
},
{
"code": null,
"e": 3995,
"s": 3978,
"text": "GET /logs/_doc/1"
},
{
"code": null,
"e": 4052,
"s": 3995,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 4297,
"s": 4052,
"text": "{\n \"_index\" : \"logs\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"_seq_no\" : 0,\n \"_primary_term\" : 1,\n \"found\" : true,\n \"_source\" : {\n \"Addrs\" : \"Hyderabad\",\n \"name\" : \"Tutorialspoint\",\n \"seq\" : 21\n }\n}\n"
},
{
"code": null,
"e": 4346,
"s": 4297,
"text": "You can see above that 21 has become an integer."
},
{
"code": null,
"e": 4399,
"s": 4346,
"text": "Now we create a document without using the pipeline."
},
{
"code": null,
"e": 4499,
"s": 4399,
"text": "PUT /logs/_doc/2\n{\n \"seq\":\"11\",\n \"name\":\"Tutorix\",\n \"Addrs\":\"Secunderabad\"\n}\nGET /logs/_doc/2"
},
{
"code": null,
"e": 4556,
"s": 4499,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 4799,
"s": 4556,
"text": "{\n \"_index\" : \"logs\",\n \"_type\" : \"_doc\",\n \"_id\" : \"2\",\n \"_version\" : 1,\n \"_seq_no\" : 1,\n \"_primary_term\" : 1,\n \"found\" : true,\n \"_source\" : {\n \"seq\" : \"11\",\n \"name\" : \"Tutorix\",\n \"Addrs\" : \"Secunderabad\"\n }\n}\n"
},
{
"code": null,
"e": 4870,
"s": 4799,
"text": "You can see above that 11 is a string without the pipeline being used."
},
{
"code": null,
"e": 4903,
"s": 4870,
"text": "\n 14 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4919,
"s": 4903,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 4952,
"s": 4919,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4967,
"s": 4952,
"text": " Faizan Tayyab"
},
{
"code": null,
"e": 4974,
"s": 4967,
"text": " Print"
},
{
"code": null,
"e": 4985,
"s": 4974,
"text": " Add Notes"
}
] |
Python Risk Management: Monte Carlo Simulations | by Lester Leong | Towards Data Science | In this article, we’ll go over Monte Carlo simulations, which can be applied to offer insights on modeling future events. The whole idea of this article came from a combination of two factors. First was from an experiment I am running off of options trading, the journey can be found here. The second was the other Python Risk Management article about Kelly Criterion was pretty popular, so I thought of expanding the topic, which the original article is found here. Without further ado, let’s begin the discussion on Monte Carlo simulations for asset pricing!
A common way Monte Carlo simulations is taught is thinking about any form of chance, hence the slot machine image. At any given time, multiple events can occur in the next time step based on an action. Now, I believe in learning simple examples first to understand complex ones, so let’s think about throwing a fair six-sided die. We all know that dice have 6 possible chances numbering from 1 to 6. But to figure out how much experimentally, we would have to roll the die a few times and record the results. With Monte Carlo simulations, we can perform as many amount of trials we want within the simulation.
In a more technical definition, Monte Carlo are taken from a probability distribution to provide a multivariate model of risk or present multiple what if events [1]. The base formula for Monte Carlo boils down to:
Basically, the formula is made up of 3 major components. First, is the data over time of the asset we are looking at. In our article, it would be the cryptocurrency Tezos and the stock ticker AMD. The next piece is drift, which is the direction the asset has been moving in the past. The third component is a random component taken from a distribution. In our case, we will use the normal distribution to simulate asset volatility. Volatility is normally seen as the crazy movement a stock does on a usual basis that kind of looks random.
As stated earlier, Monte Carlo is a good way to map out a problem with multiple possible outcomes. In finance and specifically the financial markets, an asset could go to multiple different price levels in the future. Besides asset pricing, Monte Carlo simulation can be applied in projecting financial line items such as cash flow [2].
Tezos is another crypto currency that applies smart contracts like Etherium [3]. I just got curious about it, since there is an interesting feature dividend like feature about it. At least in my Tezos holdings in Coinbase, it actually paid roughly 5% for holding it (Tezos rewards), which is similar to a dividend yield in stocks — image below:
Just a heads up, I got the Tezos for free by learning about in Coinbase and you can get $10 for signing up with this affiliate link. To get the earn the Tezos, you have to scroll down in your dashboard and should see an earn page. The just complete the tutorial and you should see rewards available. One example of the crypto EOS can be found in this affiliate link. On to the Tezos Monte Carlo simulation example, daily data taken from investing.com:
#Import Librariesimport numpy as np import pandas as pd import pandas_datareader as wb import matplotlib.pyplot as plt from scipy.stats import norm%matplotlib inline#Settings for Monte Carlo asset data, how long, and how many forecasts ticker = 'XTZ_USD' # tickert_intervals = 30 # time steps forecasted into futureiterations = 25 # amount of simulations#Acquiring datadata = pd.read_csv('XTZ_USD Huobi Historical Data.csv',index_col=0,usecols=['Date', 'Price'])data = data.rename(columns={"Price": ticker})#Preparing log returns from datalog_returns = np.log(1 + data.pct_change())#Plot of asset historical closing pricedata.plot(figsize=(10, 6));
#Plot of log returnslog_returns.plot(figsize = (10, 6))
#Setting up drift and random component in relation to asset datau = log_returns.mean()var = log_returns.var()drift = u - (0.5 * var)stdev = log_returns.std()daily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations)))#Takes last data point as startpoint point for simulationS0 = data.iloc[-1]price_list = np.zeros_like(daily_returns)price_list[0] = S0#Applies Monte Carlo simulation in assetfor t in range(1, t_intervals): price_list[t] = price_list[t - 1] * daily_returns[t]#Plot simulationsplt.figure(figsize=(10,6))plt.plot(price_list);
One thing to note is the large volatility in these simulations. From today’s price of 1.50, Tezos can potentially swing from 1.00 to 2.75! From these small number of simulations, I can see why some people like to take a chance on Bitcoin and similar cryptos due to the slightly favored upside potential.
I just decided to do AMD due to my other posts trading AMD options found here. Now, let’s get to the Advanced Micro Devices Monte Carlo simulation.
#Import Librariesimport numpy as np import pandas as pd import pandas_datareader as wb import matplotlib.pyplot as plt from scipy.stats import norm%matplotlib inline#Settings for Monte Carlo asset data, how long, and how many forecasts ticker = 'AMD' # stock tickert_intervals = 30 # time steps forecasted into futureiterations = 25 # amount of simulations#Acquiring datadata = pd.DataFrame()data[ticker] = wb.DataReader(ticker, data_source='yahoo', start='2018-1-1')['Adj Close']#Preparing log returns from datalog_returns = np.log(1 + data.pct_change())#Plot of asset historical closing pricedata.plot(figsize=(10, 6));
#Plot of log returnslog_returns.plot(figsize = (10, 6))
The log returns are looking pretty good from the closing prices above. Now on to setting up the drift and random components.
#Setting up drift and random component in relatoin to asset datau = log_returns.mean()var = log_returns.var()drift = u - (0.5 * var)stdev = log_returns.std()daily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations)))#Takes last data point as startpoint point for simulationS0 = data.iloc[-1]price_list = np.zeros_like(daily_returns)price_list[0] = S0#Applies Monte Carlo simulation in assetfor t in range(1, t_intervals): price_list[t] = price_list[t - 1] * daily_returns[t]#Plot simulationsplt.figure(figsize=(10,6))plt.plot(price_list);
Looks like the overall trend of AMD from the Monte Carlo simulations is up, which is a good sign due to my bullish positions at the time of the challenge!
Monte Carlo simulations permit investors and traders to transform investment possibilities into decisions. The upside of Monte Carlo is its capacity to factor in a scope of qualities for different possible events. This is likewise its most noteworthy downside is it sometimes fails to accurately gauge extreme events. For example, multiple Monte Carlo simulations failed during the great bear crisis. So, this model-like others are restricted by the data and settings applied. One possible solution to this weakness is to take a non-normal probably distribution for the random component simulated.
— — — — — — — — — — — — — — — — — — — — — — — — — —
References
[1] Stammers, R. (2020, January 3). How to Use Monte Carlo Analysis to Estimate Risk. Retrieved from https://www.investopedia.com/articles/financial-theory/08/monte-carlo-multivariate-model.asp
[2] Agarwal, K. (2019, November 18). What Can The Monte Carlo Simulation Do For Your Portfolio? Retrieved from https://www.investopedia.com/articles/investing/112514/monte-carlo-simulation-basics.asp
[3] Coinbase. (2019). Earn Tezos. Retrieved from https://www.coinbase.com/earn/tezos
— — — — — — — — — — — — — — — — — — — — — — — — — —
To get into Coinbase click this affiliate link, so we both get $10.
This article was created due to Options $100k Challenge.
Disclaimers: All things stated in this article are of my own opinion and not of any employer. Investing carries serious risk and consult your investment advisor for all investment decisions. I may actively trade assets stated in this article. This post contains affiliate links. | [
{
"code": null,
"e": 733,
"s": 172,
"text": "In this article, we’ll go over Monte Carlo simulations, which can be applied to offer insights on modeling future events. The whole idea of this article came from a combination of two factors. First was from an experiment I am running off of options trading, the journey can be found here. The second was the other Python Risk Management article about Kelly Criterion was pretty popular, so I thought of expanding the topic, which the original article is found here. Without further ado, let’s begin the discussion on Monte Carlo simulations for asset pricing!"
},
{
"code": null,
"e": 1343,
"s": 733,
"text": "A common way Monte Carlo simulations is taught is thinking about any form of chance, hence the slot machine image. At any given time, multiple events can occur in the next time step based on an action. Now, I believe in learning simple examples first to understand complex ones, so let’s think about throwing a fair six-sided die. We all know that dice have 6 possible chances numbering from 1 to 6. But to figure out how much experimentally, we would have to roll the die a few times and record the results. With Monte Carlo simulations, we can perform as many amount of trials we want within the simulation."
},
{
"code": null,
"e": 1557,
"s": 1343,
"text": "In a more technical definition, Monte Carlo are taken from a probability distribution to provide a multivariate model of risk or present multiple what if events [1]. The base formula for Monte Carlo boils down to:"
},
{
"code": null,
"e": 2096,
"s": 1557,
"text": "Basically, the formula is made up of 3 major components. First, is the data over time of the asset we are looking at. In our article, it would be the cryptocurrency Tezos and the stock ticker AMD. The next piece is drift, which is the direction the asset has been moving in the past. The third component is a random component taken from a distribution. In our case, we will use the normal distribution to simulate asset volatility. Volatility is normally seen as the crazy movement a stock does on a usual basis that kind of looks random."
},
{
"code": null,
"e": 2433,
"s": 2096,
"text": "As stated earlier, Monte Carlo is a good way to map out a problem with multiple possible outcomes. In finance and specifically the financial markets, an asset could go to multiple different price levels in the future. Besides asset pricing, Monte Carlo simulation can be applied in projecting financial line items such as cash flow [2]."
},
{
"code": null,
"e": 2778,
"s": 2433,
"text": "Tezos is another crypto currency that applies smart contracts like Etherium [3]. I just got curious about it, since there is an interesting feature dividend like feature about it. At least in my Tezos holdings in Coinbase, it actually paid roughly 5% for holding it (Tezos rewards), which is similar to a dividend yield in stocks — image below:"
},
{
"code": null,
"e": 3230,
"s": 2778,
"text": "Just a heads up, I got the Tezos for free by learning about in Coinbase and you can get $10 for signing up with this affiliate link. To get the earn the Tezos, you have to scroll down in your dashboard and should see an earn page. The just complete the tutorial and you should see rewards available. One example of the crypto EOS can be found in this affiliate link. On to the Tezos Monte Carlo simulation example, daily data taken from investing.com:"
},
{
"code": null,
"e": 3884,
"s": 3230,
"text": "#Import Librariesimport numpy as np import pandas as pd import pandas_datareader as wb import matplotlib.pyplot as plt from scipy.stats import norm%matplotlib inline#Settings for Monte Carlo asset data, how long, and how many forecasts ticker = 'XTZ_USD' # tickert_intervals = 30 # time steps forecasted into futureiterations = 25 # amount of simulations#Acquiring datadata = pd.read_csv('XTZ_USD Huobi Historical Data.csv',index_col=0,usecols=['Date', 'Price'])data = data.rename(columns={\"Price\": ticker})#Preparing log returns from datalog_returns = np.log(1 + data.pct_change())#Plot of asset historical closing pricedata.plot(figsize=(10, 6));"
},
{
"code": null,
"e": 3940,
"s": 3884,
"text": "#Plot of log returnslog_returns.plot(figsize = (10, 6))"
},
{
"code": null,
"e": 4529,
"s": 3940,
"text": "#Setting up drift and random component in relation to asset datau = log_returns.mean()var = log_returns.var()drift = u - (0.5 * var)stdev = log_returns.std()daily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations)))#Takes last data point as startpoint point for simulationS0 = data.iloc[-1]price_list = np.zeros_like(daily_returns)price_list[0] = S0#Applies Monte Carlo simulation in assetfor t in range(1, t_intervals): price_list[t] = price_list[t - 1] * daily_returns[t]#Plot simulationsplt.figure(figsize=(10,6))plt.plot(price_list);"
},
{
"code": null,
"e": 4833,
"s": 4529,
"text": "One thing to note is the large volatility in these simulations. From today’s price of 1.50, Tezos can potentially swing from 1.00 to 2.75! From these small number of simulations, I can see why some people like to take a chance on Bitcoin and similar cryptos due to the slightly favored upside potential."
},
{
"code": null,
"e": 4981,
"s": 4833,
"text": "I just decided to do AMD due to my other posts trading AMD options found here. Now, let’s get to the Advanced Micro Devices Monte Carlo simulation."
},
{
"code": null,
"e": 5610,
"s": 4981,
"text": "#Import Librariesimport numpy as np import pandas as pd import pandas_datareader as wb import matplotlib.pyplot as plt from scipy.stats import norm%matplotlib inline#Settings for Monte Carlo asset data, how long, and how many forecasts ticker = 'AMD' # stock tickert_intervals = 30 # time steps forecasted into futureiterations = 25 # amount of simulations#Acquiring datadata = pd.DataFrame()data[ticker] = wb.DataReader(ticker, data_source='yahoo', start='2018-1-1')['Adj Close']#Preparing log returns from datalog_returns = np.log(1 + data.pct_change())#Plot of asset historical closing pricedata.plot(figsize=(10, 6));"
},
{
"code": null,
"e": 5666,
"s": 5610,
"text": "#Plot of log returnslog_returns.plot(figsize = (10, 6))"
},
{
"code": null,
"e": 5791,
"s": 5666,
"text": "The log returns are looking pretty good from the closing prices above. Now on to setting up the drift and random components."
},
{
"code": null,
"e": 6380,
"s": 5791,
"text": "#Setting up drift and random component in relatoin to asset datau = log_returns.mean()var = log_returns.var()drift = u - (0.5 * var)stdev = log_returns.std()daily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations)))#Takes last data point as startpoint point for simulationS0 = data.iloc[-1]price_list = np.zeros_like(daily_returns)price_list[0] = S0#Applies Monte Carlo simulation in assetfor t in range(1, t_intervals): price_list[t] = price_list[t - 1] * daily_returns[t]#Plot simulationsplt.figure(figsize=(10,6))plt.plot(price_list);"
},
{
"code": null,
"e": 6535,
"s": 6380,
"text": "Looks like the overall trend of AMD from the Monte Carlo simulations is up, which is a good sign due to my bullish positions at the time of the challenge!"
},
{
"code": null,
"e": 7133,
"s": 6535,
"text": "Monte Carlo simulations permit investors and traders to transform investment possibilities into decisions. The upside of Monte Carlo is its capacity to factor in a scope of qualities for different possible events. This is likewise its most noteworthy downside is it sometimes fails to accurately gauge extreme events. For example, multiple Monte Carlo simulations failed during the great bear crisis. So, this model-like others are restricted by the data and settings applied. One possible solution to this weakness is to take a non-normal probably distribution for the random component simulated."
},
{
"code": null,
"e": 7185,
"s": 7133,
"text": "— — — — — — — — — — — — — — — — — — — — — — — — — —"
},
{
"code": null,
"e": 7196,
"s": 7185,
"text": "References"
},
{
"code": null,
"e": 7390,
"s": 7196,
"text": "[1] Stammers, R. (2020, January 3). How to Use Monte Carlo Analysis to Estimate Risk. Retrieved from https://www.investopedia.com/articles/financial-theory/08/monte-carlo-multivariate-model.asp"
},
{
"code": null,
"e": 7590,
"s": 7390,
"text": "[2] Agarwal, K. (2019, November 18). What Can The Monte Carlo Simulation Do For Your Portfolio? Retrieved from https://www.investopedia.com/articles/investing/112514/monte-carlo-simulation-basics.asp"
},
{
"code": null,
"e": 7675,
"s": 7590,
"text": "[3] Coinbase. (2019). Earn Tezos. Retrieved from https://www.coinbase.com/earn/tezos"
},
{
"code": null,
"e": 7727,
"s": 7675,
"text": "— — — — — — — — — — — — — — — — — — — — — — — — — —"
},
{
"code": null,
"e": 7795,
"s": 7727,
"text": "To get into Coinbase click this affiliate link, so we both get $10."
},
{
"code": null,
"e": 7852,
"s": 7795,
"text": "This article was created due to Options $100k Challenge."
}
] |
MySQL Tryit Editor v1.0 | SELECT CONCAT("SQL ", "Tutorial ", "is ", "fun!") AS ConcatenatedString;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 73,
"s": 0,
"text": "SELECT CONCAT(\"SQL \", \"Tutorial \", \"is \", \"fun!\") AS ConcatenatedString;"
},
{
"code": null,
"e": 75,
"s": 73,
"text": ""
},
{
"code": null,
"e": 147,
"s": 84,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 207,
"s": 147,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 275,
"s": 207,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 313,
"s": 275,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 398,
"s": 313,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 572,
"s": 398,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 623,
"s": 572,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 691,
"s": 623,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 862,
"s": 691,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 962,
"s": 862,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1012,
"s": 962,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
What are Reserved Keywords in Python? | Reserved words (also called keywords) are defined with predefined meaning and syntax in the language. These keywords have to be used to develop programming instructions. Reserved words can’t be used as identifiers for other programming elements like name of variable, function etc.
Following is the list of reserved keywords in Python 3
Python 3 has 33 keywords while Python 2 has 30. The print has been removed from Python 2 as keyword and included as built-in function.
To check the keyword list, type following commands in interpreter −
>>> import keyword
>>> keyword.kwlist | [
{
"code": null,
"e": 1344,
"s": 1062,
"text": "Reserved words (also called keywords) are defined with predefined meaning and syntax in the language. These keywords have to be used to develop programming instructions. Reserved words can’t be used as identifiers for other programming elements like name of variable, function etc."
},
{
"code": null,
"e": 1399,
"s": 1344,
"text": "Following is the list of reserved keywords in Python 3"
},
{
"code": null,
"e": 1534,
"s": 1399,
"text": "Python 3 has 33 keywords while Python 2 has 30. The print has been removed from Python 2 as keyword and included as built-in function."
},
{
"code": null,
"e": 1602,
"s": 1534,
"text": "To check the keyword list, type following commands in interpreter −"
},
{
"code": null,
"e": 1640,
"s": 1602,
"text": ">>> import keyword\n>>> keyword.kwlist"
}
] |
How-to Fine-Tune a Q&A Transformer | by James Briggs | Towards Data Science | Transformer models are undoubtedly the leaders in NLP — outperforming almost every other model architecture in almost every other task.
One of the most fascinating language-based tasks that transformers have proven themselves more than capable of dealing with is question-and-answering.
In this article, we will learn about the field of Q&A in NLP — and learn how to download and fine-tune some of the most advanced transformer models in the world for this very purpose. In short:
> Our Dataset - Downloading SQuAD> Preparing The Data - Extraction - Encoding - Initializing the Dataset> Fine-Tuning> Measuring Performance - Implementing Accuracy
If you prefer video — I cover everything here too:
For our example, we will use the Stanford Question Answering Dataset (SQuAD) 2.0. Our model will be expected to correctly select the specific part of a text segment that answers a question we provide.
We can download the data in Python like so:
Which will return two files, our training data train-v2.0.json — and our validation data dev-v2.0.json. Both look like this:
Here we have three key parts in our data, which are:
Questions — strings containing the question which we will ask our model
Contexts — larger segments of text that contain the answers to our questions within them
Answers — shorter strings which are ‘extracts’ of the given contexts that provide an answer to our questions
So, we will provide the model with a question and corresponding answer. The model must then read both and return the token positions of the predicted answer from the context.
The first step in preparing this data for fine-tuning is extracting our questions, contexts, and answers from the JSON files into training and validation sets. We can do this like so:
This gives us our two datasets split between three lists (each):
Our contexts and questions are simple strings — each corresponds to each other. The answer to each question can be found within the context.
The answers lists are slightly different in that each item is a dictionary where the answer is contained within 'text' — and the starting position of this answer within the context is also provided in 'answer_start'.
This is okay, but we need to train our model to find the start and end of our answer within the context — so we need to add an 'answer_end' value too:
This gives us:
Our data is almost ready; we just need to convert our strings into tokens — and then translate our answer_start and answer_end indices from character-position to token-position.
Tokenization is easily done using a built-in HuggingFace tokenizer like so:
Our context-question pairs are now represented as Encoding objects. These objects merge each corresponding context and question strings to create the Q&A format expected by BERT — which is simply both context and question concatenated but separated with a [SEP] token:
This concatenated version is stored within the input_ids attribute of our Encoding object. But, rather than the human-readable text — the data is stored as BERT-readable token IDs.
The tokenizer is great, but it doesn’t produce our answer start-end token positions. For that, we define a custom add_token_positions function:
This function adds two more attributes to our Encoding objects — start_positions and end_positions. Each of these is simply a list containing the start/end token positions of the answer that corresponds to their respective question-context pairs.
We’ve now prepared our data, and we have everything we need — we just need to transform it into the correct format for training with PyTorch.
For this, we need to build a dataset object, which we can do easily like so:
We will be able to feed these dataset objects into our model during training and validation.
Our data is now wholly ready for use by our model. All we do now is set up our PyTorch environment, initialize the DataLoader which we will be using to load data during training — and finally, begin fine-tuning our model:
DistilBert is a small model compared to most transformer models — but this will still take some time to train.
Once done, we can go ahead and save our newly fine-tuned model (and tokenizer if needed) — we will save it to a new directory models/distilbert-custom:
When loading our model again, we can use the same from_pretrained method that we use when loading models from HuggingFace — all we do is replace the online model path/name with our local path — in this case:
model_path = 'models/distilbert-custom'model = DistilBertForQuestionAnswering.from_pretrained(model_path)tokenizer = DistilBertTokenizerFast.from_pretrained(model_path)
Or using the generic AutoModel loader:
model = AutoModel.from_pretrained(model_path)tokenizer = AutoTokenizer.from_pretrained(model_path)
Once we have trained our model, we can begin making predictions and asking our model a few questions.
Bear in mind here that we are already using a highly optimized base model — which gets us halfway there — but we could still benefit from experimenting with different models.
But for now, we just need to learn this approach — and how to apply it to our own more specific use-cases. So let’s learn what to do post-training.
To extract the start-end token range from our model, we can access the start_logits and end_logits tensors and perform an argmax function like so:
start_pred = torch.argmax(outputs['start_logits'], dim=1)end_pred = torch.argmax(outputs['end_logits'], dim=1)
The simplest metric we can measure here is accuracy — more specifically known as exact match (EM) — did the model get the right start or end token, or not? Of course, this doesn’t factor in models that are getting close and maybe missing by one or two tokens — but it’s a start.
To calculate the EM of each batch, we take the sum of the number of matches per batch — and divide by the total. We do this with PyTorch like so:
acc = ( (start_pred == start_true).sum() / len(start_pred) ).item()
The final .item() extracts the tensor value as a plain and simple Python int.
Now we know how to calculate our Q&A accuracy — let’s implement it for our val_dataset!
Once again, we set up a DataLoader — and then loop through each batch. This time though, we call model.eval() to switch the behavior of relevant layers from training to inference mode — and use torch.no_grad() to stop PyTorch from calculating model gradients (only needed during training):
After all of that, we have an — albeit rough — measure of accuracy.
63.6% of the time, the model manages to get the exact span (start and/or end) of our answer correct. 63.6% is certainly not a particularly impressive number until we look a little deeper into how the model performs.
The EM metric doesn’t paint a full picture — despite scoring an EM of just 18.75% in the last batch — the model did get incredibly close in 4/8 of the questions, which is not reflected in the EM score.
Nonetheless, when measuring and comparing models — EM is the perfect place to start.
That’s all for this walk-through! We’ve taken a pre-trained DistilBert model, fitted it with a Q&A head — and fine-tuned it using the SQuAD dataset. Producing our very own Q&A model.
However, more importantly, we have introduced the process of taking a Q&A dataset — and used it to ‘fine-tune’ a pre-trained transformer model.
Learning and understanding this process is very important and, when applied correctly, can push Q&A model performance on specific use-cases much higher.
You most likely won’t be using the SQuAD dataset for any fine-tuning — instead, you will be using your own data, or an open-source Q&A dataset:
NewsQA — 120K CNN news articles
FigureQA — Chart-based Q&A
FiQA — Financial opinion Q&A from Reddit
CommonSenseQA — Good luck with this one 😄
There are already a tremendous number of datasets available — and more are made available frequently — so there’s plenty to learn from!
I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too.
Thanks for reading!
Fine-tuning with custom datasets, HuggingFace’s Transformers Docs
🤖 NLP With Transformers Course
Full Article Code
*All images are by the author except where stated otherwise | [
{
"code": null,
"e": 308,
"s": 172,
"text": "Transformer models are undoubtedly the leaders in NLP — outperforming almost every other model architecture in almost every other task."
},
{
"code": null,
"e": 459,
"s": 308,
"text": "One of the most fascinating language-based tasks that transformers have proven themselves more than capable of dealing with is question-and-answering."
},
{
"code": null,
"e": 653,
"s": 459,
"text": "In this article, we will learn about the field of Q&A in NLP — and learn how to download and fine-tune some of the most advanced transformer models in the world for this very purpose. In short:"
},
{
"code": null,
"e": 823,
"s": 653,
"text": "> Our Dataset - Downloading SQuAD> Preparing The Data - Extraction - Encoding - Initializing the Dataset> Fine-Tuning> Measuring Performance - Implementing Accuracy"
},
{
"code": null,
"e": 874,
"s": 823,
"text": "If you prefer video — I cover everything here too:"
},
{
"code": null,
"e": 1075,
"s": 874,
"text": "For our example, we will use the Stanford Question Answering Dataset (SQuAD) 2.0. Our model will be expected to correctly select the specific part of a text segment that answers a question we provide."
},
{
"code": null,
"e": 1119,
"s": 1075,
"text": "We can download the data in Python like so:"
},
{
"code": null,
"e": 1244,
"s": 1119,
"text": "Which will return two files, our training data train-v2.0.json — and our validation data dev-v2.0.json. Both look like this:"
},
{
"code": null,
"e": 1297,
"s": 1244,
"text": "Here we have three key parts in our data, which are:"
},
{
"code": null,
"e": 1369,
"s": 1297,
"text": "Questions — strings containing the question which we will ask our model"
},
{
"code": null,
"e": 1458,
"s": 1369,
"text": "Contexts — larger segments of text that contain the answers to our questions within them"
},
{
"code": null,
"e": 1567,
"s": 1458,
"text": "Answers — shorter strings which are ‘extracts’ of the given contexts that provide an answer to our questions"
},
{
"code": null,
"e": 1742,
"s": 1567,
"text": "So, we will provide the model with a question and corresponding answer. The model must then read both and return the token positions of the predicted answer from the context."
},
{
"code": null,
"e": 1926,
"s": 1742,
"text": "The first step in preparing this data for fine-tuning is extracting our questions, contexts, and answers from the JSON files into training and validation sets. We can do this like so:"
},
{
"code": null,
"e": 1991,
"s": 1926,
"text": "This gives us our two datasets split between three lists (each):"
},
{
"code": null,
"e": 2132,
"s": 1991,
"text": "Our contexts and questions are simple strings — each corresponds to each other. The answer to each question can be found within the context."
},
{
"code": null,
"e": 2349,
"s": 2132,
"text": "The answers lists are slightly different in that each item is a dictionary where the answer is contained within 'text' — and the starting position of this answer within the context is also provided in 'answer_start'."
},
{
"code": null,
"e": 2500,
"s": 2349,
"text": "This is okay, but we need to train our model to find the start and end of our answer within the context — so we need to add an 'answer_end' value too:"
},
{
"code": null,
"e": 2515,
"s": 2500,
"text": "This gives us:"
},
{
"code": null,
"e": 2693,
"s": 2515,
"text": "Our data is almost ready; we just need to convert our strings into tokens — and then translate our answer_start and answer_end indices from character-position to token-position."
},
{
"code": null,
"e": 2769,
"s": 2693,
"text": "Tokenization is easily done using a built-in HuggingFace tokenizer like so:"
},
{
"code": null,
"e": 3038,
"s": 2769,
"text": "Our context-question pairs are now represented as Encoding objects. These objects merge each corresponding context and question strings to create the Q&A format expected by BERT — which is simply both context and question concatenated but separated with a [SEP] token:"
},
{
"code": null,
"e": 3219,
"s": 3038,
"text": "This concatenated version is stored within the input_ids attribute of our Encoding object. But, rather than the human-readable text — the data is stored as BERT-readable token IDs."
},
{
"code": null,
"e": 3363,
"s": 3219,
"text": "The tokenizer is great, but it doesn’t produce our answer start-end token positions. For that, we define a custom add_token_positions function:"
},
{
"code": null,
"e": 3610,
"s": 3363,
"text": "This function adds two more attributes to our Encoding objects — start_positions and end_positions. Each of these is simply a list containing the start/end token positions of the answer that corresponds to their respective question-context pairs."
},
{
"code": null,
"e": 3752,
"s": 3610,
"text": "We’ve now prepared our data, and we have everything we need — we just need to transform it into the correct format for training with PyTorch."
},
{
"code": null,
"e": 3829,
"s": 3752,
"text": "For this, we need to build a dataset object, which we can do easily like so:"
},
{
"code": null,
"e": 3922,
"s": 3829,
"text": "We will be able to feed these dataset objects into our model during training and validation."
},
{
"code": null,
"e": 4144,
"s": 3922,
"text": "Our data is now wholly ready for use by our model. All we do now is set up our PyTorch environment, initialize the DataLoader which we will be using to load data during training — and finally, begin fine-tuning our model:"
},
{
"code": null,
"e": 4255,
"s": 4144,
"text": "DistilBert is a small model compared to most transformer models — but this will still take some time to train."
},
{
"code": null,
"e": 4407,
"s": 4255,
"text": "Once done, we can go ahead and save our newly fine-tuned model (and tokenizer if needed) — we will save it to a new directory models/distilbert-custom:"
},
{
"code": null,
"e": 4615,
"s": 4407,
"text": "When loading our model again, we can use the same from_pretrained method that we use when loading models from HuggingFace — all we do is replace the online model path/name with our local path — in this case:"
},
{
"code": null,
"e": 4784,
"s": 4615,
"text": "model_path = 'models/distilbert-custom'model = DistilBertForQuestionAnswering.from_pretrained(model_path)tokenizer = DistilBertTokenizerFast.from_pretrained(model_path)"
},
{
"code": null,
"e": 4823,
"s": 4784,
"text": "Or using the generic AutoModel loader:"
},
{
"code": null,
"e": 4922,
"s": 4823,
"text": "model = AutoModel.from_pretrained(model_path)tokenizer = AutoTokenizer.from_pretrained(model_path)"
},
{
"code": null,
"e": 5024,
"s": 4922,
"text": "Once we have trained our model, we can begin making predictions and asking our model a few questions."
},
{
"code": null,
"e": 5199,
"s": 5024,
"text": "Bear in mind here that we are already using a highly optimized base model — which gets us halfway there — but we could still benefit from experimenting with different models."
},
{
"code": null,
"e": 5347,
"s": 5199,
"text": "But for now, we just need to learn this approach — and how to apply it to our own more specific use-cases. So let’s learn what to do post-training."
},
{
"code": null,
"e": 5494,
"s": 5347,
"text": "To extract the start-end token range from our model, we can access the start_logits and end_logits tensors and perform an argmax function like so:"
},
{
"code": null,
"e": 5605,
"s": 5494,
"text": "start_pred = torch.argmax(outputs['start_logits'], dim=1)end_pred = torch.argmax(outputs['end_logits'], dim=1)"
},
{
"code": null,
"e": 5884,
"s": 5605,
"text": "The simplest metric we can measure here is accuracy — more specifically known as exact match (EM) — did the model get the right start or end token, or not? Of course, this doesn’t factor in models that are getting close and maybe missing by one or two tokens — but it’s a start."
},
{
"code": null,
"e": 6030,
"s": 5884,
"text": "To calculate the EM of each batch, we take the sum of the number of matches per batch — and divide by the total. We do this with PyTorch like so:"
},
{
"code": null,
"e": 6098,
"s": 6030,
"text": "acc = ( (start_pred == start_true).sum() / len(start_pred) ).item()"
},
{
"code": null,
"e": 6176,
"s": 6098,
"text": "The final .item() extracts the tensor value as a plain and simple Python int."
},
{
"code": null,
"e": 6264,
"s": 6176,
"text": "Now we know how to calculate our Q&A accuracy — let’s implement it for our val_dataset!"
},
{
"code": null,
"e": 6554,
"s": 6264,
"text": "Once again, we set up a DataLoader — and then loop through each batch. This time though, we call model.eval() to switch the behavior of relevant layers from training to inference mode — and use torch.no_grad() to stop PyTorch from calculating model gradients (only needed during training):"
},
{
"code": null,
"e": 6622,
"s": 6554,
"text": "After all of that, we have an — albeit rough — measure of accuracy."
},
{
"code": null,
"e": 6838,
"s": 6622,
"text": "63.6% of the time, the model manages to get the exact span (start and/or end) of our answer correct. 63.6% is certainly not a particularly impressive number until we look a little deeper into how the model performs."
},
{
"code": null,
"e": 7040,
"s": 6838,
"text": "The EM metric doesn’t paint a full picture — despite scoring an EM of just 18.75% in the last batch — the model did get incredibly close in 4/8 of the questions, which is not reflected in the EM score."
},
{
"code": null,
"e": 7125,
"s": 7040,
"text": "Nonetheless, when measuring and comparing models — EM is the perfect place to start."
},
{
"code": null,
"e": 7308,
"s": 7125,
"text": "That’s all for this walk-through! We’ve taken a pre-trained DistilBert model, fitted it with a Q&A head — and fine-tuned it using the SQuAD dataset. Producing our very own Q&A model."
},
{
"code": null,
"e": 7452,
"s": 7308,
"text": "However, more importantly, we have introduced the process of taking a Q&A dataset — and used it to ‘fine-tune’ a pre-trained transformer model."
},
{
"code": null,
"e": 7605,
"s": 7452,
"text": "Learning and understanding this process is very important and, when applied correctly, can push Q&A model performance on specific use-cases much higher."
},
{
"code": null,
"e": 7749,
"s": 7605,
"text": "You most likely won’t be using the SQuAD dataset for any fine-tuning — instead, you will be using your own data, or an open-source Q&A dataset:"
},
{
"code": null,
"e": 7781,
"s": 7749,
"text": "NewsQA — 120K CNN news articles"
},
{
"code": null,
"e": 7808,
"s": 7781,
"text": "FigureQA — Chart-based Q&A"
},
{
"code": null,
"e": 7849,
"s": 7808,
"text": "FiQA — Financial opinion Q&A from Reddit"
},
{
"code": null,
"e": 7891,
"s": 7849,
"text": "CommonSenseQA — Good luck with this one 😄"
},
{
"code": null,
"e": 8027,
"s": 7891,
"text": "There are already a tremendous number of datasets available — and more are made available frequently — so there’s plenty to learn from!"
},
{
"code": null,
"e": 8198,
"s": 8027,
"text": "I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too."
},
{
"code": null,
"e": 8218,
"s": 8198,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 8284,
"s": 8218,
"text": "Fine-tuning with custom datasets, HuggingFace’s Transformers Docs"
},
{
"code": null,
"e": 8315,
"s": 8284,
"text": "🤖 NLP With Transformers Course"
},
{
"code": null,
"e": 8333,
"s": 8315,
"text": "Full Article Code"
}
] |
Program to find number of tasks can be finished with given conditions in Python | Suppose we have a list of tasks and another list of people. The tasks[i] determines the amount of strength required to perform the ith task. And the people[i] determines the amount of strength the ith person has. Finally, we have to find the number of tasks that can be finished if one person can perform at most one task.
So, if the input is like tasks = [4, 3, 9, 15], people = [10, 5, 3, 2], then the output will be 3, as the first person can perform task 9, second person can perform task 4, third person can perform task 3, and fourth person can't perform any tasks.
To solve this, we will follow these steps −
sort the list tasks, sort the list people
ct:= 0, ind:= 0
for i in range 0 to size of people, dofor j in range ind to size of tasks, doif people[i] >= tasks[j], thenct := ct + 1ind := ind + 1come out from the loopotherwise,come out from the loop
for j in range ind to size of tasks, doif people[i] >= tasks[j], thenct := ct + 1ind := ind + 1come out from the loopotherwise,come out from the loop
if people[i] >= tasks[j], thenct := ct + 1ind := ind + 1come out from the loop
ct := ct + 1
ind := ind + 1
come out from the loop
otherwise,come out from the loop
come out from the loop
return ct
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, tasks, people): tasks.sort()
people.sort()
ct=0
ind=0
for i in range(len(people)):
for j in range(ind,len(tasks)):
if people[i]>=tasks[j]:
ct+=1
ind+=1
break
else:
break
return ct
ob = Solution()
tasks = [4, 3, 9, 15]
people = [10, 5, 3, 2] print(ob.solve(tasks, people))
[4, 3, 9, 15], [10, 5, 3, 2]
3 | [
{
"code": null,
"e": 1385,
"s": 1062,
"text": "Suppose we have a list of tasks and another list of people. The tasks[i] determines the amount of strength required to perform the ith task. And the people[i] determines the amount of strength the ith person has. Finally, we have to find the number of tasks that can be finished if one person can perform at most one task."
},
{
"code": null,
"e": 1634,
"s": 1385,
"text": "So, if the input is like tasks = [4, 3, 9, 15], people = [10, 5, 3, 2], then the output will be 3, as the first person can perform task 9, second person can perform task 4, third person can perform task 3, and fourth person can't perform any tasks."
},
{
"code": null,
"e": 1678,
"s": 1634,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1720,
"s": 1678,
"text": "sort the list tasks, sort the list people"
},
{
"code": null,
"e": 1736,
"s": 1720,
"text": "ct:= 0, ind:= 0"
},
{
"code": null,
"e": 1924,
"s": 1736,
"text": "for i in range 0 to size of people, dofor j in range ind to size of tasks, doif people[i] >= tasks[j], thenct := ct + 1ind := ind + 1come out from the loopotherwise,come out from the loop"
},
{
"code": null,
"e": 2074,
"s": 1924,
"text": "for j in range ind to size of tasks, doif people[i] >= tasks[j], thenct := ct + 1ind := ind + 1come out from the loopotherwise,come out from the loop"
},
{
"code": null,
"e": 2153,
"s": 2074,
"text": "if people[i] >= tasks[j], thenct := ct + 1ind := ind + 1come out from the loop"
},
{
"code": null,
"e": 2166,
"s": 2153,
"text": "ct := ct + 1"
},
{
"code": null,
"e": 2181,
"s": 2166,
"text": "ind := ind + 1"
},
{
"code": null,
"e": 2204,
"s": 2181,
"text": "come out from the loop"
},
{
"code": null,
"e": 2237,
"s": 2204,
"text": "otherwise,come out from the loop"
},
{
"code": null,
"e": 2260,
"s": 2237,
"text": "come out from the loop"
},
{
"code": null,
"e": 2270,
"s": 2260,
"text": "return ct"
},
{
"code": null,
"e": 2340,
"s": 2270,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2351,
"s": 2340,
"text": " Live Demo"
},
{
"code": null,
"e": 2784,
"s": 2351,
"text": "class Solution:\n def solve(self, tasks, people): tasks.sort()\n people.sort()\n ct=0\n ind=0\n for i in range(len(people)):\n for j in range(ind,len(tasks)):\n if people[i]>=tasks[j]:\n ct+=1\n ind+=1\n break\n else:\n break\n return ct\nob = Solution()\ntasks = [4, 3, 9, 15]\npeople = [10, 5, 3, 2] print(ob.solve(tasks, people))"
},
{
"code": null,
"e": 2813,
"s": 2784,
"text": "[4, 3, 9, 15], [10, 5, 3, 2]"
},
{
"code": null,
"e": 2815,
"s": 2813,
"text": "3"
}
] |
Basics of Numbers in Dart - GeeksforGeeks | 14 Jul, 2020
Like other languages, Dart Programming also supports numerical values as Number objects. The number in Dart Programming is the data type that is used to hold the numeric value. Dart numbers can be classified as:
int: The int data type is used to represent whole numbers.
Syntax: int var_name;
double: The double data type is used to represent 64-bit floating-point numbers.
Syntax: double var_name;
Example 1:
Dart
void main() { // declare an integer int num1 = 2; // declare a double value double num2 = 1.5; // print the values print(num1); print(num2);}
Output:
2
1.5
Note: The num type is an inherited data type of the int and double types.
Parsing in Dart: The parse() function is used parsing a string containing numeric literal and convert to the number.
Example 2:
Dart
void main(){ var a1 = num.parse("1"); var b1 = num.parse("2.34"); var c1 = a1+b1; print("Product = ${c1}"); }
Output:
Product = 3.34
Properties:
hashcode: This property is used to get the hash code of the given number.
isFinite: If the given number is finite, then this property will return true.
isInfinite: If the number is infinite, then this property will return true.
isNan: If the number is non-negative then this property will return true.
isNegative: If the number is negative then this property will return true.
sign: This property is used to get -1, 0, or 1 depending upon the sign of the given number.
isEven: If the given number is an even then this property will return true.
isOdd: If the given number is odd then this property will return true.
Methods:
abs(): This method gives the absolute value of the given number.
ceil(): This method gives the ceiling value of the given number.
floor(): This method gives the floor value of the given number.
compareTo(): This method compares the value with other numbers.
remainder(): This method gives the truncated remainder after dividing the two numbers.
round(): This method returns the round of the number.
toDouble(): This method gives the double equivalent representation of the number.
toInt(): This method returns the integer equivalent representation of the number.
toString(): This method returns the String equivalent representation of the number
truncate(): This method returns the integer after discarding fraction digits.
Dart-basics
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Flutter - Flexible Widget
ListView Class in Flutter
Flutter - Stack Widget
Android Studio Setup for Flutter Development
Format Dates in Flutter
Flutter - Positioned Widget
Simple Calculator App using Flutter
Flutter - Dialogs
Flutter - Managing the MediaQuery Object | [
{
"code": null,
"e": 23643,
"s": 23615,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 23857,
"s": 23643,
"text": "Like other languages, Dart Programming also supports numerical values as Number objects. The number in Dart Programming is the data type that is used to hold the numeric value. Dart numbers can be classified as: "
},
{
"code": null,
"e": 23916,
"s": 23857,
"text": "int: The int data type is used to represent whole numbers."
},
{
"code": null,
"e": 23938,
"s": 23916,
"text": "Syntax: int var_name;"
},
{
"code": null,
"e": 24019,
"s": 23938,
"text": "double: The double data type is used to represent 64-bit floating-point numbers."
},
{
"code": null,
"e": 24044,
"s": 24019,
"text": "Syntax: double var_name;"
},
{
"code": null,
"e": 24057,
"s": 24044,
"text": "Example 1: "
},
{
"code": null,
"e": 24062,
"s": 24057,
"text": "Dart"
},
{
"code": "void main() { // declare an integer int num1 = 2; // declare a double value double num2 = 1.5; // print the values print(num1); print(num2);}",
"e": 24246,
"s": 24062,
"text": null
},
{
"code": null,
"e": 24255,
"s": 24246,
"text": "Output: "
},
{
"code": null,
"e": 24262,
"s": 24255,
"text": "2\n1.5\n"
},
{
"code": null,
"e": 24336,
"s": 24262,
"text": "Note: The num type is an inherited data type of the int and double types."
},
{
"code": null,
"e": 24455,
"s": 24336,
"text": "Parsing in Dart: The parse() function is used parsing a string containing numeric literal and convert to the number. "
},
{
"code": null,
"e": 24468,
"s": 24455,
"text": "Example 2: "
},
{
"code": null,
"e": 24473,
"s": 24468,
"text": "Dart"
},
{
"code": "void main(){ var a1 = num.parse(\"1\"); var b1 = num.parse(\"2.34\"); var c1 = a1+b1; print(\"Product = ${c1}\"); } ",
"e": 24603,
"s": 24473,
"text": null
},
{
"code": null,
"e": 24612,
"s": 24603,
"text": "Output: "
},
{
"code": null,
"e": 24628,
"s": 24612,
"text": "Product = 3.34\n"
},
{
"code": null,
"e": 24641,
"s": 24628,
"text": "Properties: "
},
{
"code": null,
"e": 24715,
"s": 24641,
"text": "hashcode: This property is used to get the hash code of the given number."
},
{
"code": null,
"e": 24793,
"s": 24715,
"text": "isFinite: If the given number is finite, then this property will return true."
},
{
"code": null,
"e": 24869,
"s": 24793,
"text": "isInfinite: If the number is infinite, then this property will return true."
},
{
"code": null,
"e": 24943,
"s": 24869,
"text": "isNan: If the number is non-negative then this property will return true."
},
{
"code": null,
"e": 25018,
"s": 24943,
"text": "isNegative: If the number is negative then this property will return true."
},
{
"code": null,
"e": 25110,
"s": 25018,
"text": "sign: This property is used to get -1, 0, or 1 depending upon the sign of the given number."
},
{
"code": null,
"e": 25186,
"s": 25110,
"text": "isEven: If the given number is an even then this property will return true."
},
{
"code": null,
"e": 25257,
"s": 25186,
"text": "isOdd: If the given number is odd then this property will return true."
},
{
"code": null,
"e": 25267,
"s": 25257,
"text": "Methods: "
},
{
"code": null,
"e": 25332,
"s": 25267,
"text": "abs(): This method gives the absolute value of the given number."
},
{
"code": null,
"e": 25397,
"s": 25332,
"text": "ceil(): This method gives the ceiling value of the given number."
},
{
"code": null,
"e": 25461,
"s": 25397,
"text": "floor(): This method gives the floor value of the given number."
},
{
"code": null,
"e": 25525,
"s": 25461,
"text": "compareTo(): This method compares the value with other numbers."
},
{
"code": null,
"e": 25612,
"s": 25525,
"text": "remainder(): This method gives the truncated remainder after dividing the two numbers."
},
{
"code": null,
"e": 25666,
"s": 25612,
"text": "round(): This method returns the round of the number."
},
{
"code": null,
"e": 25748,
"s": 25666,
"text": "toDouble(): This method gives the double equivalent representation of the number."
},
{
"code": null,
"e": 25830,
"s": 25748,
"text": "toInt(): This method returns the integer equivalent representation of the number."
},
{
"code": null,
"e": 25913,
"s": 25830,
"text": "toString(): This method returns the String equivalent representation of the number"
},
{
"code": null,
"e": 25991,
"s": 25913,
"text": "truncate(): This method returns the integer after discarding fraction digits."
},
{
"code": null,
"e": 26003,
"s": 25991,
"text": "Dart-basics"
},
{
"code": null,
"e": 26008,
"s": 26003,
"text": "Dart"
},
{
"code": null,
"e": 26106,
"s": 26008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26115,
"s": 26106,
"text": "Comments"
},
{
"code": null,
"e": 26128,
"s": 26115,
"text": "Old Comments"
},
{
"code": null,
"e": 26167,
"s": 26128,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 26193,
"s": 26167,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 26219,
"s": 26193,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 26242,
"s": 26219,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 26287,
"s": 26242,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 26311,
"s": 26287,
"text": "Format Dates in Flutter"
},
{
"code": null,
"e": 26339,
"s": 26311,
"text": "Flutter - Positioned Widget"
},
{
"code": null,
"e": 26375,
"s": 26339,
"text": "Simple Calculator App using Flutter"
},
{
"code": null,
"e": 26393,
"s": 26375,
"text": "Flutter - Dialogs"
}
] |
Introduction to Java - GeeksforGeeks | 09 Apr, 2022
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later acquired by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++.
Java’s history is very interesting. It is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green team initiated the Java language in 1991. Sun Microsystems released its first public implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms. Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its specifications. With the arrival of Java 2, new versions had multiple configurations built for different types of platforms.
In 1997, Sun Microsystems approached the ISO standards body and later formalized Java, but it soon withdrew from the process. At one time, Sun made most of its Java implementations available without charge, despite their proprietary software status. Sun generated revenue from Java through the selling of licenses for specialized products such as the Java Enterprise System.
On November 13, 2006, Sun released much of its Java virtual machine as free, open-source software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code available under open-source distribution terms.
The principles for creating java were simple, robust, secured, high performance, portable, multi-threaded, interpreted, dynamic, etc. In 1995 Java was developed by James Gosling, who is known as the Father of Java. Currently, Java is used in mobile devices, internet programming, games, e-business, etc.
After the name OAK, the team decided to give a new name to it and the suggested words were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all names were easy to spell and fun to say, but they all wanted the name to reflect the essence of technology. In accordance with James Gosling, Java the among the top names along with Silk, and since java was a unique name so most of them preferred it.
Java is the name of an island in Indonesia where the first coffee(named java coffee) was produced. And this name was chosen by James Gosling while having coffee near his office. Note that Java is just a name, not an acronym.
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution phases of a program. They are written, compile and run the program.
Writing a program is done by a java programmer like you and me.
The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java development kit (JDK). It takes the Java program as input and generates bytecode as output.
In the Running phase of a program, JVM executes the bytecode generated by the compiler.
Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced by the compiler. Every Operating System has a different JVM but the output they produce after the execution of bytecode is the same across all the operating systems. This is why Java is known as a platform-independent language.
2. Bytecode in the Development process: As discussed, the Javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the bytecode, a disassembler like javap can be used.
3. Java Development Kit(JDK): While we were using the term JDK when we learn about bytecode and JVM. So, as the name suggests, it is a complete Java development kit that includes everything including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program to execute in java, we need to install JDK on our computer in order to create, compile and run the java program.
4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the java program to run, however, we cannot compile it. JRE includes a browser, JVM, applet supports, and plugins. For running the java program, a computer needs JRE.
5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a program called Garbage Collector. Garbage Collectors can recollect the objects that are not referenced. So Java makes the life of a programmer easy by handling memory management. However, programmers should be careful about their code whether they are using objects that have been used for a long time. Because Garbage cannot recover the memory of objects being referenced.
6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for .class files to load. By default, JDK provides many libraries. If you want to include external libraries they should be added to the classpath.
1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode generated by the compiler. This bytecode can run on any platform be it Windows, Linux, macOS which means if we compile a program on Windows, then we can run it on Linux and vice versa. Each operating system has a different JVM, but the output produced by all the OS is the same after the execution of bytecode. That is why we call java a platform-independent language.
2. Object-Oriented Programming Language: Organizing the program in the terms of collection of objects is a way of object-oriented programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator overloading, multiple inheritances, Explicit memory allocation.
4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not easy to detect by another programming language. The main features of java that make it robust are garbage collection, Exception Handling, and memory allocation.
5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack corruption or buffer overflow are impossible to exploit in Java.
6. Distributed: We can create distributed applications using the java programming language. Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily distributed on one or more systems that are connected to each other through an internet connection.
7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU.
8. Portable: As we know, java code written on one machine can be run on another machine. The platform-independent feature of java in which its platform-independent bytecode can be taken to any platform for execution makes java portable.
9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and at some time java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basics where it only compiles those methods that are called making applications to execute faster.
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new methods to existing classes and even create new classes through sub-classes. Java even supports functions written in other languages such as C, C++ which are referred to as native methods.
11. Sandbox Execution: Java programs run in a separate space that allows user to execute their applications without affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides additional security as its role is to check the code for any violation of access.
12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file which corresponds to our applications(program) but contains code in binary format. It provides ease t architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the primary reason java is used in the enterprising IT industry globally worldwide.
13. Power of compilation and interpretation: Most languages are designed with purpose either they are compiled language or they are interpreted language. But java integrates arising enormous power as Java compiler compiles the source code to bytecode and JVM executes this bytecode to machine OS-dependent executable code.
Example
Java
// Demo Java program // Importing classes from packagesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println("Welcome to GeeksforGeeks"); }}
Welcone to GeeksforGeeks
Explanation:
1. Comments: Comments are used for explaining code and are used in a similar manner in Java or C or C++. Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple lines.
Single line Comments:Syntax:
// Single line comment
Multi-line comments:Syntax:
/* Multi line comments*/
2. import java.io.*: This means all the classes of io package can be imported. Java io package provides a set of input and output streams for reading and writing data to files or other input or output sources.
3. class: The class contains the data and methods to be used in the program. Methods define the behavior of the class. Class GFG has only one method Main in JAVA.
4. static void Main(): static keyword tells us that this method is accessible without instantiating the class.
5. void: keywords tell that this method will not return anything. The main() method is the entry point of our application.
6. System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device.
7. System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen.
8. println(): This method in Java is also used to display text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line.
Everything in java , is represented in Class as an object including the main function.
abhinavsiwach501
solankimayank
s4shibam
shivampurena44
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split() String method in Java with examples
Reverse a string in Java
Arrays.sort() in Java with examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
How to add an element to an Array in Java?
Stream In Java
Initializing a List in Java
Different ways of Reading a text file in Java | [
{
"code": null,
"e": 28559,
"s": 28531,
"text": "\n09 Apr, 2022"
},
{
"code": null,
"e": 28830,
"s": 28559,
"text": "JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later acquired by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs."
},
{
"code": null,
"e": 29245,
"s": 28830,
"text": "Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++."
},
{
"code": null,
"e": 29808,
"s": 29245,
"text": "Java’s history is very interesting. It is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green team initiated the Java language in 1991. Sun Microsystems released its first public implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms. Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its specifications. With the arrival of Java 2, new versions had multiple configurations built for different types of platforms."
},
{
"code": null,
"e": 30183,
"s": 29808,
"text": "In 1997, Sun Microsystems approached the ISO standards body and later formalized Java, but it soon withdrew from the process. At one time, Sun made most of its Java implementations available without charge, despite their proprietary software status. Sun generated revenue from Java through the selling of licenses for specialized products such as the Java Enterprise System."
},
{
"code": null,
"e": 30406,
"s": 30183,
"text": "On November 13, 2006, Sun released much of its Java virtual machine as free, open-source software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code available under open-source distribution terms."
},
{
"code": null,
"e": 30710,
"s": 30406,
"text": "The principles for creating java were simple, robust, secured, high performance, portable, multi-threaded, interpreted, dynamic, etc. In 1995 Java was developed by James Gosling, who is known as the Father of Java. Currently, Java is used in mobile devices, internet programming, games, e-business, etc."
},
{
"code": null,
"e": 31108,
"s": 30710,
"text": "After the name OAK, the team decided to give a new name to it and the suggested words were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all names were easy to spell and fun to say, but they all wanted the name to reflect the essence of technology. In accordance with James Gosling, Java the among the top names along with Silk, and since java was a unique name so most of them preferred it."
},
{
"code": null,
"e": 31333,
"s": 31108,
"text": "Java is the name of an island in Indonesia where the first coffee(named java coffee) was produced. And this name was chosen by James Gosling while having coffee near his office. Note that Java is just a name, not an acronym."
},
{
"code": null,
"e": 31409,
"s": 31333,
"text": "Before learning Java, one must be familiar with these common terms of Java."
},
{
"code": null,
"e": 31573,
"s": 31409,
"text": "1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution phases of a program. They are written, compile and run the program."
},
{
"code": null,
"e": 31637,
"s": 31573,
"text": "Writing a program is done by a java programmer like you and me."
},
{
"code": null,
"e": 31829,
"s": 31637,
"text": "The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java development kit (JDK). It takes the Java program as input and generates bytecode as output."
},
{
"code": null,
"e": 31917,
"s": 31829,
"text": "In the Running phase of a program, JVM executes the bytecode generated by the compiler."
},
{
"code": null,
"e": 32242,
"s": 31917,
"text": "Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced by the compiler. Every Operating System has a different JVM but the output they produce after the execution of bytecode is the same across all the operating systems. This is why Java is known as a platform-independent language."
},
{
"code": null,
"e": 32507,
"s": 32242,
"text": "2. Bytecode in the Development process: As discussed, the Javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the bytecode, a disassembler like javap can be used."
},
{
"code": null,
"e": 32910,
"s": 32507,
"text": "3. Java Development Kit(JDK): While we were using the term JDK when we learn about bytecode and JVM. So, as the name suggests, it is a complete Java development kit that includes everything including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program to execute in java, we need to install JDK on our computer in order to create, compile and run the java program."
},
{
"code": null,
"e": 33171,
"s": 32910,
"text": "4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the java program to run, however, we cannot compile it. JRE includes a browser, JVM, applet supports, and plugins. For running the java program, a computer needs JRE."
},
{
"code": null,
"e": 33659,
"s": 33171,
"text": "5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a program called Garbage Collector. Garbage Collectors can recollect the objects that are not referenced. So Java makes the life of a programmer easy by handling memory management. However, programmers should be careful about their code whether they are using objects that have been used for a long time. Because Garbage cannot recover the memory of objects being referenced."
},
{
"code": null,
"e": 33898,
"s": 33659,
"text": "6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for .class files to load. By default, JDK provides many libraries. If you want to include external libraries they should be added to the classpath."
},
{
"code": null,
"e": 34374,
"s": 33898,
"text": "1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode generated by the compiler. This bytecode can run on any platform be it Windows, Linux, macOS which means if we compile a program on Windows, then we can run it on Linux and vice versa. Each operating system has a different JVM, but the output produced by all the OS is the same after the execution of bytecode. That is why we call java a platform-independent language."
},
{
"code": null,
"e": 34569,
"s": 34374,
"text": "2. Object-Oriented Programming Language: Organizing the program in the terms of collection of objects is a way of object-oriented programming, each of which represents an instance of the class."
},
{
"code": null,
"e": 34628,
"s": 34569,
"text": "The four main concepts of Object-Oriented programming are:"
},
{
"code": null,
"e": 34640,
"s": 34628,
"text": "Abstraction"
},
{
"code": null,
"e": 34654,
"s": 34640,
"text": "Encapsulation"
},
{
"code": null,
"e": 34666,
"s": 34654,
"text": "Inheritance"
},
{
"code": null,
"e": 34679,
"s": 34666,
"text": "Polymorphism"
},
{
"code": null,
"e": 34853,
"s": 34679,
"text": "3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator overloading, multiple inheritances, Explicit memory allocation. "
},
{
"code": null,
"e": 35253,
"s": 34853,
"text": "4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not easy to detect by another programming language. The main features of java that make it robust are garbage collection, Exception Handling, and memory allocation."
},
{
"code": null,
"e": 35518,
"s": 35253,
"text": "5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack corruption or buffer overflow are impossible to exploit in Java. "
},
{
"code": null,
"e": 35850,
"s": 35518,
"text": "6. Distributed: We can create distributed applications using the java programming language. Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java programs can be easily distributed on one or more systems that are connected to each other through an internet connection."
},
{
"code": null,
"e": 36020,
"s": 35850,
"text": "7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU."
},
{
"code": null,
"e": 36258,
"s": 36020,
"text": "8. Portable: As we know, java code written on one machine can be run on another machine. The platform-independent feature of java in which its platform-independent bytecode can be taken to any platform for execution makes java portable."
},
{
"code": null,
"e": 36563,
"s": 36258,
"text": "9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and at some time java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basics where it only compiles those methods that are called making applications to execute faster."
},
{
"code": null,
"e": 36861,
"s": 36563,
"text": "10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new methods to existing classes and even create new classes through sub-classes. Java even supports functions written in other languages such as C, C++ which are referred to as native methods."
},
{
"code": null,
"e": 37157,
"s": 36861,
"text": "11. Sandbox Execution: Java programs run in a separate space that allows user to execute their applications without affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides additional security as its role is to check the code for any violation of access."
},
{
"code": null,
"e": 37524,
"s": 37157,
"text": "12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file which corresponds to our applications(program) but contains code in binary format. It provides ease t architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the primary reason java is used in the enterprising IT industry globally worldwide."
},
{
"code": null,
"e": 37848,
"s": 37524,
"text": "13. Power of compilation and interpretation: Most languages are designed with purpose either they are compiled language or they are interpreted language. But java integrates arising enormous power as Java compiler compiles the source code to bytecode and JVM executes this bytecode to machine OS-dependent executable code."
},
{
"code": null,
"e": 37856,
"s": 37848,
"text": "Example"
},
{
"code": null,
"e": 37861,
"s": 37856,
"text": "Java"
},
{
"code": "// Demo Java program // Importing classes from packagesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println(\"Welcome to GeeksforGeeks\"); }}",
"e": 38127,
"s": 37861,
"text": null
},
{
"code": null,
"e": 38152,
"s": 38127,
"text": "Welcone to GeeksforGeeks"
},
{
"code": null,
"e": 38165,
"s": 38152,
"text": "Explanation:"
},
{
"code": null,
"e": 38385,
"s": 38165,
"text": "1. Comments: Comments are used for explaining code and are used in a similar manner in Java or C or C++. Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple lines."
},
{
"code": null,
"e": 38414,
"s": 38385,
"text": "Single line Comments:Syntax:"
},
{
"code": null,
"e": 38437,
"s": 38414,
"text": "// Single line comment"
},
{
"code": null,
"e": 38465,
"s": 38437,
"text": "Multi-line comments:Syntax:"
},
{
"code": null,
"e": 38490,
"s": 38465,
"text": "/* Multi line comments*/"
},
{
"code": null,
"e": 38701,
"s": 38490,
"text": "2. import java.io.*: This means all the classes of io package can be imported. Java io package provides a set of input and output streams for reading and writing data to files or other input or output sources."
},
{
"code": null,
"e": 38865,
"s": 38701,
"text": "3. class: The class contains the data and methods to be used in the program. Methods define the behavior of the class. Class GFG has only one method Main in JAVA."
},
{
"code": null,
"e": 38978,
"s": 38865,
"text": "4. static void Main(): static keyword tells us that this method is accessible without instantiating the class. "
},
{
"code": null,
"e": 39102,
"s": 38978,
"text": "5. void: keywords tell that this method will not return anything. The main() method is the entry point of our application."
},
{
"code": null,
"e": 39237,
"s": 39102,
"text": "6. System.in: This is the standard input stream that is used to read characters from the keyboard or any other standard input device."
},
{
"code": null,
"e": 39382,
"s": 39237,
"text": "7. System.out: This is the standard output stream that is used to produce the result of a program on an output device like the computer screen."
},
{
"code": null,
"e": 39613,
"s": 39382,
"text": "8. println(): This method in Java is also used to display text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line."
},
{
"code": null,
"e": 39700,
"s": 39613,
"text": "Everything in java , is represented in Class as an object including the main function."
},
{
"code": null,
"e": 39717,
"s": 39700,
"text": "abhinavsiwach501"
},
{
"code": null,
"e": 39731,
"s": 39717,
"text": "solankimayank"
},
{
"code": null,
"e": 39740,
"s": 39731,
"text": "s4shibam"
},
{
"code": null,
"e": 39755,
"s": 39740,
"text": "shivampurena44"
},
{
"code": null,
"e": 39767,
"s": 39755,
"text": "java-basics"
},
{
"code": null,
"e": 39772,
"s": 39767,
"text": "Java"
},
{
"code": null,
"e": 39777,
"s": 39772,
"text": "Java"
},
{
"code": null,
"e": 39875,
"s": 39777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39884,
"s": 39875,
"text": "Comments"
},
{
"code": null,
"e": 39897,
"s": 39884,
"text": "Old Comments"
},
{
"code": null,
"e": 39941,
"s": 39897,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 39966,
"s": 39941,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 40002,
"s": 39966,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 40033,
"s": 40002,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 40065,
"s": 40033,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 40089,
"s": 40065,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 40132,
"s": 40089,
"text": "How to add an element to an Array in Java?"
},
{
"code": null,
"e": 40147,
"s": 40132,
"text": "Stream In Java"
},
{
"code": null,
"e": 40175,
"s": 40147,
"text": "Initializing a List in Java"
}
] |
Combine values of two columns separated with hyphen in an R data frame. | To combine values of two columns separated with hyphen in an R data frame, we can
use apply function.
For Example, if we have a data frame called df that contains only two columns say X and
Y then we can combine the values in X and Y by using the below command given below −
df$X_Y<-apply(df,1,paste,collapse="-")
Consider the data frame given below −
Age<-sample(20:50,20)
Height<-sample(130:200,20)
df1<-data.frame(Age,Height)
df1
The following dataframe is created
Age Height
1 22 147
2 37 138
3 28 184
4 40 154
5 32 193
6 20 135
7 47 185
8 27 198
9 46 156
10 29 170
11 44 140
12 43 167
13 23 182
14 49 171
15 31 150
16 25 148
17 21 180
18 45 169
19 39 179
20 36 133
To combine the values of both columns in df1 separated with hyphen on the above
created data frame, add the following code to the above snippet −
Age<-sample(20:50,20)
Height<-sample(130:200,20)
df1<-data.frame(Age,Height)
df1$Age_Height<-apply(df1,1,paste,collapse="-")
df1
If you execute all the above given snippets as a single program, it generates the
following Output −
Age Height Age_Height
1 22 147 22-147
2 37 138 37-138
3 28 184 28-184
4 40 154 40-154
5 32 193 32-193
6 20 135 20-135
7 47 185 47-185
8 27 198 27-198
9 46 156 46-156
10 29 170 29-170
11 44 140 44-140
12 43 167 43-167
13 23 182 23-182
14 49 171 49-171
15 31 150 31-150
16 25 148 25-148
17 21 180 21-180
18 45 169 45-169
19 39 179 39-179
20 36 133 36-133
Following snippet creates a sample data frame −
Group<-sample(c("First","Second","Third"),20,replace=TRUE)
Rate<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Group,Rate)
df2
If you execute the above given snippet, it generates the following Output −
Group Rate
1 First 8
2 Second 4
3 First 5
4 Second 7
5 Second 4
6 Third 7
7 Second 9
8 Second 7
9 First 7
10 Second 3
11 First 10
12 Second 9
13 First 7
14 First 8
15 Second 1
16 Second 8
17 Second 5
18 Third 10
19 Second 4
20 First 5
To combine the values of both columns in df2 separated with hyphen on the above
created data frame, add the following code to the above snippet −
Group<-sample(c("First","Second","Third"),20,replace=TRUE)
Rate<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Group,Rate)
df2$Group_Rate<-apply(df2,1,paste,collapse="-")
df2
If you execute all the above given snippets as a single program, it generates the
following Output −
Group Rate Group_Rate
1 First 8 First- 8
2 Second 4 Second- 4
3 First 5 First- 5
4 Second 7 Second- 7
5 Second 4 Second- 4
6 Third 7 Third- 7
7 Second 9 Second- 9
8 Second 7 Second- 7
9 First 7 First- 7
10 Second 3 Second- 3
11 First 10 First-10
12 Second 9 Second- 9
13 First 7 First- 7
14 First 8 First- 8
15 Second 1 Second- 1
16 Second 8 Second- 8
17 Second 5 Second- 5
18 Third 10 Third- 10
19 Second 4 Second- 4
20 First 5 First- 5 | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To combine values of two columns separated with hyphen in an R data frame, we can\nuse apply function."
},
{
"code": null,
"e": 1337,
"s": 1164,
"text": "For Example, if we have a data frame called df that contains only two columns say X and\nY then we can combine the values in X and Y by using the below command given below −"
},
{
"code": null,
"e": 1376,
"s": 1337,
"text": "df$X_Y<-apply(df,1,paste,collapse=\"-\")"
},
{
"code": null,
"e": 1414,
"s": 1376,
"text": "Consider the data frame given below −"
},
{
"code": null,
"e": 1495,
"s": 1414,
"text": "Age<-sample(20:50,20)\nHeight<-sample(130:200,20)\ndf1<-data.frame(Age,Height)\ndf1"
},
{
"code": null,
"e": 1530,
"s": 1495,
"text": "The following dataframe is created"
},
{
"code": null,
"e": 1783,
"s": 1530,
"text": " Age Height\n1 22 147\n2 37 138\n3 28 184\n4 40 154\n5 32 193\n6 20 135\n7 47 185\n8 27 198\n9 46 156\n10 29 170\n11 44 140\n12 43 167\n13 23 182\n14 49 171\n15 31 150\n16 25 148\n17 21 180\n18 45 169\n19 39 179\n20 36 133"
},
{
"code": null,
"e": 1929,
"s": 1783,
"text": "To combine the values of both columns in df1 separated with hyphen on the above\ncreated data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 2058,
"s": 1929,
"text": "Age<-sample(20:50,20)\nHeight<-sample(130:200,20)\ndf1<-data.frame(Age,Height)\ndf1$Age_Height<-apply(df1,1,paste,collapse=\"-\")\ndf1"
},
{
"code": null,
"e": 2159,
"s": 2058,
"text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output −"
},
{
"code": null,
"e": 2685,
"s": 2159,
"text": " Age Height Age_Height\n 1 22 147 22-147\n 2 37 138 37-138\n 3 28 184 28-184\n 4 40 154 40-154\n 5 32 193 32-193\n 6 20 135 20-135\n 7 47 185 47-185\n 8 27 198 27-198\n 9 46 156 46-156\n10 29 170 29-170\n11 44 140 44-140\n12 43 167 43-167\n13 23 182 23-182\n14 49 171 49-171\n15 31 150 31-150\n16 25 148 25-148\n17 21 180 21-180\n18 45 169 45-169\n19 39 179 39-179\n20 36 133 36-133"
},
{
"code": null,
"e": 2733,
"s": 2685,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 2859,
"s": 2733,
"text": "Group<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\nRate<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Group,Rate)\ndf2"
},
{
"code": null,
"e": 2935,
"s": 2859,
"text": "If you execute the above given snippet, it generates the following Output −"
},
{
"code": null,
"e": 3209,
"s": 2935,
"text": " Group Rate\n1 First 8\n2 Second 4\n3 First 5\n4 Second 7\n5 Second 4\n6 Third 7\n7 Second 9\n8 Second 7\n9 First 7\n10 Second 3\n11 First 10\n12 Second 9\n13 First 7\n14 First 8\n15 Second 1\n16 Second 8\n17 Second 5\n18 Third 10\n19 Second 4\n20 First 5"
},
{
"code": null,
"e": 3355,
"s": 3209,
"text": "To combine the values of both columns in df2 separated with hyphen on the above\ncreated data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 3529,
"s": 3355,
"text": "Group<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\nRate<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Group,Rate)\ndf2$Group_Rate<-apply(df2,1,paste,collapse=\"-\")\ndf2"
},
{
"code": null,
"e": 3630,
"s": 3529,
"text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output −"
},
{
"code": null,
"e": 4197,
"s": 3630,
"text": " Group Rate Group_Rate\n1 First 8 First- 8\n2 Second 4 Second- 4\n3 First 5 First- 5\n4 Second 7 Second- 7\n5 Second 4 Second- 4\n6 Third 7 Third- 7\n7 Second 9 Second- 9\n8 Second 7 Second- 7\n9 First 7 First- 7\n10 Second 3 Second- 3\n11 First 10 First-10\n12 Second 9 Second- 9\n13 First 7 First- 7\n14 First 8 First- 8\n15 Second 1 Second- 1\n16 Second 8 Second- 8\n17 Second 5 Second- 5\n18 Third 10 Third- 10\n19 Second 4 Second- 4\n20 First 5 First- 5"
}
] |
Python Dictionaries. Use Python Dictionaries Like a Pro | by Erdem Isbilen | Towards Data Science | Python programming language is widely used by developers in data science projects. To complete such projects, understanding data structures plays an important role. Python has several built-in data structures such as lists, sets, tuples, and dictionaries, in order to support the developers with ready to use data structures.
In this article, I will try to explain why and when to use Python dictionaries, meanwhile giving you some hints about the correct usage of the dictionary methods.
Let’s understand the Python dictionaries in detail with step-by-step explanations and examples.
In a nutshell, a dictionary can be defined as a collection of data stored in key/value pairs. Keys must be an immutable data type (such as string, integer or tuple), while values in a dictionary can be any Python data type.
Duplicate keys are not allowed. If the same key is used twice in the same dictionary, then the last occurrence will override the first.
Data stored in a dictionary can be modified so they are called mutable objects. They are unordered which means that the order in which we specified the items is not maintained. (They are ordered in version 3.7 onwards)
As they are dynamic, they can grove or shrink when needed.
As you now know what is a Python dictionary, it is time to explore when to use them in your code.
Here is a list helping you to understand when to use Python dictionaries;
When the data has a unique reference that can be associated with the value.
When quick access to data items is important. Dictionaries are designed to let us find a value instantly without the need for searching through the whole collection.
When the data order is not important.
As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn’t be modified in the first place.
When memory consideration is not an important factor for the application. Compared to lists and tuples, dictionaries take up more space in memory.
There are many ways of creating and initializing the dictionaries. As shown in the below code snippet, the easiest way of creating dictionaries is using curly brackets or dict() method directly;
If you have two iterable objects (for example list objects), you can use zip() function to create a dictionary. See the example below;
fromkeys() method is another way of creating dictionaries. It takes an iterable object and creates a dictionary with specified value as shown in the below code snippet;
Python dictionary comprehensions provide an elegant way of creating dictionaries. They make your code easier to read and more Pythonic. They shorten the code required in dictionary initialisation and they can be used to substitute ‘for’ loops.
The general syntax for dictionary comprehensions is:
dictionary = {key:value for (key, value) in iterable}
You can extend the use of dictionary comprehensions with conditional statements. You can see below the use of multiple ‘if’ conditionals, ‘else-if’ conditionals in dictionary comprehensions;
Getting, setting and deleting an item in a dictionary has O(1) time complexity which means that no matter how big is your dictionary, the time it takes to access an item is constant.
Iterating over a dictionary has O(n) time complexity means that the time it takes to perform this task linearly proportional to the number of items contained in the dictionary.
If you try to access an element with a key which does not exist in your dictionary, you get a KeyError. Knowing the proper way of accessing the elements inside the dictionary is important for not to have KeyErrors during runtime.
To avoid the KeyError, access the elements of a dictionary with get() method. Alternatively, you can check the existence of the key with ‘in’ keyword.
There is no add(), insert()or append()methods that you can use to add items into your dictionary. Instead, you have to create a new key to store the value in your dictionary. If the key already exists in the dictionary, then the value will be overwritten.
Below code snippet shows many examples of adding items into your dictionary;
There are many methods contained in the Python dictionaries helping you to perform different tasks on the dictionary objects. I listed them below with their short definitions;
popitem(): Remove the last item from the dictionary
pop(key, defaultvalue): Removes and returns an element from a dictionary for the given key
keys(): Return the keys
values(): Return the values
items(): Return the dictionary’s key-value pairs
get(key[, value]): Returns the value for the specified key if the key is in a dictionary
fromkeys(keys, value): Returns a dictionary with the specified keys and the specified value
setdefault(key, value): Returns the value of the item with the specified key. If the key does not exist, inserts the key with the specified value
update(iterable): Inserts the specified items to the dictionary if the key is not in the dictionary, otherwise it updates the value
copy(): Returns a shallow copy of the dictionary
clear(): Removes all items from the dictionary
To remove an item from a dictionary object, you can use ‘del’ keyword or pop() method. In addition, you can use dictionary comprehensions to remove items of a dictionary. Check below code snippet for the implementation of those methods with examples;
You can use the copy() method to get a shallow copy of an existing dictionary. A shallow copy means a new dictionary will be populated with references to the objects in the existing dictionary.
To create a deep copy, ‘copy.deepcopy(dict)’ method should be used. It creates a fully independent clone of the original dictionary with all of its elements.
See below to understand how you can implement shallow copy and deep copy methods on dictionary objects;
You can merge dictionaries with a custom function containing dict.copy() and dict.update() methods.
In Python 3.5 and onwards, you can merge dictionaries with unpacking them using ‘**’ operator.
The simplest and easiest way of merging dictionaries is using the merging operator ‘|’ which is available in Python 3.9+
Below code snippet shows implementations of all above methods with examples;
Python dictionaries are unordered up to version 3.7 so even if you sort the (key, value) pairs, you wouldn’t be able to store them in a dictionary by preserving the ordering. To preserve the ordering, we can store the sorted dictionary in an OrderedDict
See below to explore how you can sort the dictionaries by key and by value;
Python dictionary methods; values(), keys(), and items() provide access to the elements contained inside a dictionary. You can use them in for loops to iterate through the dictionaries.
In addition, dictionary comprehensions can also be used for iteration as shown below;
As data structures are fundamental parts of our programs, it is really important to have a solid understanding of Python dictionaries to create efficient programs.
I explained why and when to use the dictionaries, some of the key takeaways are listed below;
Python dictionaries can be used when the data has a unique reference that can be associated with the value.
As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn’t be modified in the first place.
Python dictionaries are unordered up to version 3.7 so even if you sort the (key, value) pairs, you wouldn’t be able to store them in a dictionary by preserving the ordering.
Python dictionary comprehensions provide an elegant way of creating dictionaries. They make your code easier to read and more Pythonic.
Thank you for reading! | [
{
"code": null,
"e": 498,
"s": 172,
"text": "Python programming language is widely used by developers in data science projects. To complete such projects, understanding data structures plays an important role. Python has several built-in data structures such as lists, sets, tuples, and dictionaries, in order to support the developers with ready to use data structures."
},
{
"code": null,
"e": 661,
"s": 498,
"text": "In this article, I will try to explain why and when to use Python dictionaries, meanwhile giving you some hints about the correct usage of the dictionary methods."
},
{
"code": null,
"e": 757,
"s": 661,
"text": "Let’s understand the Python dictionaries in detail with step-by-step explanations and examples."
},
{
"code": null,
"e": 981,
"s": 757,
"text": "In a nutshell, a dictionary can be defined as a collection of data stored in key/value pairs. Keys must be an immutable data type (such as string, integer or tuple), while values in a dictionary can be any Python data type."
},
{
"code": null,
"e": 1117,
"s": 981,
"text": "Duplicate keys are not allowed. If the same key is used twice in the same dictionary, then the last occurrence will override the first."
},
{
"code": null,
"e": 1336,
"s": 1117,
"text": "Data stored in a dictionary can be modified so they are called mutable objects. They are unordered which means that the order in which we specified the items is not maintained. (They are ordered in version 3.7 onwards)"
},
{
"code": null,
"e": 1395,
"s": 1336,
"text": "As they are dynamic, they can grove or shrink when needed."
},
{
"code": null,
"e": 1493,
"s": 1395,
"text": "As you now know what is a Python dictionary, it is time to explore when to use them in your code."
},
{
"code": null,
"e": 1567,
"s": 1493,
"text": "Here is a list helping you to understand when to use Python dictionaries;"
},
{
"code": null,
"e": 1643,
"s": 1567,
"text": "When the data has a unique reference that can be associated with the value."
},
{
"code": null,
"e": 1809,
"s": 1643,
"text": "When quick access to data items is important. Dictionaries are designed to let us find a value instantly without the need for searching through the whole collection."
},
{
"code": null,
"e": 1847,
"s": 1809,
"text": "When the data order is not important."
},
{
"code": null,
"e": 1979,
"s": 1847,
"text": "As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn’t be modified in the first place."
},
{
"code": null,
"e": 2126,
"s": 1979,
"text": "When memory consideration is not an important factor for the application. Compared to lists and tuples, dictionaries take up more space in memory."
},
{
"code": null,
"e": 2321,
"s": 2126,
"text": "There are many ways of creating and initializing the dictionaries. As shown in the below code snippet, the easiest way of creating dictionaries is using curly brackets or dict() method directly;"
},
{
"code": null,
"e": 2456,
"s": 2321,
"text": "If you have two iterable objects (for example list objects), you can use zip() function to create a dictionary. See the example below;"
},
{
"code": null,
"e": 2625,
"s": 2456,
"text": "fromkeys() method is another way of creating dictionaries. It takes an iterable object and creates a dictionary with specified value as shown in the below code snippet;"
},
{
"code": null,
"e": 2869,
"s": 2625,
"text": "Python dictionary comprehensions provide an elegant way of creating dictionaries. They make your code easier to read and more Pythonic. They shorten the code required in dictionary initialisation and they can be used to substitute ‘for’ loops."
},
{
"code": null,
"e": 2922,
"s": 2869,
"text": "The general syntax for dictionary comprehensions is:"
},
{
"code": null,
"e": 2976,
"s": 2922,
"text": "dictionary = {key:value for (key, value) in iterable}"
},
{
"code": null,
"e": 3167,
"s": 2976,
"text": "You can extend the use of dictionary comprehensions with conditional statements. You can see below the use of multiple ‘if’ conditionals, ‘else-if’ conditionals in dictionary comprehensions;"
},
{
"code": null,
"e": 3350,
"s": 3167,
"text": "Getting, setting and deleting an item in a dictionary has O(1) time complexity which means that no matter how big is your dictionary, the time it takes to access an item is constant."
},
{
"code": null,
"e": 3527,
"s": 3350,
"text": "Iterating over a dictionary has O(n) time complexity means that the time it takes to perform this task linearly proportional to the number of items contained in the dictionary."
},
{
"code": null,
"e": 3757,
"s": 3527,
"text": "If you try to access an element with a key which does not exist in your dictionary, you get a KeyError. Knowing the proper way of accessing the elements inside the dictionary is important for not to have KeyErrors during runtime."
},
{
"code": null,
"e": 3908,
"s": 3757,
"text": "To avoid the KeyError, access the elements of a dictionary with get() method. Alternatively, you can check the existence of the key with ‘in’ keyword."
},
{
"code": null,
"e": 4164,
"s": 3908,
"text": "There is no add(), insert()or append()methods that you can use to add items into your dictionary. Instead, you have to create a new key to store the value in your dictionary. If the key already exists in the dictionary, then the value will be overwritten."
},
{
"code": null,
"e": 4241,
"s": 4164,
"text": "Below code snippet shows many examples of adding items into your dictionary;"
},
{
"code": null,
"e": 4417,
"s": 4241,
"text": "There are many methods contained in the Python dictionaries helping you to perform different tasks on the dictionary objects. I listed them below with their short definitions;"
},
{
"code": null,
"e": 4469,
"s": 4417,
"text": "popitem(): Remove the last item from the dictionary"
},
{
"code": null,
"e": 4560,
"s": 4469,
"text": "pop(key, defaultvalue): Removes and returns an element from a dictionary for the given key"
},
{
"code": null,
"e": 4584,
"s": 4560,
"text": "keys(): Return the keys"
},
{
"code": null,
"e": 4612,
"s": 4584,
"text": "values(): Return the values"
},
{
"code": null,
"e": 4661,
"s": 4612,
"text": "items(): Return the dictionary’s key-value pairs"
},
{
"code": null,
"e": 4750,
"s": 4661,
"text": "get(key[, value]): Returns the value for the specified key if the key is in a dictionary"
},
{
"code": null,
"e": 4842,
"s": 4750,
"text": "fromkeys(keys, value): Returns a dictionary with the specified keys and the specified value"
},
{
"code": null,
"e": 4988,
"s": 4842,
"text": "setdefault(key, value): Returns the value of the item with the specified key. If the key does not exist, inserts the key with the specified value"
},
{
"code": null,
"e": 5120,
"s": 4988,
"text": "update(iterable): Inserts the specified items to the dictionary if the key is not in the dictionary, otherwise it updates the value"
},
{
"code": null,
"e": 5169,
"s": 5120,
"text": "copy(): Returns a shallow copy of the dictionary"
},
{
"code": null,
"e": 5216,
"s": 5169,
"text": "clear(): Removes all items from the dictionary"
},
{
"code": null,
"e": 5467,
"s": 5216,
"text": "To remove an item from a dictionary object, you can use ‘del’ keyword or pop() method. In addition, you can use dictionary comprehensions to remove items of a dictionary. Check below code snippet for the implementation of those methods with examples;"
},
{
"code": null,
"e": 5661,
"s": 5467,
"text": "You can use the copy() method to get a shallow copy of an existing dictionary. A shallow copy means a new dictionary will be populated with references to the objects in the existing dictionary."
},
{
"code": null,
"e": 5819,
"s": 5661,
"text": "To create a deep copy, ‘copy.deepcopy(dict)’ method should be used. It creates a fully independent clone of the original dictionary with all of its elements."
},
{
"code": null,
"e": 5923,
"s": 5819,
"text": "See below to understand how you can implement shallow copy and deep copy methods on dictionary objects;"
},
{
"code": null,
"e": 6023,
"s": 5923,
"text": "You can merge dictionaries with a custom function containing dict.copy() and dict.update() methods."
},
{
"code": null,
"e": 6118,
"s": 6023,
"text": "In Python 3.5 and onwards, you can merge dictionaries with unpacking them using ‘**’ operator."
},
{
"code": null,
"e": 6239,
"s": 6118,
"text": "The simplest and easiest way of merging dictionaries is using the merging operator ‘|’ which is available in Python 3.9+"
},
{
"code": null,
"e": 6316,
"s": 6239,
"text": "Below code snippet shows implementations of all above methods with examples;"
},
{
"code": null,
"e": 6570,
"s": 6316,
"text": "Python dictionaries are unordered up to version 3.7 so even if you sort the (key, value) pairs, you wouldn’t be able to store them in a dictionary by preserving the ordering. To preserve the ordering, we can store the sorted dictionary in an OrderedDict"
},
{
"code": null,
"e": 6646,
"s": 6570,
"text": "See below to explore how you can sort the dictionaries by key and by value;"
},
{
"code": null,
"e": 6832,
"s": 6646,
"text": "Python dictionary methods; values(), keys(), and items() provide access to the elements contained inside a dictionary. You can use them in for loops to iterate through the dictionaries."
},
{
"code": null,
"e": 6918,
"s": 6832,
"text": "In addition, dictionary comprehensions can also be used for iteration as shown below;"
},
{
"code": null,
"e": 7082,
"s": 6918,
"text": "As data structures are fundamental parts of our programs, it is really important to have a solid understanding of Python dictionaries to create efficient programs."
},
{
"code": null,
"e": 7176,
"s": 7082,
"text": "I explained why and when to use the dictionaries, some of the key takeaways are listed below;"
},
{
"code": null,
"e": 7284,
"s": 7176,
"text": "Python dictionaries can be used when the data has a unique reference that can be associated with the value."
},
{
"code": null,
"e": 7416,
"s": 7284,
"text": "As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn’t be modified in the first place."
},
{
"code": null,
"e": 7591,
"s": 7416,
"text": "Python dictionaries are unordered up to version 3.7 so even if you sort the (key, value) pairs, you wouldn’t be able to store them in a dictionary by preserving the ordering."
},
{
"code": null,
"e": 7727,
"s": 7591,
"text": "Python dictionary comprehensions provide an elegant way of creating dictionaries. They make your code easier to read and more Pythonic."
}
] |
2's complement for a given string using XOR - GeeksforGeeks | 31 Dec, 2021
Given a binary string, task is to convert this string in to two’s complement with the help of XOR operator.
Examples:
Input : 00000101
Output :11111011
Input : 10010
Output : 01110
We have discussed an approach in previous post to find 2’s complement
For 2’s complement, we first find one’s complement. We traverse the one’s complement starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until we find a 0. Finally, we flip the found 0.
We traverse from the last bot and keep ignoring all 0s until we find a 1. We ignore first 1 also. Then we toggle all bits by doing XOR with 1.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find 2's complement using XOR.#include <bits/stdc++.h>using namespace std; string TwoscomplementbyXOR(string str){ int n = str.length(); // A flag used to find if a 1 bit is seen // or not. bool check_bit = 0; for (int i = n - 1; i >= 0; i--) { if (str[i] == '0' && check_bit == 0) { continue; } else { // xor operator is used to flip the if (check_bit == 1) str[i] = (str[i] - '0') ^ 1 + '0'; // bits after converting in to // ASCII values check_bit = 1; } } // if there is no 1 in the string so just add // 1 in starting of string and return if (check_bit == 0) return "1" + str; else return str;} // Driver codeint main(){ string str = "101"; cout << TwoscomplementbyXOR(str); return 0;}
// Java program to find 2's complement using XOR.import java.util.*; class GFG{ static void TwoscomplementbyXOR(String str){ int n = str.length(); // A flag used to find if a 1 bit is seen // or not. boolean check_bit = false; for(int i = n - 1; i >= 0; i--) { if (str.charAt(i) == '0' && check_bit == false) { continue; } else { // xor operator is used to flip the if (check_bit == true) { if (str.charAt(i) == '0') str = str.substring(0, i) + '1' + str.substring(i + 1); else str = str.substring(0, i) + '0' + str.substring(i + 1); } // bits after converting in to // ASCII values check_bit = true; } } // If there is no 1 in the string so just add // 1 in starting of string and return if (check_bit == false) { System.out.println("1" + str); } else System.out.println(str);} // Driver codepublic static void main(String[] args) { String str = "101"; TwoscomplementbyXOR(str);}} // This code is contributed by amreshkumar3
# Python program to find 2's complement using XOR.def TwoscomplementbyXOR(str): n = len(str) # A flag used to find if a 1 bit is seen # or not. check_bit = 0 i = n - 1 s = list(str) while (i >= 0): if (s[i] == '0' and check_bit == 0): continue else: # xor operator is used to flip the if (check_bit == 1): s[i] = chr((ord(s[i]) - 48) ^ 1 + 48) # bits after converting in to # ASCII values check_bit = 1 i -= 1 # if there is no 1 in the string so just add # 1 in starting of string and return str = "".join(s) if (check_bit == 0): return "1" + str else: return str # Driver codestr = "101"print(TwoscomplementbyXOR(str)) # This code is contributed by subhammahato348.
// C# program to find 2's complement using XOR.using System;class GFG { static void TwoscomplementbyXOR(string str) { int n = str.Length; // A flag used to find if a 1 bit is seen // or not. bool check_bit = false; for(int i = n - 1; i >= 0; i--) { if (str[i] == '0' && check_bit == false) { continue; } else { // xor operator is used to flip the if (check_bit == true) { if (str[i] == '0') str = str.Substring(0, i) + '1' + str.Substring(i + 1); else str = str.Substring(0, i) + '0' + str.Substring(i + 1); } // bits after converting in to // ASCII values check_bit = true; } } // If there is no 1 in the string so just add // 1 in starting of string and return if (check_bit == false) { Console.WriteLine("1" + str); } else Console.WriteLine(str); } // Driver code static void Main() { string str = "101"; TwoscomplementbyXOR(str); }} // This code is contributed by divyeshrabadiya07.
<?php// PHP program to find 2's complement // using XOR. function TwoscomplementbyXOR($str) { $n =strlen($str); // A flag used to find if a 1 // bit is seen or not. $check_bit = 0; for ($i = $n - 1; $i >= 0; $i--) { if ($str[$i] == '0' && $check_bit == 0) { continue; } else { // xor operator is used // to flip the if ($check_bit == 1) $str[$i] = ($str[$i] - '0') ^ 1 + '0'; // bits after converting in to // ASCII values $check_bit = 1; } } // if there is no 1 in the string // so just add 1 in starting of // string and return if ($check_bit == 0) return "1" + $str; else return $str; } // Driver code $str = "101"; echo TwoscomplementbyXOR($str); // This code is contributed by akt_mit?>
<script>// Javascript program to find 2's complement // using XOR. function TwoscomplementbyXOR(str) { let n = str.length; // A flag used to find if a 1 // bit is seen or not. let check_bit = 0; for (let i = n - 1; i >= 0; i--) { if (str[i] == '0' && check_bit == 0) { continue; } else { // xor operator is used // to flip the if (check_bit == 1) { if (str.charAt(i) == '0') str = str.substr(0, i) + '1' + str.substr(i + 1); else str = str.substr(0, i) + '0' + str.substr(i + 1); } // bits after converting in to // ASCII values check_bit = 1; } } // if there is no 1 in the string // so just add 1 in starting of // string and return if (check_bit == 0) return "1" + str; else return str;} // Driver code let str = "101";document.write(TwoscomplementbyXOR(str)); // This code is contributed by _saurabh_jaiswal</script>
011
jit_t
amreshkumar3
subhammahato348
divyeshrabadiya07
_saurabh_jaiswal
ruhelaa48
surindertarika1234
binary-string
Bitwise-XOR
complement
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Hamming code Implementation in C/C++
Check for Integer Overflow
Swap bits in a given number
Highest power of 2 less than or equal to given number
Builtin functions of GCC compiler
Count number of bits to be flipped to convert A to B | [
{
"code": null,
"e": 24988,
"s": 24960,
"text": "\n31 Dec, 2021"
},
{
"code": null,
"e": 25096,
"s": 24988,
"text": "Given a binary string, task is to convert this string in to two’s complement with the help of XOR operator."
},
{
"code": null,
"e": 25107,
"s": 25096,
"text": "Examples: "
},
{
"code": null,
"e": 25171,
"s": 25107,
"text": "Input : 00000101\nOutput :11111011\n\nInput : 10010\nOutput : 01110"
},
{
"code": null,
"e": 25241,
"s": 25171,
"text": "We have discussed an approach in previous post to find 2’s complement"
},
{
"code": null,
"e": 25464,
"s": 25241,
"text": "For 2’s complement, we first find one’s complement. We traverse the one’s complement starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until we find a 0. Finally, we flip the found 0."
},
{
"code": null,
"e": 25607,
"s": 25464,
"text": "We traverse from the last bot and keep ignoring all 0s until we find a 1. We ignore first 1 also. Then we toggle all bits by doing XOR with 1."
},
{
"code": null,
"e": 25611,
"s": 25607,
"text": "C++"
},
{
"code": null,
"e": 25616,
"s": 25611,
"text": "Java"
},
{
"code": null,
"e": 25624,
"s": 25616,
"text": "Python3"
},
{
"code": null,
"e": 25627,
"s": 25624,
"text": "C#"
},
{
"code": null,
"e": 25631,
"s": 25627,
"text": "PHP"
},
{
"code": null,
"e": 25642,
"s": 25631,
"text": "Javascript"
},
{
"code": "// C++ program to find 2's complement using XOR.#include <bits/stdc++.h>using namespace std; string TwoscomplementbyXOR(string str){ int n = str.length(); // A flag used to find if a 1 bit is seen // or not. bool check_bit = 0; for (int i = n - 1; i >= 0; i--) { if (str[i] == '0' && check_bit == 0) { continue; } else { // xor operator is used to flip the if (check_bit == 1) str[i] = (str[i] - '0') ^ 1 + '0'; // bits after converting in to // ASCII values check_bit = 1; } } // if there is no 1 in the string so just add // 1 in starting of string and return if (check_bit == 0) return \"1\" + str; else return str;} // Driver codeint main(){ string str = \"101\"; cout << TwoscomplementbyXOR(str); return 0;}",
"e": 26531,
"s": 25642,
"text": null
},
{
"code": "// Java program to find 2's complement using XOR.import java.util.*; class GFG{ static void TwoscomplementbyXOR(String str){ int n = str.length(); // A flag used to find if a 1 bit is seen // or not. boolean check_bit = false; for(int i = n - 1; i >= 0; i--) { if (str.charAt(i) == '0' && check_bit == false) { continue; } else { // xor operator is used to flip the if (check_bit == true) { if (str.charAt(i) == '0') str = str.substring(0, i) + '1' + str.substring(i + 1); else str = str.substring(0, i) + '0' + str.substring(i + 1); } // bits after converting in to // ASCII values check_bit = true; } } // If there is no 1 in the string so just add // 1 in starting of string and return if (check_bit == false) { System.out.println(\"1\" + str); } else System.out.println(str);} // Driver codepublic static void main(String[] args) { String str = \"101\"; TwoscomplementbyXOR(str);}} // This code is contributed by amreshkumar3",
"e": 27837,
"s": 26531,
"text": null
},
{
"code": "# Python program to find 2's complement using XOR.def TwoscomplementbyXOR(str): n = len(str) # A flag used to find if a 1 bit is seen # or not. check_bit = 0 i = n - 1 s = list(str) while (i >= 0): if (s[i] == '0' and check_bit == 0): continue else: # xor operator is used to flip the if (check_bit == 1): s[i] = chr((ord(s[i]) - 48) ^ 1 + 48) # bits after converting in to # ASCII values check_bit = 1 i -= 1 # if there is no 1 in the string so just add # 1 in starting of string and return str = \"\".join(s) if (check_bit == 0): return \"1\" + str else: return str # Driver codestr = \"101\"print(TwoscomplementbyXOR(str)) # This code is contributed by subhammahato348.",
"e": 28666,
"s": 27837,
"text": null
},
{
"code": "// C# program to find 2's complement using XOR.using System;class GFG { static void TwoscomplementbyXOR(string str) { int n = str.Length; // A flag used to find if a 1 bit is seen // or not. bool check_bit = false; for(int i = n - 1; i >= 0; i--) { if (str[i] == '0' && check_bit == false) { continue; } else { // xor operator is used to flip the if (check_bit == true) { if (str[i] == '0') str = str.Substring(0, i) + '1' + str.Substring(i + 1); else str = str.Substring(0, i) + '0' + str.Substring(i + 1); } // bits after converting in to // ASCII values check_bit = true; } } // If there is no 1 in the string so just add // 1 in starting of string and return if (check_bit == false) { Console.WriteLine(\"1\" + str); } else Console.WriteLine(str); } // Driver code static void Main() { string str = \"101\"; TwoscomplementbyXOR(str); }} // This code is contributed by divyeshrabadiya07.",
"e": 29792,
"s": 28666,
"text": null
},
{
"code": "<?php// PHP program to find 2's complement // using XOR. function TwoscomplementbyXOR($str) { $n =strlen($str); // A flag used to find if a 1 // bit is seen or not. $check_bit = 0; for ($i = $n - 1; $i >= 0; $i--) { if ($str[$i] == '0' && $check_bit == 0) { continue; } else { // xor operator is used // to flip the if ($check_bit == 1) $str[$i] = ($str[$i] - '0') ^ 1 + '0'; // bits after converting in to // ASCII values $check_bit = 1; } } // if there is no 1 in the string // so just add 1 in starting of // string and return if ($check_bit == 0) return \"1\" + $str; else return $str; } // Driver code $str = \"101\"; echo TwoscomplementbyXOR($str); // This code is contributed by akt_mit?>",
"e": 30724,
"s": 29792,
"text": null
},
{
"code": "<script>// Javascript program to find 2's complement // using XOR. function TwoscomplementbyXOR(str) { let n = str.length; // A flag used to find if a 1 // bit is seen or not. let check_bit = 0; for (let i = n - 1; i >= 0; i--) { if (str[i] == '0' && check_bit == 0) { continue; } else { // xor operator is used // to flip the if (check_bit == 1) { if (str.charAt(i) == '0') str = str.substr(0, i) + '1' + str.substr(i + 1); else str = str.substr(0, i) + '0' + str.substr(i + 1); } // bits after converting in to // ASCII values check_bit = 1; } } // if there is no 1 in the string // so just add 1 in starting of // string and return if (check_bit == 0) return \"1\" + str; else return str;} // Driver code let str = \"101\";document.write(TwoscomplementbyXOR(str)); // This code is contributed by _saurabh_jaiswal</script>",
"e": 31798,
"s": 30724,
"text": null
},
{
"code": null,
"e": 31802,
"s": 31798,
"text": "011"
},
{
"code": null,
"e": 31810,
"s": 31804,
"text": "jit_t"
},
{
"code": null,
"e": 31823,
"s": 31810,
"text": "amreshkumar3"
},
{
"code": null,
"e": 31839,
"s": 31823,
"text": "subhammahato348"
},
{
"code": null,
"e": 31857,
"s": 31839,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 31874,
"s": 31857,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31884,
"s": 31874,
"text": "ruhelaa48"
},
{
"code": null,
"e": 31903,
"s": 31884,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31917,
"s": 31903,
"text": "binary-string"
},
{
"code": null,
"e": 31929,
"s": 31917,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 31940,
"s": 31929,
"text": "complement"
},
{
"code": null,
"e": 31950,
"s": 31940,
"text": "Bit Magic"
},
{
"code": null,
"e": 31960,
"s": 31950,
"text": "Bit Magic"
},
{
"code": null,
"e": 32058,
"s": 31960,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32109,
"s": 32058,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 32146,
"s": 32109,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 32169,
"s": 32146,
"text": "Program to find parity"
},
{
"code": null,
"e": 32233,
"s": 32169,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 32270,
"s": 32233,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 32297,
"s": 32270,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 32325,
"s": 32297,
"text": "Swap bits in a given number"
},
{
"code": null,
"e": 32379,
"s": 32325,
"text": "Highest power of 2 less than or equal to given number"
},
{
"code": null,
"e": 32413,
"s": 32379,
"text": "Builtin functions of GCC compiler"
}
] |
Kotlin - Comments | A comment is a programmer-readable explanation or annotation in the Kotlin source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Kotlin compiler.
Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments. Kotlin comments are very much similar to the comments available in Java, C and C++ programming languages.
Single line comments in Kotlin starts with two forward slashes // and end with end of the line. So any text written in between // and the end of the line is ignored by Kotlin compiler.
Following is the sample Kotlin program which makes use of a single-line comment:
// This is a comment
fun main() {
println("Hello, World!")
}
When you run the above Kotlin program, it will generate the following output:
Hello, World!
A single line comment can start from anywhere in the program and will end till the end of the line. For example, you can use single line comment as follows:
fun main() {
println("Hello, World!") // This is also a comment
}
A multi-line comment in Kotlin starts with /* and end with */. So any text written in between /* and */ will be treated as a comment and will be ignored by Kotlin compiler.
Multi-line comments also called Block comments in Kotlin.
Following is the sample Kotlin program which makes use of a multi-line comment:
/* This is a multi-line comment and it can span
* as many lines as you like
*/
fun main() {
println("Hello, World!")
}
When you run the above Kotlin program, it will generate the following output:
Hello, Word!
Block comments in Kotlin can be nested, which means a single-line comment or multi-line comments can sit inside a multi-line comment as below:
/* This is a multi-line comment and it can span
* as many lines as you like
/* This is a nested comment */
// Another nested comment
*/
fun main() {
println("Hello, World!")
}
When you run the above Kotlin program, it will generate the following output:
Hello, World!
Q 1 - Which of the following statements is correct about Kotlin Comments:
A - Kotlin comments are ignored by the compiler
B - Kotlin comments helps programmer to increase the readability of the code
C - Kotlin supports nested comments
D - All of the above
All the given three statements are correct for Kotlin comments.
Q 2 - What could be the length of a Kotlin Single-line comment:
A - 256 characters
B - Infinite
C - Till the end of the line
D - None of the above
There is no specification about the length of Kotlin comments, so single-line comment can be as long as a line. A multi-line comment can also span as long as you want.
Q 3 - Which of the following statements is not correct about Kotlin comments
A - Kotlin comments degrade the performance of the Kotlin program
B - Kotlin supports single-line and multi-line comments
C - Kotlin comments are recommended to make code more readable
D - Kotlin comments are very much similar to the comments available in Java, C and C++
Statement A is incorrect because comments never impact a Kotlin program regardless the volume of the comments available in the program because they are ignore by the compiler and they do not cconsider while generating the final bytecode.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2640,
"s": 2425,
"text": "A comment is a programmer-readable explanation or annotation in the Kotlin source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Kotlin compiler."
},
{
"code": null,
"e": 2857,
"s": 2640,
"text": "Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments. Kotlin comments are very much similar to the comments available in Java, C and C++ programming languages."
},
{
"code": null,
"e": 3042,
"s": 2857,
"text": "Single line comments in Kotlin starts with two forward slashes // and end with end of the line. So any text written in between // and the end of the line is ignored by Kotlin compiler."
},
{
"code": null,
"e": 3123,
"s": 3042,
"text": "Following is the sample Kotlin program which makes use of a single-line comment:"
},
{
"code": null,
"e": 3190,
"s": 3123,
"text": "// This is a comment\n\nfun main() {\n println(\"Hello, World!\")\n}\n"
},
{
"code": null,
"e": 3268,
"s": 3190,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3283,
"s": 3268,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 3441,
"s": 3283,
"text": " A single line comment can start from anywhere in the program and will end till the end of the line. For example, you can use single line comment as follows:"
},
{
"code": null,
"e": 3512,
"s": 3441,
"text": "fun main() {\n println(\"Hello, World!\") // This is also a comment\n}\n"
},
{
"code": null,
"e": 3686,
"s": 3512,
"text": "A multi-line comment in Kotlin starts with /* and end with */. So any text written in between /* and */ will be treated as a comment and will be ignored by Kotlin compiler."
},
{
"code": null,
"e": 3744,
"s": 3686,
"text": "Multi-line comments also called Block comments in Kotlin."
},
{
"code": null,
"e": 3824,
"s": 3744,
"text": "Following is the sample Kotlin program which makes use of a multi-line comment:"
},
{
"code": null,
"e": 3952,
"s": 3824,
"text": "/* This is a multi-line comment and it can span\n * as many lines as you like \n */\n\nfun main() {\n println(\"Hello, World!\")\n}\n"
},
{
"code": null,
"e": 4030,
"s": 3952,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4044,
"s": 4030,
"text": "Hello, Word!\n"
},
{
"code": null,
"e": 4187,
"s": 4044,
"text": "Block comments in Kotlin can be nested, which means a single-line comment or multi-line comments can sit inside a multi-line comment as below:"
},
{
"code": null,
"e": 4375,
"s": 4187,
"text": "/* This is a multi-line comment and it can span\n * as many lines as you like \n /* This is a nested comment */\n // Another nested comment \n */\n\nfun main() {\n println(\"Hello, World!\")\n}\n"
},
{
"code": null,
"e": 4453,
"s": 4375,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4468,
"s": 4453,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 4542,
"s": 4468,
"text": "Q 1 - Which of the following statements is correct about Kotlin Comments:"
},
{
"code": null,
"e": 4590,
"s": 4542,
"text": "A - Kotlin comments are ignored by the compiler"
},
{
"code": null,
"e": 4667,
"s": 4590,
"text": "B - Kotlin comments helps programmer to increase the readability of the code"
},
{
"code": null,
"e": 4703,
"s": 4667,
"text": "C - Kotlin supports nested comments"
},
{
"code": null,
"e": 4724,
"s": 4703,
"text": "D - All of the above"
},
{
"code": null,
"e": 4788,
"s": 4724,
"text": "All the given three statements are correct for Kotlin comments."
},
{
"code": null,
"e": 4852,
"s": 4788,
"text": "Q 2 - What could be the length of a Kotlin Single-line comment:"
},
{
"code": null,
"e": 4871,
"s": 4852,
"text": "A - 256 characters"
},
{
"code": null,
"e": 4884,
"s": 4871,
"text": "B - Infinite"
},
{
"code": null,
"e": 4913,
"s": 4884,
"text": "C - Till the end of the line"
},
{
"code": null,
"e": 4935,
"s": 4913,
"text": "D - None of the above"
},
{
"code": null,
"e": 5103,
"s": 4935,
"text": "There is no specification about the length of Kotlin comments, so single-line comment can be as long as a line. A multi-line comment can also span as long as you want."
},
{
"code": null,
"e": 5180,
"s": 5103,
"text": "Q 3 - Which of the following statements is not correct about Kotlin comments"
},
{
"code": null,
"e": 5246,
"s": 5180,
"text": "A - Kotlin comments degrade the performance of the Kotlin program"
},
{
"code": null,
"e": 5303,
"s": 5246,
"text": "B - Kotlin supports single-line and multi-line comments "
},
{
"code": null,
"e": 5366,
"s": 5303,
"text": "C - Kotlin comments are recommended to make code more readable"
},
{
"code": null,
"e": 5453,
"s": 5366,
"text": "D - Kotlin comments are very much similar to the comments available in Java, C and C++"
},
{
"code": null,
"e": 5691,
"s": 5453,
"text": "Statement A is incorrect because comments never impact a Kotlin program regardless the volume of the comments available in the program because they are ignore by the compiler and they do not cconsider while generating the final bytecode."
},
{
"code": null,
"e": 5726,
"s": 5691,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5745,
"s": 5726,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5780,
"s": 5745,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5797,
"s": 5780,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5832,
"s": 5797,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5849,
"s": 5832,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 5882,
"s": 5849,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5898,
"s": 5882,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 5933,
"s": 5898,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5953,
"s": 5933,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5986,
"s": 5953,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6003,
"s": 5986,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 6010,
"s": 6003,
"text": " Print"
},
{
"code": null,
"e": 6021,
"s": 6010,
"text": " Add Notes"
}
] |
JSON and APIs with Python. An Introduction to JSON and APIs using... | by Luay Matalka | Towards Data Science | In a different tutorial, we discussed how to web scrape with python. The goal of web scraping was to access data from a website or webpage. Well, sometimes a website can make it easier for a user to have direct access to their data with the use of an API (Application Programming Interface). This basically means that the company has made a set of dedicated URLs that provide this data in a pure form (meaning without any presentation formatting). This pure data is often in a JSON (JavaScript Object Notation) format, which we can then parse through and extract what we need using python.
For this tutorial, we will use the free API found at covid19api.com that provides data on the coronavirus. We will find the total number of confirmed cases in each country and then we will create a pandas dataframe that contains that information. So let’s begin!
pub.towardsai.net
If you go to the documentation page of the API, this is what you’ll see:
This shows us the different URLs in the API, the information they provide, and example requests/responses of those URLs on the right.
We can see that the information we are seeking is in the summary page. We can click on view more on the right so we can see what the response would be from that URL:
This is a JSON object! As you can see, it is very similar to a python dictionary and is made up of key-value pairs. In fact, in order for us to parse through this and extract what we want from it, we will eventually turn it into a python dictionary object. Upon inspection, we can see that it looks like a nested dictionary. The outer dictionary has the keys ‘Global’ (with a value of a dictionary) and ‘Countries’ (with a value of a list that is made up of dictionaries, with each dictionary corresponding to a specific country).
towardsdatascience.com
So let’s open a jupyter notebook and request the information from that URL. We will use the requests library to make an HTTP request from that URL and save the response object’s text under the variable response:
response = requests.get(‘https://api.covid19api.com/summary’).text
This shows what the response is to our HTTP request from the API. As you can see, it is a long python string that is in JSON format.
towardsdatascience.com
Since the response is in JSON format, we can load this string into python and convert it into a python dictionary. We first need to import the json library, and then we can use the loads method from the json library and pass it our string:
response_info = json.loads(response)
Note how the type of our response_info variable is now a python dictionary!
Now that our response is in the form of a python dictionary, we can use what we know about python dictionaries to parse it and extract the information we need!
Also note: The requests library has a built-in JSON decoder that we could have used instead of the json module that would have converted our JSON object to a python dictionary. However, I used the above method to introduce the json module in this tutorial. Here’s what the code would have looked like if we instead used the JSON decoder within the requests module:
requests.get(‘https://api.covid19api.com/summary’).json()
As previously mentioned, we would like to make a pandas dataframe that has two columns: countries, and the number of total confirmed cases for that country. We can do so by looping through the values of the ‘Countries’ key of our outer dictionary:
As you can see, the value of our ‘Countries’ key is just a list of dictionaries, with each dictionary containing key-value pairs corresponding to a specific country. So we need to loop through this list of dictionaries, extracting the values of the ‘Country’ and ‘TotalConfirmed’ keys from each dictionary and then appending them to a new list as follows:
country_list = []for country_info in response_info[‘Countries’]: country_list.append([country_info[‘Country’], country_info[‘TotalConfirmed’]])
This will loop through the list of dictionaries, extracting the values from the ‘Country’ and ‘TotalConfirmed’ keys from each dictionary into a list, and then adding this resulting list to our country_list. We will end up with a list of lists, with each list or element in the outer list containing the country name and the total confirmed cases for that specific country.
towardsdatascience.com
We will now create a pandas dataframe using this country_list and the pandas DataFrame constructor:
country_df = pd.DataFrame(data=country_list, columns=[‘Country’, ‘Total_Confirmed’])
Success! We now have a dataframe that contains two columns: Country and Total_Confirmed!
In this tutorial, we had a brief introduction to what APIs and JSON are. We then made an HTTP request to a Coronavirus COVID19 API to get information on the number of total confirmed coronavirus cases in each country. We then converted this JSON response to our request into a python dictionary. We then parsed through this dictionary, extracting the information we were seeking, and then created a pandas dataframe containing this information. | [
{
"code": null,
"e": 762,
"s": 172,
"text": "In a different tutorial, we discussed how to web scrape with python. The goal of web scraping was to access data from a website or webpage. Well, sometimes a website can make it easier for a user to have direct access to their data with the use of an API (Application Programming Interface). This basically means that the company has made a set of dedicated URLs that provide this data in a pure form (meaning without any presentation formatting). This pure data is often in a JSON (JavaScript Object Notation) format, which we can then parse through and extract what we need using python."
},
{
"code": null,
"e": 1025,
"s": 762,
"text": "For this tutorial, we will use the free API found at covid19api.com that provides data on the coronavirus. We will find the total number of confirmed cases in each country and then we will create a pandas dataframe that contains that information. So let’s begin!"
},
{
"code": null,
"e": 1043,
"s": 1025,
"text": "pub.towardsai.net"
},
{
"code": null,
"e": 1116,
"s": 1043,
"text": "If you go to the documentation page of the API, this is what you’ll see:"
},
{
"code": null,
"e": 1250,
"s": 1116,
"text": "This shows us the different URLs in the API, the information they provide, and example requests/responses of those URLs on the right."
},
{
"code": null,
"e": 1416,
"s": 1250,
"text": "We can see that the information we are seeking is in the summary page. We can click on view more on the right so we can see what the response would be from that URL:"
},
{
"code": null,
"e": 1947,
"s": 1416,
"text": "This is a JSON object! As you can see, it is very similar to a python dictionary and is made up of key-value pairs. In fact, in order for us to parse through this and extract what we want from it, we will eventually turn it into a python dictionary object. Upon inspection, we can see that it looks like a nested dictionary. The outer dictionary has the keys ‘Global’ (with a value of a dictionary) and ‘Countries’ (with a value of a list that is made up of dictionaries, with each dictionary corresponding to a specific country)."
},
{
"code": null,
"e": 1970,
"s": 1947,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2182,
"s": 1970,
"text": "So let’s open a jupyter notebook and request the information from that URL. We will use the requests library to make an HTTP request from that URL and save the response object’s text under the variable response:"
},
{
"code": null,
"e": 2249,
"s": 2182,
"text": "response = requests.get(‘https://api.covid19api.com/summary’).text"
},
{
"code": null,
"e": 2382,
"s": 2249,
"text": "This shows what the response is to our HTTP request from the API. As you can see, it is a long python string that is in JSON format."
},
{
"code": null,
"e": 2405,
"s": 2382,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2645,
"s": 2405,
"text": "Since the response is in JSON format, we can load this string into python and convert it into a python dictionary. We first need to import the json library, and then we can use the loads method from the json library and pass it our string:"
},
{
"code": null,
"e": 2682,
"s": 2645,
"text": "response_info = json.loads(response)"
},
{
"code": null,
"e": 2758,
"s": 2682,
"text": "Note how the type of our response_info variable is now a python dictionary!"
},
{
"code": null,
"e": 2918,
"s": 2758,
"text": "Now that our response is in the form of a python dictionary, we can use what we know about python dictionaries to parse it and extract the information we need!"
},
{
"code": null,
"e": 3283,
"s": 2918,
"text": "Also note: The requests library has a built-in JSON decoder that we could have used instead of the json module that would have converted our JSON object to a python dictionary. However, I used the above method to introduce the json module in this tutorial. Here’s what the code would have looked like if we instead used the JSON decoder within the requests module:"
},
{
"code": null,
"e": 3341,
"s": 3283,
"text": "requests.get(‘https://api.covid19api.com/summary’).json()"
},
{
"code": null,
"e": 3589,
"s": 3341,
"text": "As previously mentioned, we would like to make a pandas dataframe that has two columns: countries, and the number of total confirmed cases for that country. We can do so by looping through the values of the ‘Countries’ key of our outer dictionary:"
},
{
"code": null,
"e": 3945,
"s": 3589,
"text": "As you can see, the value of our ‘Countries’ key is just a list of dictionaries, with each dictionary containing key-value pairs corresponding to a specific country. So we need to loop through this list of dictionaries, extracting the values of the ‘Country’ and ‘TotalConfirmed’ keys from each dictionary and then appending them to a new list as follows:"
},
{
"code": null,
"e": 4089,
"s": 3945,
"text": "country_list = []for country_info in response_info[‘Countries’]: country_list.append([country_info[‘Country’], country_info[‘TotalConfirmed’]])"
},
{
"code": null,
"e": 4462,
"s": 4089,
"text": "This will loop through the list of dictionaries, extracting the values from the ‘Country’ and ‘TotalConfirmed’ keys from each dictionary into a list, and then adding this resulting list to our country_list. We will end up with a list of lists, with each list or element in the outer list containing the country name and the total confirmed cases for that specific country."
},
{
"code": null,
"e": 4485,
"s": 4462,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4585,
"s": 4485,
"text": "We will now create a pandas dataframe using this country_list and the pandas DataFrame constructor:"
},
{
"code": null,
"e": 4670,
"s": 4585,
"text": "country_df = pd.DataFrame(data=country_list, columns=[‘Country’, ‘Total_Confirmed’])"
},
{
"code": null,
"e": 4759,
"s": 4670,
"text": "Success! We now have a dataframe that contains two columns: Country and Total_Confirmed!"
}
] |
Espresso Testing Framework - Overview of JUnit | In this chapter, let us understand the basics of JUnit, the popular unit-testing framework developed by the Java community upon which the espresso testing framework is build.
JUnit is the de facto standard for unit testing a Java application. Even though, it is popular for unit testing, it has complete support and provision for instrumentation testing as well. Espresso testing library extends the necessary JUnit classes to support the Android based instrumentation testing.
Let us create a Java class, Computation (Computation.java) and write simple mathematical operation, Summation and Multiplication. Then, we will write test cases using JUnit and check it by running the test cases.
Start Android Studio.
Start Android Studio.
Open HelloWorldApp created in the previous chapter.
Open HelloWorldApp created in the previous chapter.
Create a file, Computation.java in app/src/main/java/com/tutorialspoint/espressosamples/helloworldapp/ and write two functions – Sum and Multiply as specified below,
Create a file, Computation.java in app/src/main/java/com/tutorialspoint/espressosamples/helloworldapp/ and write two functions – Sum and Multiply as specified below,
package com.tutorialspoint.espressosamples.helloworldapp;
public class Computation {
public Computation() {}
public int Sum(int a, int b) {
return a + b;
}
public int Multiply(int a, int b) {
return a * b;
}
}
Create a file, ComputationUnitTest.java in app/src/test/java/com/tutorialspoint/espressosamples/helloworldapp and write unit test cases to test Sum and Multiply functionality as specified below
Create a file, ComputationUnitTest.java in app/src/test/java/com/tutorialspoint/espressosamples/helloworldapp and write unit test cases to test Sum and Multiply functionality as specified below
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
@Test
public void sum_isCorrect() {
Computation computation = new Computation();
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
Computation computation = new Computation();
assertEquals(4, computation.Multiply(2,2));
}
}
Here, we have used two new terms – @Test and assertEquals. In general, JUnit uses Java annotation to identify the test cases in a class and information on how to execute the test cases. @Test is one such Java annotation, which specifies that the particular function is a junit test case. assertEquals is a function to assert that the first argument (expected value) and the second argument (computed value) are equal and same. JUnit provides a number of assertion methods for different test scenarios.
Now, run the ComputationUnitTest in the Android studio by right-clicking the class and invoking the Run 'ComputationUnitTest' option as explained in the previous chapter. This will run the unit test cases and report success.
Now, run the ComputationUnitTest in the Android studio by right-clicking the class and invoking the Run 'ComputationUnitTest' option as explained in the previous chapter. This will run the unit test cases and report success.
Result of computation unit test is as shown below −
The JUnit framework uses annotation extensively. Some of the important annotations are as follows −
@Test
@Test
@Before
@Before
@After
@After
@BeforeClass
@BeforeClass
@AfterClass
@AfterClass
@Rule
@Rule
@Test is the very important annotation in the JUnit framework. @Test is used to differentiate a normal method from the test case method. Once a method is decorated with @Test annotation, then that particular method is considered as a Test case and will be run by JUnit Runner. JUnit Runner is a special class, which is used to find and run the JUnit test cases available inside the java classes. For now, we are using Android Studio’s build in option to run the unit tests (which in turn run the JUnit Runner). A sample code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
@Test
public void multiply_isCorrect() {
Computation computation = new Computation();
assertEquals(4, computation.Multiply(2,2));
}
}
@Before annotation is used to refer a method, which needs to be invoked before running any test method available in a particular test class. For example in our sample, the Computation object can be created in a separate method and annotated with @Before so that it will run before both sum_isCorrect and multiply_isCorrect test case. The complete code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
Computation computation = null;
@Before
public void CreateComputationObject() {
this.computation = new Computation();
}
@Test
public void sum_isCorrect() {
assertEquals(4, this.computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, this.computation.Multiply(2,2));
}
}
@After is similar to @Before, but the method annotated with @After will be called or executed after each test case is run. The sample code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
Computation computation = null;
@Before
public void CreateComputationObject() {
this.computation = new Computation();
}
@After
public void DestroyComputationObject() {
this.computation = null;
}
@Test
public void sum_isCorrect() {
assertEquals(4, this.computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, this.computation.Multiply(2,2));
}
}
@BeforeClass is similar to @Before, but the method annotated with @BeforeClass will be called or executed only once before running all test cases in a particular class. It is useful to create resource intensive object like database connection object. This will reduce the time to execute a collection of test cases. This method needs to be static in order to work properly. In our sample, we can create the computation object once before running all test cases as specified below,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
private static Computation computation = null;
@BeforeClass
public static void CreateComputationObject() {
computation = new Computation();
}
@Test
public void sum_isCorrect() {
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, computation.Multiply(2,2));
}
}
@AfterClass is similar to @BeforeClass, but the method annotated with @AfterClass will be called or executed only once after all test cases in a particular class are run. This method also needs to be static to work properly. The sample code is as follows −
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
private static Computation computation = null;
@BeforeClass
public static void CreateComputationObject() {
computation = new Computation();
}
@AfterClass
public static void DestroyComputationObject() {
computation = null;
}
@Test
public void sum_isCorrect() {
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, computation.Multiply(2,2));
}
}
@Rule annotation is one of the highlights of JUnit. It is used to add behavior to the test cases. We can only annotate the fields of type TestRule. It actually provides feature set provided by @Before and @After annotation but in an efficient and reusable way. For example, we may need a temporary folder to store some data during a test case. Normally, we need to create a temporary folder before running the test case (using either @Before or @BeforeClass annotation) and destroy it after the test case is run (using either @After or @AfterClass annotation). Instead, we can use TemporaryFolder (of type TestRule) class provided by JUnit framework to create a temporary folder for all our test cases and the temporary folder will be deleted as and when the test case is run. We need to create a new variable of type TemporaryFolder and need to annotate with @Rule as specified below,
package com.tutorialspoint.espressosamples.helloworldapp;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
public class ComputationUnitTest {
private static Computation computation = null;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void file_isCreated() throws IOException {
folder.newFolder("MyTestFolder");
File testFile = folder.newFile("MyTestFile.txt");
assertTrue(testFile.exists());
}
@BeforeClass
public static void CreateComputationObject() {
computation = new Computation();
}
@AfterClass
public static void DestroyComputationObject() {
computation = null;
}
@Test
public void sum_isCorrect() {
assertEquals(4, computation.Sum(2,2));
}
@Test
public void multiply_isCorrect() {
assertEquals(4, computation.Multiply(2,2));
}
}
In JUnit, the methods annotated with different annotation will be executed in specific order as shown below,
@BeforeClass
@BeforeClass
@Rule
@Rule
@Before
@Before
@Test
@Test
@After
@After
@AfterClass
@AfterClass
Assertion is a way of checking whether the expected value of the test case matches the actual value of the test case result. JUnit provides assertion for different scenario; a few important assertions are listed below −
fail() − To explicitly make a test case fail.
fail() − To explicitly make a test case fail.
assertTrue(boolean test_condition) − Checks that the test_condition is true
assertTrue(boolean test_condition) − Checks that the test_condition is true
assertFalse(boolean test_condition) − Checks that the test_condition is false
assertFalse(boolean test_condition) − Checks that the test_condition is false
assertEquals(expected, actual) − Checks that both values are equal
assertEquals(expected, actual) − Checks that both values are equal
assertNull(object) − Checks that the object is null
assertNull(object) − Checks that the object is null
assertNotNull(object) − Checks that the object is not null
assertNotNull(object) − Checks that the object is not null
assertSame(expected, actual) − Checks that both refers same object.
assertSame(expected, actual) − Checks that both refers same object.
assertNotSame(expected, actual) − Checks that both refers different object.
assertNotSame(expected, actual) − Checks that both refers different object.
17 Lectures
1.5 hours
Anuja Jain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2151,
"s": 1976,
"text": "In this chapter, let us understand the basics of JUnit, the popular unit-testing framework developed by the Java community upon which the espresso testing framework is build."
},
{
"code": null,
"e": 2454,
"s": 2151,
"text": "JUnit is the de facto standard for unit testing a Java application. Even though, it is popular for unit testing, it has complete support and provision for instrumentation testing as well. Espresso testing library extends the necessary JUnit classes to support the Android based instrumentation testing."
},
{
"code": null,
"e": 2667,
"s": 2454,
"text": "Let us create a Java class, Computation (Computation.java) and write simple mathematical operation, Summation and Multiplication. Then, we will write test cases using JUnit and check it by running the test cases."
},
{
"code": null,
"e": 2689,
"s": 2667,
"text": "Start Android Studio."
},
{
"code": null,
"e": 2711,
"s": 2689,
"text": "Start Android Studio."
},
{
"code": null,
"e": 2763,
"s": 2711,
"text": "Open HelloWorldApp created in the previous chapter."
},
{
"code": null,
"e": 2815,
"s": 2763,
"text": "Open HelloWorldApp created in the previous chapter."
},
{
"code": null,
"e": 2981,
"s": 2815,
"text": "Create a file, Computation.java in app/src/main/java/com/tutorialspoint/espressosamples/helloworldapp/ and write two functions – Sum and Multiply as specified below,"
},
{
"code": null,
"e": 3147,
"s": 2981,
"text": "Create a file, Computation.java in app/src/main/java/com/tutorialspoint/espressosamples/helloworldapp/ and write two functions – Sum and Multiply as specified below,"
},
{
"code": null,
"e": 3384,
"s": 3147,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\npublic class Computation {\n public Computation() {}\n public int Sum(int a, int b) {\n return a + b;\n }\n public int Multiply(int a, int b) {\n return a * b;\n }\n}"
},
{
"code": null,
"e": 3578,
"s": 3384,
"text": "Create a file, ComputationUnitTest.java in app/src/test/java/com/tutorialspoint/espressosamples/helloworldapp and write unit test cases to test Sum and Multiply functionality as specified below"
},
{
"code": null,
"e": 3772,
"s": 3578,
"text": "Create a file, ComputationUnitTest.java in app/src/test/java/com/tutorialspoint/espressosamples/helloworldapp and write unit test cases to test Sum and Multiply functionality as specified below"
},
{
"code": null,
"e": 4231,
"s": 3772,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\npublic class ComputationUnitTest {\n @Test\n public void sum_isCorrect() {\n Computation computation = new Computation();\n assertEquals(4, computation.Sum(2,2));\n }\n @Test\n public void multiply_isCorrect() {\n Computation computation = new Computation();\n assertEquals(4, computation.Multiply(2,2));\n }\n}"
},
{
"code": null,
"e": 4733,
"s": 4231,
"text": "Here, we have used two new terms – @Test and assertEquals. In general, JUnit uses Java annotation to identify the test cases in a class and information on how to execute the test cases. @Test is one such Java annotation, which specifies that the particular function is a junit test case. assertEquals is a function to assert that the first argument (expected value) and the second argument (computed value) are equal and same. JUnit provides a number of assertion methods for different test scenarios."
},
{
"code": null,
"e": 4958,
"s": 4733,
"text": "Now, run the ComputationUnitTest in the Android studio by right-clicking the class and invoking the Run 'ComputationUnitTest' option as explained in the previous chapter. This will run the unit test cases and report success."
},
{
"code": null,
"e": 5183,
"s": 4958,
"text": "Now, run the ComputationUnitTest in the Android studio by right-clicking the class and invoking the Run 'ComputationUnitTest' option as explained in the previous chapter. This will run the unit test cases and report success."
},
{
"code": null,
"e": 5235,
"s": 5183,
"text": "Result of computation unit test is as shown below −"
},
{
"code": null,
"e": 5335,
"s": 5235,
"text": "The JUnit framework uses annotation extensively. Some of the important annotations are as follows −"
},
{
"code": null,
"e": 5341,
"s": 5335,
"text": "@Test"
},
{
"code": null,
"e": 5347,
"s": 5341,
"text": "@Test"
},
{
"code": null,
"e": 5355,
"s": 5347,
"text": "@Before"
},
{
"code": null,
"e": 5363,
"s": 5355,
"text": "@Before"
},
{
"code": null,
"e": 5370,
"s": 5363,
"text": "@After"
},
{
"code": null,
"e": 5377,
"s": 5370,
"text": "@After"
},
{
"code": null,
"e": 5390,
"s": 5377,
"text": "@BeforeClass"
},
{
"code": null,
"e": 5403,
"s": 5390,
"text": "@BeforeClass"
},
{
"code": null,
"e": 5415,
"s": 5403,
"text": "@AfterClass"
},
{
"code": null,
"e": 5427,
"s": 5415,
"text": "@AfterClass"
},
{
"code": null,
"e": 5433,
"s": 5427,
"text": "@Rule"
},
{
"code": null,
"e": 5439,
"s": 5433,
"text": "@Rule"
},
{
"code": null,
"e": 5979,
"s": 5439,
"text": "@Test is the very important annotation in the JUnit framework. @Test is used to differentiate a normal method from the test case method. Once a method is decorated with @Test annotation, then that particular method is considered as a Test case and will be run by JUnit Runner. JUnit Runner is a special class, which is used to find and run the JUnit test cases available inside the java classes. For now, we are using Android Studio’s build in option to run the unit tests (which in turn run the JUnit Runner). A sample code is as follows,"
},
{
"code": null,
"e": 6296,
"s": 5979,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class ComputationUnitTest {\n @Test\n public void multiply_isCorrect() {\n Computation computation = new Computation();\n assertEquals(4, computation.Multiply(2,2));\n }\n}"
},
{
"code": null,
"e": 6663,
"s": 6296,
"text": "@Before annotation is used to refer a method, which needs to be invoked before running any test method available in a particular test class. For example in our sample, the Computation object can be created in a separate method and annotated with @Before so that it will run before both sum_isCorrect and multiply_isCorrect test case. The complete code is as follows,"
},
{
"code": null,
"e": 7194,
"s": 6663,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\nimport org.junit.Before;\nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class ComputationUnitTest {\n Computation computation = null;\n @Before\n public void CreateComputationObject() {\n this.computation = new Computation();\n }\n @Test\n public void sum_isCorrect() {\n assertEquals(4, this.computation.Sum(2,2));\n }\n @Test\n public void multiply_isCorrect() {\n assertEquals(4, this.computation.Multiply(2,2));\n }\n}"
},
{
"code": null,
"e": 7348,
"s": 7194,
"text": "@After is similar to @Before, but the method annotated with @After will be called or executed after each test case is run. The sample code is as follows,"
},
{
"code": null,
"e": 7993,
"s": 7348,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class ComputationUnitTest {\n Computation computation = null;\n @Before\n public void CreateComputationObject() {\n this.computation = new Computation();\n }\n @After\n public void DestroyComputationObject() {\n this.computation = null;\n }\n @Test\n public void sum_isCorrect() {\n assertEquals(4, this.computation.Sum(2,2));\n }\n @Test\n public void multiply_isCorrect() {\n assertEquals(4, this.computation.Multiply(2,2));\n }\n}"
},
{
"code": null,
"e": 8474,
"s": 7993,
"text": "@BeforeClass is similar to @Before, but the method annotated with @BeforeClass will be called or executed only once before running all test cases in a particular class. It is useful to create resource intensive object like database connection object. This will reduce the time to execute a collection of test cases. This method needs to be static in order to work properly. In our sample, we can create the computation object once before running all test cases as specified below,"
},
{
"code": null,
"e": 9022,
"s": 8474,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class ComputationUnitTest {\n private static Computation computation = null;\n @BeforeClass\n public static void CreateComputationObject() {\n computation = new Computation();\n }\n @Test\n public void sum_isCorrect() {\n assertEquals(4, computation.Sum(2,2));\n }\n @Test\n public void multiply_isCorrect() {\n assertEquals(4, computation.Multiply(2,2));\n }\n}"
},
{
"code": null,
"e": 9279,
"s": 9022,
"text": "@AfterClass is similar to @BeforeClass, but the method annotated with @AfterClass will be called or executed only once after all test cases in a particular class are run. This method also needs to be static to work properly. The sample code is as follows −"
},
{
"code": null,
"e": 9953,
"s": 9279,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport static org.junit.Assert.assertEquals;\n\npublic class ComputationUnitTest {\n private static Computation computation = null;\n @BeforeClass\n public static void CreateComputationObject() {\n computation = new Computation();\n }\n @AfterClass\n public static void DestroyComputationObject() {\n computation = null;\n }\n @Test\n public void sum_isCorrect() {\n assertEquals(4, computation.Sum(2,2));\n }\n @Test\n public void multiply_isCorrect() {\n assertEquals(4, computation.Multiply(2,2));\n }\n}"
},
{
"code": null,
"e": 10839,
"s": 9953,
"text": "@Rule annotation is one of the highlights of JUnit. It is used to add behavior to the test cases. We can only annotate the fields of type TestRule. It actually provides feature set provided by @Before and @After annotation but in an efficient and reusable way. For example, we may need a temporary folder to store some data during a test case. Normally, we need to create a temporary folder before running the test case (using either @Before or @BeforeClass annotation) and destroy it after the test case is run (using either @After or @AfterClass annotation). Instead, we can use TemporaryFolder (of type TestRule) class provided by JUnit framework to create a temporary folder for all our test cases and the temporary folder will be deleted as and when the test case is run. We need to create a new variable of type TemporaryFolder and need to annotate with @Rule as specified below,"
},
{
"code": null,
"e": 11944,
"s": 10839,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.TemporaryFolder;\nimport java.io.File;\nimport java.io.IOException;\nimport static junit.framework.TestCase.assertTrue;\nimport static org.junit.Assert.assertEquals;\n\npublic class ComputationUnitTest {\n private static Computation computation = null;\n @Rule\n public TemporaryFolder folder = new TemporaryFolder();\n @Test\n public void file_isCreated() throws IOException {\n folder.newFolder(\"MyTestFolder\");\n File testFile = folder.newFile(\"MyTestFile.txt\");\n assertTrue(testFile.exists());\n }\n @BeforeClass\n public static void CreateComputationObject() {\n computation = new Computation();\n }\n @AfterClass\n public static void DestroyComputationObject() {\n computation = null;\n }\n @Test\n public void sum_isCorrect() {\n assertEquals(4, computation.Sum(2,2));\n }\n @Test\n public void multiply_isCorrect() {\n assertEquals(4, computation.Multiply(2,2));\n }\n}"
},
{
"code": null,
"e": 12053,
"s": 11944,
"text": "In JUnit, the methods annotated with different annotation will be executed in specific order as shown below,"
},
{
"code": null,
"e": 12066,
"s": 12053,
"text": "@BeforeClass"
},
{
"code": null,
"e": 12079,
"s": 12066,
"text": "@BeforeClass"
},
{
"code": null,
"e": 12085,
"s": 12079,
"text": "@Rule"
},
{
"code": null,
"e": 12091,
"s": 12085,
"text": "@Rule"
},
{
"code": null,
"e": 12099,
"s": 12091,
"text": "@Before"
},
{
"code": null,
"e": 12107,
"s": 12099,
"text": "@Before"
},
{
"code": null,
"e": 12113,
"s": 12107,
"text": "@Test"
},
{
"code": null,
"e": 12119,
"s": 12113,
"text": "@Test"
},
{
"code": null,
"e": 12126,
"s": 12119,
"text": "@After"
},
{
"code": null,
"e": 12133,
"s": 12126,
"text": "@After"
},
{
"code": null,
"e": 12145,
"s": 12133,
"text": "@AfterClass"
},
{
"code": null,
"e": 12157,
"s": 12145,
"text": "@AfterClass"
},
{
"code": null,
"e": 12377,
"s": 12157,
"text": "Assertion is a way of checking whether the expected value of the test case matches the actual value of the test case result. JUnit provides assertion for different scenario; a few important assertions are listed below −"
},
{
"code": null,
"e": 12423,
"s": 12377,
"text": "fail() − To explicitly make a test case fail."
},
{
"code": null,
"e": 12469,
"s": 12423,
"text": "fail() − To explicitly make a test case fail."
},
{
"code": null,
"e": 12545,
"s": 12469,
"text": "assertTrue(boolean test_condition) − Checks that the test_condition is true"
},
{
"code": null,
"e": 12621,
"s": 12545,
"text": "assertTrue(boolean test_condition) − Checks that the test_condition is true"
},
{
"code": null,
"e": 12699,
"s": 12621,
"text": "assertFalse(boolean test_condition) − Checks that the test_condition is false"
},
{
"code": null,
"e": 12777,
"s": 12699,
"text": "assertFalse(boolean test_condition) − Checks that the test_condition is false"
},
{
"code": null,
"e": 12844,
"s": 12777,
"text": "assertEquals(expected, actual) − Checks that both values are equal"
},
{
"code": null,
"e": 12911,
"s": 12844,
"text": "assertEquals(expected, actual) − Checks that both values are equal"
},
{
"code": null,
"e": 12963,
"s": 12911,
"text": "assertNull(object) − Checks that the object is null"
},
{
"code": null,
"e": 13015,
"s": 12963,
"text": "assertNull(object) − Checks that the object is null"
},
{
"code": null,
"e": 13074,
"s": 13015,
"text": "assertNotNull(object) − Checks that the object is not null"
},
{
"code": null,
"e": 13133,
"s": 13074,
"text": "assertNotNull(object) − Checks that the object is not null"
},
{
"code": null,
"e": 13201,
"s": 13133,
"text": "assertSame(expected, actual) − Checks that both refers same object."
},
{
"code": null,
"e": 13269,
"s": 13201,
"text": "assertSame(expected, actual) − Checks that both refers same object."
},
{
"code": null,
"e": 13345,
"s": 13269,
"text": "assertNotSame(expected, actual) − Checks that both refers different object."
},
{
"code": null,
"e": 13421,
"s": 13345,
"text": "assertNotSame(expected, actual) − Checks that both refers different object."
},
{
"code": null,
"e": 13456,
"s": 13421,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13468,
"s": 13456,
"text": " Anuja Jain"
},
{
"code": null,
"e": 13475,
"s": 13468,
"text": " Print"
},
{
"code": null,
"e": 13486,
"s": 13475,
"text": " Add Notes"
}
] |
Pairwise Sequence Alignment using Biopython | by Vijini Mallawaarachchi | Towards Data Science | How similar are two sequences?
If you want to answer this question, you need to have a basic idea about sequence alignment. As described in my previous article, Sequence alignment is a method of arranging sequences of DNA, RNA, or protein to identify regions of similarity. The similarity being identified, may be a result of functional, structural, or evolutionary relationships between the sequences.
In this article, I will be walking you through pairwise sequence alignment. Furthermore, we will be trying out some coding with a cool python tool known as Biopython.
Pairwise sequence alignment is one form of sequence alignment technique, where we compare only two sequences. This process involves finding the optimal alignment between the two sequences, scoring based on their similarity (how similar they are) or distance (how different they are), and then assessing the significance of this score.
Before moving on to the pairwise sequence alignment techniques, let’s go through the process of scoring.
The basis of sequence alignment lies with the scoring process, where the two sequences are given a score on how similar (or different) they are to each other. The pairwise sequence aligning algorithms require a scoring matrix to keep track of the scores assigned. The scoring matrix assigns a positive score for a match, and a penalty for a mismatch.
Three basic aspects are considered when assigning scores. They are,
Match value — Value assigned for matching charactersMismatch value — Value assigned for mismatching charactersGap penalty — Value assigned for spaces
Match value — Value assigned for matching characters
Mismatch value — Value assigned for mismatching characters
Gap penalty — Value assigned for spaces
The Figure 3 given below shows how you can identify a match, mismatch and a gap among two sequences.
The first character of the two sequences is a match, as both are letter A. Second character of the first sequence is C and that of the second sequence is T. So, it is mismatch.
A space is introduced at the end of the second sequence to match with G. This space is known as a gap. A gap is the maximal contiguous run of spaces in a single sequence within a given alignment.
In general, a gap is expressed as a gap penalty function which is a function that measures the cost of a gap as a (possibly nonlinear) function of its length.
Consider that you are given two sequences as below.
X = x1 ... xi ... xnY = y1 ... yj ... ym
Global alignment: This method finds the best alignment over the entire lengths of the 2 sequences. What is the maximum similarity between sequence X and Y?Local alignment: This method finds the most similar subsequences among the 2 sequences. What is the maximum similarity between a subsequence of X and a subsequence of Y?
Global alignment: This method finds the best alignment over the entire lengths of the 2 sequences. What is the maximum similarity between sequence X and Y?
Local alignment: This method finds the most similar subsequences among the 2 sequences. What is the maximum similarity between a subsequence of X and a subsequence of Y?
In this method, we consider the entire length of the 2 sequences and try to match them to obtain the best alignment. It is obtained by inserting gaps (spaces) to X and Y until the length of the two sequences will be the same so that the two sequences are matched.
For example, consider the sequences X = ACGCTGAT and Y = CAGCTAT. One possible global alignment is,
AC-GCTGAT | || ||-CAGC-TAT
Not that we have included gaps so that the strings are aligned.
If we set a scoring scheme as match score = 1, mismatch score = 0 and gap penalty = 0, then the overall score for the above alignment will be,
Score = nMatch x 1 + nMismatch x 0 + nGap x 0 = 6x1 + 1x0 + 2x0 = 6
One of the algorithms that uses dynamic programming to obtain global alignment is the Needleman-Wunsch algorithm. This algorithm was published by Needleman and Wunsch in 1970 for alignment of two protein sequences and it was the first application of dynamic programming to biological sequence analysis. The Needleman-Wunsch algorithm finds the best-scoring global alignment between two sequences.
In this method, we consider subsequences within each of the 2 sequences and try to match them to obtain the best alignment.
For example, consider 2 sequences as X=GGTCTGATG and Y=AAACGATC. Characters in bold are the subsequences to be considered. The best local alignment is,
CTGAT (in X)| |||C-GAT (in Y)
Here, one gap is introduced in order to match the 2 subsequences.
If we set a scoring scheme as match score = 1, mismatch score = 0 and gap penalty = 0, then the overall score for the above alignment will be,
Score = nMatch x 1 + nMismatch x 0 + nGap x 0 = 4x1 + 0x0 + 1x0 = 4
One of the algorithms that uses dynamic programming to obtain local alignments within two given sequences is the Smith-Waterman algorithm. Smith and Waterman published an application of dynamic programming to find the optimal local alignments in 1981. This algorithm is similar to Needleman-Wunsch algorithm, but there are slight differences with the scoring process.
We will not go into details of the above two algorithms in this article.
Since we have a basic idea about pairwise sequence alignment and two useful algorithms, it is time to try out some coding.
In this article, I am going to introduce you to set of tools which we will use to play around with biological data from hereafter. Biopython is a set of tools written in Python which can be used for a variety of biological computations, simulations and analysis.
You can download and install Biopython from here. Make sure that you have Python 2.7, 3.4, 3.5, or 3.6 already installed. You can refer the Biopython Tutorial and Cookbook for further details on what we can do and how to use these tools.
Let’s try out some coding to simulate pairwise sequence alignment using Biopython. I will be using pairwise2 module which can be found in the Bio package. This module provides alignment functions to get global and local alignments between two sequences.
The names of the alignment functions follow the convention;
<alignment type>XX
where <alignment type> is either global or local and XX is a 2 character code indicating the parameters it takes. The first character indicates the parameters for matches (and mismatches), and the second indicates the parameters for gap penalties.
The match parameters are:
CODE DESCRIPTIONx No parameters. Identical characters have score of 1, else 0.m A match score is the score of identical chars, else mismatch score.d A dictionary returns the score of any pair of characters.c A callback function returns scores.
The gap penalty parameters are:
CODE DESCRIPTIONx No gap penalties.s Same open and extend gap penalties for both sequences.d The sequences have different open and extend gap penalties.c A callback function returns the gap penalties.
Let’s try out a few examples of pairwise sequence alignments using Bio.pairwise2 module.
Consider two sequences given below. We want to find out all the possible global alignments with the maximum similarity score.
X = ACGGGTY = ACG
Given below is the python code to get the global alignments for the given two sequences. Note how we have used Bio.pairwise2 module and its functionality.
By running the code, we can get all the possible global alignments as given below in Figure 5.
In this example, note that matching characters have been given 1 point. No points have been deducted for mismatches or gaps.
Consider the two sequences given in the previous example. We want to find out all the possible local alignments with the maximum similarity score.
Given below is the python code to get the local alignments for the given two sequences.
By running the code, we can get all the possible local alignments as given below in Figure 6.
In this example, note that matching characters have been given 1 point. No points have been deducted for mismatches or gaps.
In this example, we are going to change the scoring scheme and assign values for matches, mismatches and gaps. We will be considering the same two sequences as before. We want to find out all the possible global alignments with the maximum similarity score.
Matching characters are given 2 points, 1 point is deducted for each mismatching character. 0.5 points are deducted when opening a gap, and 0.1 points are deducted when extending it.
By running the code, we can get all the possible global alignments as given below in Figure 7.
Hope you enjoyed reading this article and learned something useful and interesting.
Since I’m still very new to this field, I would like to hear your advice. 😇
Thanks for reading... 😃 | [
{
"code": null,
"e": 202,
"s": 171,
"text": "How similar are two sequences?"
},
{
"code": null,
"e": 574,
"s": 202,
"text": "If you want to answer this question, you need to have a basic idea about sequence alignment. As described in my previous article, Sequence alignment is a method of arranging sequences of DNA, RNA, or protein to identify regions of similarity. The similarity being identified, may be a result of functional, structural, or evolutionary relationships between the sequences."
},
{
"code": null,
"e": 741,
"s": 574,
"text": "In this article, I will be walking you through pairwise sequence alignment. Furthermore, we will be trying out some coding with a cool python tool known as Biopython."
},
{
"code": null,
"e": 1076,
"s": 741,
"text": "Pairwise sequence alignment is one form of sequence alignment technique, where we compare only two sequences. This process involves finding the optimal alignment between the two sequences, scoring based on their similarity (how similar they are) or distance (how different they are), and then assessing the significance of this score."
},
{
"code": null,
"e": 1181,
"s": 1076,
"text": "Before moving on to the pairwise sequence alignment techniques, let’s go through the process of scoring."
},
{
"code": null,
"e": 1532,
"s": 1181,
"text": "The basis of sequence alignment lies with the scoring process, where the two sequences are given a score on how similar (or different) they are to each other. The pairwise sequence aligning algorithms require a scoring matrix to keep track of the scores assigned. The scoring matrix assigns a positive score for a match, and a penalty for a mismatch."
},
{
"code": null,
"e": 1600,
"s": 1532,
"text": "Three basic aspects are considered when assigning scores. They are,"
},
{
"code": null,
"e": 1750,
"s": 1600,
"text": "Match value — Value assigned for matching charactersMismatch value — Value assigned for mismatching charactersGap penalty — Value assigned for spaces"
},
{
"code": null,
"e": 1803,
"s": 1750,
"text": "Match value — Value assigned for matching characters"
},
{
"code": null,
"e": 1862,
"s": 1803,
"text": "Mismatch value — Value assigned for mismatching characters"
},
{
"code": null,
"e": 1902,
"s": 1862,
"text": "Gap penalty — Value assigned for spaces"
},
{
"code": null,
"e": 2003,
"s": 1902,
"text": "The Figure 3 given below shows how you can identify a match, mismatch and a gap among two sequences."
},
{
"code": null,
"e": 2180,
"s": 2003,
"text": "The first character of the two sequences is a match, as both are letter A. Second character of the first sequence is C and that of the second sequence is T. So, it is mismatch."
},
{
"code": null,
"e": 2376,
"s": 2180,
"text": "A space is introduced at the end of the second sequence to match with G. This space is known as a gap. A gap is the maximal contiguous run of spaces in a single sequence within a given alignment."
},
{
"code": null,
"e": 2535,
"s": 2376,
"text": "In general, a gap is expressed as a gap penalty function which is a function that measures the cost of a gap as a (possibly nonlinear) function of its length."
},
{
"code": null,
"e": 2587,
"s": 2535,
"text": "Consider that you are given two sequences as below."
},
{
"code": null,
"e": 2628,
"s": 2587,
"text": "X = x1 ... xi ... xnY = y1 ... yj ... ym"
},
{
"code": null,
"e": 2953,
"s": 2628,
"text": "Global alignment: This method finds the best alignment over the entire lengths of the 2 sequences. What is the maximum similarity between sequence X and Y?Local alignment: This method finds the most similar subsequences among the 2 sequences. What is the maximum similarity between a subsequence of X and a subsequence of Y?"
},
{
"code": null,
"e": 3109,
"s": 2953,
"text": "Global alignment: This method finds the best alignment over the entire lengths of the 2 sequences. What is the maximum similarity between sequence X and Y?"
},
{
"code": null,
"e": 3279,
"s": 3109,
"text": "Local alignment: This method finds the most similar subsequences among the 2 sequences. What is the maximum similarity between a subsequence of X and a subsequence of Y?"
},
{
"code": null,
"e": 3543,
"s": 3279,
"text": "In this method, we consider the entire length of the 2 sequences and try to match them to obtain the best alignment. It is obtained by inserting gaps (spaces) to X and Y until the length of the two sequences will be the same so that the two sequences are matched."
},
{
"code": null,
"e": 3643,
"s": 3543,
"text": "For example, consider the sequences X = ACGCTGAT and Y = CAGCTAT. One possible global alignment is,"
},
{
"code": null,
"e": 3671,
"s": 3643,
"text": "AC-GCTGAT | || ||-CAGC-TAT"
},
{
"code": null,
"e": 3735,
"s": 3671,
"text": "Not that we have included gaps so that the strings are aligned."
},
{
"code": null,
"e": 3878,
"s": 3735,
"text": "If we set a scoring scheme as match score = 1, mismatch score = 0 and gap penalty = 0, then the overall score for the above alignment will be,"
},
{
"code": null,
"e": 3956,
"s": 3878,
"text": "Score = nMatch x 1 + nMismatch x 0 + nGap x 0 = 6x1 + 1x0 + 2x0 = 6"
},
{
"code": null,
"e": 4353,
"s": 3956,
"text": "One of the algorithms that uses dynamic programming to obtain global alignment is the Needleman-Wunsch algorithm. This algorithm was published by Needleman and Wunsch in 1970 for alignment of two protein sequences and it was the first application of dynamic programming to biological sequence analysis. The Needleman-Wunsch algorithm finds the best-scoring global alignment between two sequences."
},
{
"code": null,
"e": 4477,
"s": 4353,
"text": "In this method, we consider subsequences within each of the 2 sequences and try to match them to obtain the best alignment."
},
{
"code": null,
"e": 4629,
"s": 4477,
"text": "For example, consider 2 sequences as X=GGTCTGATG and Y=AAACGATC. Characters in bold are the subsequences to be considered. The best local alignment is,"
},
{
"code": null,
"e": 4659,
"s": 4629,
"text": "CTGAT (in X)| |||C-GAT (in Y)"
},
{
"code": null,
"e": 4725,
"s": 4659,
"text": "Here, one gap is introduced in order to match the 2 subsequences."
},
{
"code": null,
"e": 4868,
"s": 4725,
"text": "If we set a scoring scheme as match score = 1, mismatch score = 0 and gap penalty = 0, then the overall score for the above alignment will be,"
},
{
"code": null,
"e": 4946,
"s": 4868,
"text": "Score = nMatch x 1 + nMismatch x 0 + nGap x 0 = 4x1 + 0x0 + 1x0 = 4"
},
{
"code": null,
"e": 5314,
"s": 4946,
"text": "One of the algorithms that uses dynamic programming to obtain local alignments within two given sequences is the Smith-Waterman algorithm. Smith and Waterman published an application of dynamic programming to find the optimal local alignments in 1981. This algorithm is similar to Needleman-Wunsch algorithm, but there are slight differences with the scoring process."
},
{
"code": null,
"e": 5387,
"s": 5314,
"text": "We will not go into details of the above two algorithms in this article."
},
{
"code": null,
"e": 5510,
"s": 5387,
"text": "Since we have a basic idea about pairwise sequence alignment and two useful algorithms, it is time to try out some coding."
},
{
"code": null,
"e": 5773,
"s": 5510,
"text": "In this article, I am going to introduce you to set of tools which we will use to play around with biological data from hereafter. Biopython is a set of tools written in Python which can be used for a variety of biological computations, simulations and analysis."
},
{
"code": null,
"e": 6011,
"s": 5773,
"text": "You can download and install Biopython from here. Make sure that you have Python 2.7, 3.4, 3.5, or 3.6 already installed. You can refer the Biopython Tutorial and Cookbook for further details on what we can do and how to use these tools."
},
{
"code": null,
"e": 6265,
"s": 6011,
"text": "Let’s try out some coding to simulate pairwise sequence alignment using Biopython. I will be using pairwise2 module which can be found in the Bio package. This module provides alignment functions to get global and local alignments between two sequences."
},
{
"code": null,
"e": 6325,
"s": 6265,
"text": "The names of the alignment functions follow the convention;"
},
{
"code": null,
"e": 6345,
"s": 6325,
"text": "<alignment type>XX "
},
{
"code": null,
"e": 6593,
"s": 6345,
"text": "where <alignment type> is either global or local and XX is a 2 character code indicating the parameters it takes. The first character indicates the parameters for matches (and mismatches), and the second indicates the parameters for gap penalties."
},
{
"code": null,
"e": 6619,
"s": 6593,
"text": "The match parameters are:"
},
{
"code": null,
"e": 6885,
"s": 6619,
"text": "CODE DESCRIPTIONx No parameters. Identical characters have score of 1, else 0.m A match score is the score of identical chars, else mismatch score.d A dictionary returns the score of any pair of characters.c A callback function returns scores."
},
{
"code": null,
"e": 6917,
"s": 6885,
"text": "The gap penalty parameters are:"
},
{
"code": null,
"e": 7135,
"s": 6917,
"text": "CODE DESCRIPTIONx No gap penalties.s Same open and extend gap penalties for both sequences.d The sequences have different open and extend gap penalties.c A callback function returns the gap penalties."
},
{
"code": null,
"e": 7224,
"s": 7135,
"text": "Let’s try out a few examples of pairwise sequence alignments using Bio.pairwise2 module."
},
{
"code": null,
"e": 7350,
"s": 7224,
"text": "Consider two sequences given below. We want to find out all the possible global alignments with the maximum similarity score."
},
{
"code": null,
"e": 7368,
"s": 7350,
"text": "X = ACGGGTY = ACG"
},
{
"code": null,
"e": 7523,
"s": 7368,
"text": "Given below is the python code to get the global alignments for the given two sequences. Note how we have used Bio.pairwise2 module and its functionality."
},
{
"code": null,
"e": 7618,
"s": 7523,
"text": "By running the code, we can get all the possible global alignments as given below in Figure 5."
},
{
"code": null,
"e": 7743,
"s": 7618,
"text": "In this example, note that matching characters have been given 1 point. No points have been deducted for mismatches or gaps."
},
{
"code": null,
"e": 7890,
"s": 7743,
"text": "Consider the two sequences given in the previous example. We want to find out all the possible local alignments with the maximum similarity score."
},
{
"code": null,
"e": 7978,
"s": 7890,
"text": "Given below is the python code to get the local alignments for the given two sequences."
},
{
"code": null,
"e": 8072,
"s": 7978,
"text": "By running the code, we can get all the possible local alignments as given below in Figure 6."
},
{
"code": null,
"e": 8197,
"s": 8072,
"text": "In this example, note that matching characters have been given 1 point. No points have been deducted for mismatches or gaps."
},
{
"code": null,
"e": 8455,
"s": 8197,
"text": "In this example, we are going to change the scoring scheme and assign values for matches, mismatches and gaps. We will be considering the same two sequences as before. We want to find out all the possible global alignments with the maximum similarity score."
},
{
"code": null,
"e": 8638,
"s": 8455,
"text": "Matching characters are given 2 points, 1 point is deducted for each mismatching character. 0.5 points are deducted when opening a gap, and 0.1 points are deducted when extending it."
},
{
"code": null,
"e": 8733,
"s": 8638,
"text": "By running the code, we can get all the possible global alignments as given below in Figure 7."
},
{
"code": null,
"e": 8817,
"s": 8733,
"text": "Hope you enjoyed reading this article and learned something useful and interesting."
},
{
"code": null,
"e": 8893,
"s": 8817,
"text": "Since I’m still very new to this field, I would like to hear your advice. 😇"
}
] |
Full Stack Machine Learning on Azure | by Doug Foo | Towards Data Science | Guide to building a Full Stack Machine Learning site on Azure using MERN (Mongo, Express, React (Node.js))
Having gotten rusty on the latest tech, I took it upon myself to concurrently learn a whole bunch of things at once and build http://diamonds.foostack.ai which is now live. (Basic machine learning app to price diamonds).
My idea came after my gf asked me to buy her a diamond ring... I told the gf “NO wait !!! I have to build a pricing app/site first... (try that at home)”
Outline of steps and chapters in this blog:
Sourcing data using PythonTraining the ML model in Jupyter Notebooks w/ ScikitLearnDeploying ML models to AzureBuilding Front End on React w/ ExpressBuilding backend Express, MongoDBAzure Web App Deployment & CI/CDSummary, Tips and Tricks
Sourcing data using Python
Training the ML model in Jupyter Notebooks w/ ScikitLearn
Deploying ML models to Azure
Building Front End on React w/ Express
Building backend Express, MongoDB
Azure Web App Deployment & CI/CD
Summary, Tips and Tricks
Looking back at my github check-ins, the project took me 1 month (26 days) — probably spending ~8–10hrs a week, so probably ~40hrs+. The end product isn’t too shabby:
I searched the web for good diamond data. I found:
Kaggle’s diamond dataset has 50k rows but it seemed to be lacking real world pricing accuracy when cross comparing to other datasets I found.
Other “experimental datasets” were old or similarly not in synch w/ current prices.
A few commercial vendors sell updated diamond inventory/price data but I wasn’t willing pay.
Retail websites had data, but it’d require scraping (bluenile.com, rarecarat.com, etc)
Solution: Reinforced by breaking news that scraping is not illegal — I am scraping BLUENILE.COM — (thanks Andrew Marder for the starter code).
Andrews code mostly worked, except:
It was written in Python 2.7 so had a few issues
Data format on website changed since he wrote it
Bluenile evolved and as of now blocks leechers running such scripts
My only hack/contrib was to add retry loops when they kept shutting me off:
# (bluenile API restricts to 1,000 page chunks at a time)home = requests.get('http://www.bluenile.com/')while True: url = 'http://www.bluenile.com/api/public/diamond-search-grid/v2' try: response = requests.get(url, params, cookies=home.cookies) except: # request api exception, usually timeout time.sleep(60*30) next if (response.ok == False): # server may have disconnected us time.sleep(60*30) next else: # all going well time.sleep(60*4) next
The original script did inline cleanup —I opted to cleanup downstream (often a bad idea).
Output example 1 row (note the $ comma quotes etc needing cleanup):
carat,clarity,color,culet,cut,date,dateSet,depth,detailsPageUrl,fluorescence,hasVisualization,id,imageUrl,lxwRatio,measurements,polish,price,pricePerCarat,sellingIndex,shapeCode,shapeName,skus,symmetry,table,v360BaseUrl,visualizationImageUrl,willArriveForHoliday['0.23'],['FL'],['D'],['None'],"[{'label': 'Ideal', 'labelSmall': 'Ideal'}]",['Sep 30'],['Oct 1'],['58.8'],./diamond-details/LD12750672,['None'],[True],LD12750672,,['1.01'],"[{'label': '4.04 x 4.00 x 2.36 mm', 'labelSmall': '4.04 x 4.00 x 2.36'}]",['Excellent'],871,"['$3,787']",0.7348354,['RD'],['Round'],['LD12750672'],['Excellent'],['60.0'],https://bluenile.v360.in/50/imaged/gia-7313767639/1/,https://bnsec.bluenile.com/bnsecure/diamondvis/gia-7313767639/still_230x230.jpg,False
In the end, my heist was successful 140,000 round diamonds! I saved these into a CSV file for the cleanup and model training.
Jupyter Notebooks are great (see my full notebook here):
Easy way to annotate my thinking as I test out different ideas — helps when revising later or passing it to someone else!
Quicker to setup and run than a VS Code proj — the ability to isolate cells and run independently is like modified REPL!
Visualization is far easier to work with since you can re-run the cell doing just the plots rather than re-run an entire program!
(Some of above could be done w/ a debugger and REPL shell, but seems cleaner & easier to reproduce in notebooks)
For data cleanup, some options:
Scrub via a python script: CSV -> scrub.py -> CSVScrub within a notebook: CSV -> notebook -> pandas/python -> CSVScrub inside a database: CSV-> MongoDB -> sqlscrubbing -> CSVUse some other tool like Alteryx, Trifacta, or Informatica
Scrub via a python script: CSV -> scrub.py -> CSV
Scrub within a notebook: CSV -> notebook -> pandas/python -> CSV
Scrub inside a database: CSV-> MongoDB -> sqlscrubbing -> CSV
Use some other tool like Alteryx, Trifacta, or Informatica
Option #1 would work, but why have another script/env to deal with. #2 seemed like the right approach since we are using Python and Notebooks for ML after. #3 sounds like we are deferring the inevitable and rather not put junk into a DB. #4 not a real option for poor people like me.
Scrubbing Using Pandas & DataFrames
Pandas is amazing stuff. Loading up my CSV is easy and describe() on a dataframe shows some basic stats:
import pandas as pddiamonds5 = pd.read_csv('./blue-nile-download-round-full.csv')diamonds5.describe()
As mentioned earlier the data has some problems this is my checklist of data related pre-training tasks:
Determine what columns to use in prod modelConvert text to clean text (ie, remove the [])Convert numerics properly (remove $ and , and remove [] and ‘’)Handle null or out of range values in key fieldsTrim down outliers (use carats ≤ 4.5 since it is sparse after that)
Determine what columns to use in prod model
Convert text to clean text (ie, remove the [])
Convert numerics properly (remove $ and , and remove [] and ‘’)
Handle null or out of range values in key fields
Trim down outliers (use carats ≤ 4.5 since it is sparse after that)
Once that is done, we do a little visual graph inspection for carats & cut (color) to price — it's so easy w/ Jupyter:
fig, ax = plt.subplots()for c, df in diamonds5a.groupby('cut'): ax.scatter(df['carat'], df['price'], label=c, s=np.pi*3)fig.set_size_inches(18.5, 10.5)
While some metrics like the shape and depth are probably valuable for prediction, I really wanted to just focus on the 4-C’s — carats, clarity, color and cut (+sku which is the ID in BlueNile). I can drop the rest.
(note, I find it annoying DataFrame has some mutator functions that change the obj in place, and some return the changed objects. seems bit inconsistent? )
# basic cleanup functionsdef cleanBracketsToF(x): return float(cleanBracketsToS(x))def cleanBracketsToS(x): return x.replace("['",'').replace("']",'')def cleanCut(str): return str[str.index('label') + 9: str.index('labelSmall')-4]df.loc[:,'carat'] = df.loc[:,'carat'].to_frame().applymap(cleanBracketsToF)...# clear nullspd.set_option('use_inf_as_na', True)df = df.loc[~df['carat'].isnull()]...
After cleaning and including just the columns needed for training we have this (1st column is the Pandas DF identifier which is internal, and skus we drop later for training but include later for display/linking back to bluenile.com):
Next we need to convert non-numerics (Cut, Color, Clarity). You have a few options on encoding:
Onehot encoding (maybe most common, convert categories to binary columns)Ordinal mapping if its ranked/sequential (ie for Color, D->0, E->1, F->2 ...) or flipped other way around (K->0, J->1, ...)
Onehot encoding (maybe most common, convert categories to binary columns)
Ordinal mapping if its ranked/sequential (ie for Color, D->0, E->1, F->2 ...) or flipped other way around (K->0, J->1, ...)
I went with Onehot using sklearn’s Pandas.get_dummies() call
cut = pd.get_dummies( diamonds5b['cut'], prefix='cut_')# result: cut__Astor Ideal', 'cut__Good', 'cut__Ideal','cut__Very Good'# do the same for color, clarity...
OneHot Encoded our data now looks like this:
One tricky thing I learned is if you encode all columns OneHot you can create a linear algebra problem of having col-linearity & being “singular” which short story screws up the model. Read this article on the Dummy Trap.
This is the net result of applying one-hot to all columns and measuring the coefficients (think of it as weights of each feature):
Exact weights below from reg._coeff
coefficients: [ 1122.35088004 -957.70046613 471.56252273 3604.24362627 3443.65378177 3128.96414383 2340.71261083 1717.39519952 1673.9767721 590.1060328 10566.54997464 1383.32878002 -1131.5953868 -1340.53213295 -457.74564551 -848.77484115 540.46973926 15014.89306894]intercept: -8389.974398175218
What this means is the linear prediction model is heavily based on carat (makes sense), and flawless diamonds. The equation results in something like:
y = -8389 + 1122*(cut == Astor ? 1: 0) + ..... + carat*15014)....
Ie if we are pricing a 1.0 carat, cut Ideal, color G, clarity VVS1, the calc is:
y = -8389 + 1*15014 (carats)+ 1*471 (cut)+ 1*2340 (color)+ 1*540 (clarity) = $9,976
To train a model in SKLearn — most of the code is like this. Caveat — you can spend a lot of time debugging wrong shapes & orientation of your arrays & matrices!
regr = linear_model.LinearRegression()regr.fit(X_train, y_train) # trainingy_pred = regr.predict(X_test) # inferencer2score = regr.score(X_test, y_test) # get r2 score
R2 score is worth mentioning — it is not an “accuracy” score so don’t expect to get 99%. It is a measure of accuracy/variance, read more here @ R2 Wiki.
I tested other SKLearn models: ridge regression, lasso regression, isotonic regression (single feature on carat), elastic regular regression. Newer AutoML frameworks (H2O, DataRobot, Azure AutoML, SageMaker, etc) test all models & hyperparams simultaneously .. putting a lot of amateur DS’s out of work..
Next I apply tree and ensemble methods again using the same dataset. The best performance (R2) after trying various hyperparam combos is no surprise XGBoost:
est = GradientBoostingRegressor(n_estimators=ne, learning_rate=lr, max_depth=md, random_state=8, loss='ls').fit(X_train, y_train)score = est.score(X_test, y_test)
See the feature weights — carat is the highest, with others having modest impact (interestingly Flawless clarity not as impactful as it was for linear regression).
Coefficients may not be optimal to determine “importance” of each feature. Shapley values appear to be more industry standard.
Once trained in notebooks, we export all the trained models for later deployment using SKLearn’s joblib library (which “pickles” or serializes files into a proprietary format (read about some bad aspects to pickling)).
joblib.dump(value=regr_full, filename='regr_model.pkl')joblib.dump(value=model, filename='xgb_model.pkl')joblib.dump(value=rfr, filename='randomforest_model.pkl')joblib.dump(value=iso_reg, filename='isoridgelineartreg_model.pkl')
Taking one step back — we have a few ways to run models in production:
Embed a pre-trained model into the backend. In our case, we are using Express (Javascript) which isn’t the best for embedding..Publish the pre-trained model somewhere (like a Python Flask container) and expose via a webservice.Use an API like Azure ML to publish and deploy into their containers.Use a framework like Azure ML Studio to design, train and publish (semi-automatically).
Embed a pre-trained model into the backend. In our case, we are using Express (Javascript) which isn’t the best for embedding..
Publish the pre-trained model somewhere (like a Python Flask container) and expose via a webservice.
Use an API like Azure ML to publish and deploy into their containers.
Use a framework like Azure ML Studio to design, train and publish (semi-automatically).
We’ll be doing #2, #3 and #4
The first step is to get set up on Azure — if this is new to you a few basic steps:
Create an account on portal.azure.comYou can get a free subscription for some period, but eventually you may need to create a paid one (with which be careful $$$).
Create an account on portal.azure.com
You can get a free subscription for some period, but eventually you may need to create a paid one (with which be careful $$$).
We can use the new Azure ML API (though you should take a look at the ML GUI Workspace — you can launch Jupyter notebooks, try their menu driven AutoML, the ML Studio Visual GUI (pic below), and other things which are constantly changing right now...
There are a few steps to setting up your services on Azure using the API
Register your models (your pickle [.pkl] files)Setup an env file & scoring callback file (.py interface)Setup the WebService (AciWebService), Model, InferenceConfig, and deploy.
Register your models (your pickle [.pkl] files)
Setup an env file & scoring callback file (.py interface)
Setup the WebService (AciWebService), Model, InferenceConfig, and deploy.
Registering is really easy, do it once per model (pkl file):
ws = Workspace.get(name='DiamondMLWS', subscription_id='****',resource_group='diamond-ml')new_model = Model.register(model_path="mymodel.pkl"model_name=name, description="mymodel descr",workspace=ws)
Env file can be generated w/ a script like this (one time):
myenv = CondaDependencies.create(conda_packages=['numpy', 'scikit-learn'])with open("myenv.yml","w") as f: f.write(myenv.serialize_to_string())
Scoring file looks like this implementing init() and run() for each model:
#score_mymodel.pydef init(): global model model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'mymodel.pkl') model = joblib.load(model_path)def run(raw_data): data = np.array(json.loads(raw_data)['data']) y_hat = model.predict(data) return y_hat.tolist()
The final step involves setting up the Service, Model, and deploying once per model:
aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1,tags={"data": "diamonds","method": "sklearn"}, description='Predict Diamonds with sklearn')ws = Workspace.get(name='DiamondMLWS', subscription_id='****', resource_group='diamond-ml')model = Model(ws, name)inference_config = InferenceConfig(runtime= "python", entry_script="score_mymodel.py", conda_file="myenv.yml")service = Model.deploy(workspace=ws, name=svcname, models=[model], inference_config=inference_config, deployment_config=aciconfig)service.wait_for_deployment(show_output=True)
That is it! You should see output declaring that the service has been deployed and returns the URI to access, and check on the Azure portal to see it is there.
Running.......................ACI service creation operation finished, operation "Succeeded"http://dds2f-97f5eb5c4163.eastus.azurecontainer.io/score
That is pretty much it. The input format and output is defined by the model specifics that you created in part2. You can test the API with Postman or curl — make sure it is pricing:
POST to azure webservice — price a 1.1carat, F color, unspec cut, VVS2 clarity diamond → $11,272 is the predict!
I won’t go into details of using the GUI driven Azure ML Studio. You drag, drop, train and ultimately publishes a webservice URL (with a different input/output format). For my app I published 3 models in GUI ML Studio and 4 from SKLearn. See output of pricing requests on the web GUI:
Notice the NN model is totally whacked... not sure if I will bother fixing it...
Due to Azure ML container cost I opted to move the models to an Azure hosted Flask Python service. It is very minimal code — and cost is a fraction of Azure ML ACI [$2/day per service, so w/ 4 models deployed, it was like $8 a day.. quickly bankrupting old Doug Foo]. It was super easy to re-deploy the .pkl in Flask:
app = Flask(__name__)models = {}models['XGB2'] = joblib.load('models/sklearn_diamond_xgb_model.pkl')models['ISO'] = joblib.load('models/sklearn_diamond_iso_model.pkl')models['LR3'] = joblib.load('models/sklearn_diamond_regr_model.pkl')print('loaded models', models)@app.route('/models/<model>', methods=['POST'])def predict(model): if (models.get(model) is None): print('model not found: ',model) return jsonify("[-1]") j_data = np.array(request.get_json()['data']) y_hat = np.array2string(models[model].predict(j_data)) print('input: ',j_data, ', results:', y_hat) return y_hatif __name__ == '__main__': app.run(debug=True)
Again, there are countless stories on starting a React project & Express.js project, so I’ll skip some steps..
install express into my project folder ~/diamonds
install react, create the starter project with create-react-app in a subdir called ~/diamonds/diamond-app
for prod deployment these are merged via webpack into a single express bundle
I’m pretty familiar w/ Web dev on old stuff like Perl-CGI, Php, JSP, ASP and all those “Web 2.0” frameworks including old school AJAX. I’ve also used Django and looked closely at Angular. React is different — there is a learning curve. After a bit of struggle — I’m now a big fan! Key things to keep in mind:
Components — Coding is in JSX which looks like Javascript but is slightly different. You code components (<Tags/>) by way of a JSX Class or Function. The top level component is usually App.js is where you add your custom JSX and other components like <MyTag/>.
class MyTag extends React.Component { const constvar = "Text" render() { return (<div>Hi {constvar}</div>) }}
State — dynamic rendering flow is very different than what you may be used to. React has its own lifecycle mostly controlled by “state” (special variable) changes. Declare a set of state variables and React refreshes impacted components like magic. See below, as the value of dynamic changes the GUI component will refresh itself.
class MyTag extends React.Component { constructor(props) { super(props); this.state = { dynamic: 'Dyn txt' } } const constvar = "Const Txt"; render() { return (<div>Hi {constvar} and {this.state.dynamic} </div> )}}// equiv as a function, bit tighter ? also use MyTagfunction MyTag2() { const constvar = "Const Txt"; const [dynamic, setDynamic] = React.useState('Dyn Txt'); return (<div>Hi {constvar} and {dynamic} and <MyTag/> </div>);}
Props — props are tag attributes and children of your component/tag — a way to pass data. You can pass data down via props, but calls up need a callback function (eg myCallbackFunc defined in the caller/parent).
function MyTag2(props) { const constvar = "Const Txt"; const [dynamic, setDynamic] = React.useState('Dyn Txt'); return ( <div> Hi {constvar} and {dynamic} Hi {props.var1} <Button onClick={props.callback} /> </div>); }}function App() { function myCallbackFunc() { // do something on button click } return ( <div> <MyTag2 var1=’var' callback={myCallbackFunc}>Text</MyTag2> </div>); }}
Above example — your app root is <App/>, inside it, we call MyTag w/ “props” var1 and callback and the internal “Text”.
It takes some fiddling to learn but it is actually very elegant — try it out!
Kickstarting the UI with Material-Design
Google’s Material-UI is a component lib/framework for React that gives you great widgets & default themes so that anyone can make a site look good! I looked thru the gallery and picked the Dashboard (on the left) to start.
Material-UI has components like a <Grid> layout and <Paper> container to manage reactive/auto-resizing components. A nice side-menu <Drawer> is included.
Main things I did on top of the default Dashboard:
Set left drawer to be closed by default, added <Modal> help pop-ups for links to external sites.
Updated top bar w/ new text and replaced notification bell w/ Help
Implemented 3 main “paper” containers in the Grid: Random Diamond, Inventory Chooser/Filter, and the ML Pricer.
This is the easiest one to build. Assuming a server REST endpoint exists at /diamonds/daily/ which returns a json (data.price, data.carat, etc..) — we just fetch on component load (useEffect()) and set the state variables from results.
export default function Daily() { const [diamond, setDiamond] = useState({ price:0.0,carat:0.0,color:'',cut:'',clarity: '',skus: '' }); useEffect(() => { axios.get('/diamonds/daily/').then(response => { setDiamond({ price: response.data.price, carat: response.data.carat, ... }); })}, []); return ( <React.Fragment><Title>Random Diamond Featured</Title> <Typography>Price: {diamond.price}</Typography> <Typography>Carats: {diamond.carat}</Typography> ... </React.Fragment> );}
I wanted a basic search form to let me filter thru the 140k diamonds — graph + details in a table.
I choose Victory for my graphing/plotting since it works w/ ReactNative (also in consideration was React-Viz and Re-Chart). I didn’t like the material-ui data table (lack of higher level abstraction) so went with the smaller open-source Material-Table project. Lots of components you can pick from out there in React-land!
Main steps in creating this component:
Using Material-UI Form components, added checkboxes into form groups and implementing a Slider for carats.Implement the onClick of the SearchButtonMock or build your backend to return a JSON of diamonds in a list which we render in a graph + table (via tabs) — more in Part 5
Using Material-UI Form components, added checkboxes into form groups and implementing a Slider for carats.
Implement the onClick of the SearchButton
Mock or build your backend to return a JSON of diamonds in a list which we render in a graph + table (via tabs) — more in Part 5
Refer to github for full source. Below shows how the options are passed to the server:
class Chooser extends Component { constructor(props) { super(props); this.state = { D: true, E: true, F: true, G: true, H: true, AstorIdeal: false, Ideal: true, diamonds: [], ... } handleSubmit = event => { // call REST api, setState of return diamonds[] etc } render() { return ( <React.Fragment > <Title>Filter Diamonds</Title> <FormControl component="fieldset" > ... checkboxes and button </FormControl> <Paper square className={classes.root}> <Chart diamonds={this.state.diamonds}/> <DiamondsTable diamonds={this.state.diamonds} /> </Paper> </React.Fragment> )}
DiamondsTable is a 3rd party table component to view a grid of data. Just pass the diamonds[] as a prop. Any change in the diamonds[] state and it forces re-rendering on its own. React refresh magic !
We are close to the goal — to predict diamond pricing based on the 140k diamonds in our training set.
The control is really simple — much like the Filter/Chooser, we have a basic form and button.
Code structure is very similar:
FormGroup and Button with a submitPrice callbacksubmitPrice calls a REST service passing the inputs {carat, clarity, cut, color} and returning a list of diamonds[] which are set as state variables.diamonds[] are passed to the charts and tables as props.The initial and any subsequent change in diamonds[] state triggers re-rendering of sub-components using diamonds[].
FormGroup and Button with a submitPrice callback
submitPrice calls a REST service passing the inputs {carat, clarity, cut, color} and returning a list of diamonds[] which are set as state variables.
diamonds[] are passed to the charts and tables as props.
The initial and any subsequent change in diamonds[] state triggers re-rendering of sub-components using diamonds[].
Filter from prior step (Chooser.js) and Pricer.js are very similar. Pricer is implemented as a Function instead of a Class hence syntax has slight differences. Functions with state are new “Hooks” added to React and makes for a nice higher substitute to full classes.
Express is the JavaScript Node.js webserver. I’d still prefer backends in Python, but I guess this tutorial is MERN so I must use/learn Express (which isn’t too hard). A key advantage is re-use when you have the same front-end and back-end libraries.
Again I won’t go into basics of install. I’ll jump to the server.js script that hosts my API logic. The main REST calls I need:
GET /diamonds/daily — random diamond of the day
POST /diamonds/q/ — to fetch a list w/ some filtering criteria
POST /diamonds/q2/ — to fetch a list w/ matching the pricing criteria
POST /diamonds/price — to price diamonds using my ML models
Setup a Mongoose model for Express, create a DB and bulk load the DB.
Setup Express endpointsMongoDB free on MLab — FYI Azure has CosmoDB which is (mostly) wire compliant/compatible to MongoDB. CosmoDB cheapest plan is $24/month!
Setup Express endpoints
MongoDB free on MLab — FYI Azure has CosmoDB which is (mostly) wire compliant/compatible to MongoDB. CosmoDB cheapest plan is $24/month!
Once you create a DB, you need to upload data or hand enter them. The easiest way for me was to use a bulk loader script — requires you to install MongoDB client on your PC and point to the MLAB connect string.
mongoimport --uri mongodb://user:[email protected]:12122/diamonds --collection myc --type csv --headerline --file jsonfile.csv
Uploading 150k diamond entries was fast, a few minutes and does use close to the 0.5gb limit. All done !
2. Mongoose Model — create a script that defines a schema that matches your MongoDB collection’s JSON format:
#diamond.model.jslet Diamond = new Schema({ carat: { type: Number, default: -1 }, color: { type: String, default: 'Default' }, ...}, { collection: 'myc' });module.exports = mongoose.model('Diamond', Diamond);
3. Express.js REST Endpoints (server.js) are the next step.
There, most of it is boilerplate. Open a connection to be shared, set any alternate mappings (react path in this case), and listen to a port. In between, we create routes for various GET/POST handlers (defined in next section).
app.use(cors());app.use(bodyParser.json());mongoose.connect('mongodb://user:pass@host:port/diamonds', { useNewUrlParser: true, useUnifiedTopology: true });const connection = mongoose.connection;connection.once('open', function() { console.log("MongoDB connection established successfully");})//-- fill w/ diamondRoutes start... see below//-- fill endapp.use('/diamonds', diamondRoutes);// for webpack'd react front end app.use(express.static("./diamond-app/build")); app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "./diamond-app", "build", "index.html"));});app.listen(PORT, function() { console.log("Server is running on Port..: " + PORT);});
Next we fill in the diamondRoutes — /daily /q /q2 and /price. ‘/daily’ is easy — just a hack randomized query that returns 1 diamond (using json schema defined earlier in diamond.model.js)
diamondRoutes.route('/daily').get(function(req, res) { let random = Math.floor(Math.random() * 140000); // skip n Diamond.findOne().skip(random).exec(function(err, diamonds) { res.json(diamonds); });});
The /q and /q2 are all similar query searches that take in POST params and map to a Mongoose query — the POST input is a JSON like{carat:3, color:’D’,cut:’’,clarity:’’}
diamondRoutes.route('/q2').post(function(req, res) { const qobj = req.body; query = Diamond.find(); query = query.where('carat'). gt(qobj.carat-0.05).lt(qobj.carat+0.05); if (qobj.cut !== '') query = query.where('cut').equals(qobj.cut); if (qobj.color !== '') query = query.where('color').equals(qobj.color); if (qobj.clarity !== '') query = query.where('clarity').equals(qobj.clarity); query.exec(function(err, diamonds) { res.json(diamonds); });});
Calling /price — the Machine Learning Inference call is done via another REST API callout to Azure ML Studio’s farm (now most to an Azure Flask server).
The request chain: React Client -> Express.js -> ML Services-> back to Express.js -> back to React Client.
I think showing the code in chunks will be confusing, so just look at the key step which is to use an ‘asynch’ call to the callSvc function, then ‘await’ them all to join the results:
let r0 = await callSvc(p2.XGB.url, p2.XGB.token, reqJson);let r1 = await callSvc(p2.LR.url, p2.LR.token, reqJson);let r2 = ...
callSvc just does an axios http POST to get the ML predictions. Notice the ‘async’ def on the function, and the await call above that pairs up the async calls.
async function callSvc(apiurl, token, reqJson) { return axios.post(apiurl, reqJson, { headers: { 'Content-Type': 'application/json', 'Authorization': token, } }) .catch(function (error){ console.log(error); });}
The responses are rolled into a single response JSON for the front end, notice ML Studio format differs from my custom SKLearn models:
res.json([ { price:r0.data.Results.output1.value.Values[0][6],model:'XGB' }, { price:r1.data.Results.output1.value.Values[0][6],model:'LR' }, { price:r2.data.Results.output1.value.Values[0][6],model:'NN' }, { price: r3.data[0], model: 'ISO' }, { price: r4.data[0], model: 'XGB2' }, { price: r5.data[0], model: 'LR3' }, { price: r6.data[0], model: 'RF' },]);
See how the chain looks via POSTMAN (calling express which calls ML services aggregating the results of all 7 models):
Look at the full source code for the full story. That's mostly it — we’ve now built the express.js backend!
Deploying to an Azure site is really simple (when it works which it usually does) — and frustrating as heck when there is a build or deploy error. Good luck!
First, you should understand in development you may be running 2 servers:
React dev engine (default port 3000)Express dev server (default port 4000)
React dev engine (default port 3000)
Express dev server (default port 4000)
In prod you only run a single server (Express) and the React stuff is “bundled” into a webpack via “npm build” which results i something like this:
Your express.js has code pointing to this build/static folder
app.use(express.static("./diamond-app/build"));app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "./diamond-app", "build", "index.html"));});
Check this project into github and you are ready to go! (.gitignore the node_modules at both express.js (~diamonds) and react (~diamonds/diamond-app) levels).
Login into Azure Portal and Create the Web App
“testwebapp23” will become http://testwebapp23.azurewebsites.net so name it carefully, it can’t be changed later (you can externally DNS alias it if you own a domain). Pick the cheapest size, B1 will cost you about $15 a month!
I would check the Config panel in Azure Web App, a few things to confirm:
Next, you need to create a project in Azure DevOps (https://dev.azure.com) to host the build env. Afterward, go to the Project Settings (bottom-left) and link it to your GitHub repo, and enable Pipelines:
Pipelines will enable your CI/CD setup so check-ins to GitHub trigger a build and deployment. There are several ways to set this up and each has its pitfalls. The weird but semi-simple way is to jump back to Azure Portal and finish with their webapp->Deployment Center.
You have the choice of Kudu App Build or Azure Pipelines. Pipelines is the latest Azure CI/CD toolset (replaces TFS). Both are buggy.. but I found for node.js Pipeline deployment works better (and for Python I prefer Kudu).
Finish and this creates your first build and deployment. If you are lucky it will work and you can view your app online like this:
Jump back to Azure DevOps and you’ll see it generated a Pipeline (build) and Release (deployment):
If that passes, it goes onto Release (Deployment):
You can customize each step and add some nifty stuff like pre/post scripts or an approval flow like below to propagate changes thru your environments. A change triggers a pre-prod (Demo) build then I have to manually approve to release to PROD (diamonds.foostack.ai) once I verify the build.
My top list of things I learned and want to warn you about:
Azure Insights is great to track usage statistics (more difficult to setup than you’d think, you have to hook in code to each of your components but then you get some great telemetry)
Azure is evolving (and breaking) so be prepared to have some annoyances esp with newer things like Machine Learning and Pipelines (node.js releases on linux broke suddenly.. for weeks now the Azure team is trying to clean up the debacle):
Scrum Boards and ticket management can be done in Azure DevOps and integrates with GitHub. It is very new but not bad for a small project.
Cost Management — track it closely. The cost per Machine Learning model is a bit crazy ($2 per model container / day cost me $100+ for just 12 days). This motivated me to migrate to Flask. On another project SQL Warehouse for like 2 days was over $100 ! Be careful, set cost alarms!
Python Flask Deploy — I added this late because of the cost issue above. I used the traditional Kudu build from WebApp->Deployment rather than Azure Pipelines due to some errors I kept having w/ Azure Pipelines.
Domain name setup is really easy — Azure doesn't do this, go to namecheap.com — then just link on Azure. Very simple instructions.
Happy coding! Peruse the live http://diamonds.foostack.ai site, github project or the Jupyter notebook online.
Some rights reserved | [
{
"code": null,
"e": 279,
"s": 172,
"text": "Guide to building a Full Stack Machine Learning site on Azure using MERN (Mongo, Express, React (Node.js))"
},
{
"code": null,
"e": 500,
"s": 279,
"text": "Having gotten rusty on the latest tech, I took it upon myself to concurrently learn a whole bunch of things at once and build http://diamonds.foostack.ai which is now live. (Basic machine learning app to price diamonds)."
},
{
"code": null,
"e": 654,
"s": 500,
"text": "My idea came after my gf asked me to buy her a diamond ring... I told the gf “NO wait !!! I have to build a pricing app/site first... (try that at home)”"
},
{
"code": null,
"e": 698,
"s": 654,
"text": "Outline of steps and chapters in this blog:"
},
{
"code": null,
"e": 937,
"s": 698,
"text": "Sourcing data using PythonTraining the ML model in Jupyter Notebooks w/ ScikitLearnDeploying ML models to AzureBuilding Front End on React w/ ExpressBuilding backend Express, MongoDBAzure Web App Deployment & CI/CDSummary, Tips and Tricks"
},
{
"code": null,
"e": 964,
"s": 937,
"text": "Sourcing data using Python"
},
{
"code": null,
"e": 1022,
"s": 964,
"text": "Training the ML model in Jupyter Notebooks w/ ScikitLearn"
},
{
"code": null,
"e": 1051,
"s": 1022,
"text": "Deploying ML models to Azure"
},
{
"code": null,
"e": 1090,
"s": 1051,
"text": "Building Front End on React w/ Express"
},
{
"code": null,
"e": 1124,
"s": 1090,
"text": "Building backend Express, MongoDB"
},
{
"code": null,
"e": 1157,
"s": 1124,
"text": "Azure Web App Deployment & CI/CD"
},
{
"code": null,
"e": 1182,
"s": 1157,
"text": "Summary, Tips and Tricks"
},
{
"code": null,
"e": 1349,
"s": 1182,
"text": "Looking back at my github check-ins, the project took me 1 month (26 days) — probably spending ~8–10hrs a week, so probably ~40hrs+. The end product isn’t too shabby:"
},
{
"code": null,
"e": 1400,
"s": 1349,
"text": "I searched the web for good diamond data. I found:"
},
{
"code": null,
"e": 1542,
"s": 1400,
"text": "Kaggle’s diamond dataset has 50k rows but it seemed to be lacking real world pricing accuracy when cross comparing to other datasets I found."
},
{
"code": null,
"e": 1626,
"s": 1542,
"text": "Other “experimental datasets” were old or similarly not in synch w/ current prices."
},
{
"code": null,
"e": 1719,
"s": 1626,
"text": "A few commercial vendors sell updated diamond inventory/price data but I wasn’t willing pay."
},
{
"code": null,
"e": 1806,
"s": 1719,
"text": "Retail websites had data, but it’d require scraping (bluenile.com, rarecarat.com, etc)"
},
{
"code": null,
"e": 1949,
"s": 1806,
"text": "Solution: Reinforced by breaking news that scraping is not illegal — I am scraping BLUENILE.COM — (thanks Andrew Marder for the starter code)."
},
{
"code": null,
"e": 1985,
"s": 1949,
"text": "Andrews code mostly worked, except:"
},
{
"code": null,
"e": 2034,
"s": 1985,
"text": "It was written in Python 2.7 so had a few issues"
},
{
"code": null,
"e": 2083,
"s": 2034,
"text": "Data format on website changed since he wrote it"
},
{
"code": null,
"e": 2151,
"s": 2083,
"text": "Bluenile evolved and as of now blocks leechers running such scripts"
},
{
"code": null,
"e": 2227,
"s": 2151,
"text": "My only hack/contrib was to add retry loops when they kept shutting me off:"
},
{
"code": null,
"e": 2723,
"s": 2227,
"text": "# (bluenile API restricts to 1,000 page chunks at a time)home = requests.get('http://www.bluenile.com/')while True: url = 'http://www.bluenile.com/api/public/diamond-search-grid/v2' try: response = requests.get(url, params, cookies=home.cookies) except: # request api exception, usually timeout time.sleep(60*30) next if (response.ok == False): # server may have disconnected us time.sleep(60*30) next else: # all going well time.sleep(60*4) next"
},
{
"code": null,
"e": 2813,
"s": 2723,
"text": "The original script did inline cleanup —I opted to cleanup downstream (often a bad idea)."
},
{
"code": null,
"e": 2881,
"s": 2813,
"text": "Output example 1 row (note the $ comma quotes etc needing cleanup):"
},
{
"code": null,
"e": 3626,
"s": 2881,
"text": "carat,clarity,color,culet,cut,date,dateSet,depth,detailsPageUrl,fluorescence,hasVisualization,id,imageUrl,lxwRatio,measurements,polish,price,pricePerCarat,sellingIndex,shapeCode,shapeName,skus,symmetry,table,v360BaseUrl,visualizationImageUrl,willArriveForHoliday['0.23'],['FL'],['D'],['None'],\"[{'label': 'Ideal', 'labelSmall': 'Ideal'}]\",['Sep 30'],['Oct 1'],['58.8'],./diamond-details/LD12750672,['None'],[True],LD12750672,,['1.01'],\"[{'label': '4.04 x 4.00 x 2.36 mm', 'labelSmall': '4.04 x 4.00 x 2.36'}]\",['Excellent'],871,\"['$3,787']\",0.7348354,['RD'],['Round'],['LD12750672'],['Excellent'],['60.0'],https://bluenile.v360.in/50/imaged/gia-7313767639/1/,https://bnsec.bluenile.com/bnsecure/diamondvis/gia-7313767639/still_230x230.jpg,False"
},
{
"code": null,
"e": 3752,
"s": 3626,
"text": "In the end, my heist was successful 140,000 round diamonds! I saved these into a CSV file for the cleanup and model training."
},
{
"code": null,
"e": 3809,
"s": 3752,
"text": "Jupyter Notebooks are great (see my full notebook here):"
},
{
"code": null,
"e": 3931,
"s": 3809,
"text": "Easy way to annotate my thinking as I test out different ideas — helps when revising later or passing it to someone else!"
},
{
"code": null,
"e": 4052,
"s": 3931,
"text": "Quicker to setup and run than a VS Code proj — the ability to isolate cells and run independently is like modified REPL!"
},
{
"code": null,
"e": 4182,
"s": 4052,
"text": "Visualization is far easier to work with since you can re-run the cell doing just the plots rather than re-run an entire program!"
},
{
"code": null,
"e": 4295,
"s": 4182,
"text": "(Some of above could be done w/ a debugger and REPL shell, but seems cleaner & easier to reproduce in notebooks)"
},
{
"code": null,
"e": 4327,
"s": 4295,
"text": "For data cleanup, some options:"
},
{
"code": null,
"e": 4560,
"s": 4327,
"text": "Scrub via a python script: CSV -> scrub.py -> CSVScrub within a notebook: CSV -> notebook -> pandas/python -> CSVScrub inside a database: CSV-> MongoDB -> sqlscrubbing -> CSVUse some other tool like Alteryx, Trifacta, or Informatica"
},
{
"code": null,
"e": 4610,
"s": 4560,
"text": "Scrub via a python script: CSV -> scrub.py -> CSV"
},
{
"code": null,
"e": 4675,
"s": 4610,
"text": "Scrub within a notebook: CSV -> notebook -> pandas/python -> CSV"
},
{
"code": null,
"e": 4737,
"s": 4675,
"text": "Scrub inside a database: CSV-> MongoDB -> sqlscrubbing -> CSV"
},
{
"code": null,
"e": 4796,
"s": 4737,
"text": "Use some other tool like Alteryx, Trifacta, or Informatica"
},
{
"code": null,
"e": 5080,
"s": 4796,
"text": "Option #1 would work, but why have another script/env to deal with. #2 seemed like the right approach since we are using Python and Notebooks for ML after. #3 sounds like we are deferring the inevitable and rather not put junk into a DB. #4 not a real option for poor people like me."
},
{
"code": null,
"e": 5116,
"s": 5080,
"text": "Scrubbing Using Pandas & DataFrames"
},
{
"code": null,
"e": 5221,
"s": 5116,
"text": "Pandas is amazing stuff. Loading up my CSV is easy and describe() on a dataframe shows some basic stats:"
},
{
"code": null,
"e": 5323,
"s": 5221,
"text": "import pandas as pddiamonds5 = pd.read_csv('./blue-nile-download-round-full.csv')diamonds5.describe()"
},
{
"code": null,
"e": 5428,
"s": 5323,
"text": "As mentioned earlier the data has some problems this is my checklist of data related pre-training tasks:"
},
{
"code": null,
"e": 5696,
"s": 5428,
"text": "Determine what columns to use in prod modelConvert text to clean text (ie, remove the [])Convert numerics properly (remove $ and , and remove [] and ‘’)Handle null or out of range values in key fieldsTrim down outliers (use carats ≤ 4.5 since it is sparse after that)"
},
{
"code": null,
"e": 5740,
"s": 5696,
"text": "Determine what columns to use in prod model"
},
{
"code": null,
"e": 5787,
"s": 5740,
"text": "Convert text to clean text (ie, remove the [])"
},
{
"code": null,
"e": 5851,
"s": 5787,
"text": "Convert numerics properly (remove $ and , and remove [] and ‘’)"
},
{
"code": null,
"e": 5900,
"s": 5851,
"text": "Handle null or out of range values in key fields"
},
{
"code": null,
"e": 5968,
"s": 5900,
"text": "Trim down outliers (use carats ≤ 4.5 since it is sparse after that)"
},
{
"code": null,
"e": 6087,
"s": 5968,
"text": "Once that is done, we do a little visual graph inspection for carats & cut (color) to price — it's so easy w/ Jupyter:"
},
{
"code": null,
"e": 6242,
"s": 6087,
"text": "fig, ax = plt.subplots()for c, df in diamonds5a.groupby('cut'): ax.scatter(df['carat'], df['price'], label=c, s=np.pi*3)fig.set_size_inches(18.5, 10.5)"
},
{
"code": null,
"e": 6457,
"s": 6242,
"text": "While some metrics like the shape and depth are probably valuable for prediction, I really wanted to just focus on the 4-C’s — carats, clarity, color and cut (+sku which is the ID in BlueNile). I can drop the rest."
},
{
"code": null,
"e": 6613,
"s": 6457,
"text": "(note, I find it annoying DataFrame has some mutator functions that change the obj in place, and some return the changed objects. seems bit inconsistent? )"
},
{
"code": null,
"e": 7023,
"s": 6613,
"text": "# basic cleanup functionsdef cleanBracketsToF(x): return float(cleanBracketsToS(x))def cleanBracketsToS(x): return x.replace(\"['\",'').replace(\"']\",'')def cleanCut(str): return str[str.index('label') + 9: str.index('labelSmall')-4]df.loc[:,'carat'] = df.loc[:,'carat'].to_frame().applymap(cleanBracketsToF)...# clear nullspd.set_option('use_inf_as_na', True)df = df.loc[~df['carat'].isnull()]..."
},
{
"code": null,
"e": 7258,
"s": 7023,
"text": "After cleaning and including just the columns needed for training we have this (1st column is the Pandas DF identifier which is internal, and skus we drop later for training but include later for display/linking back to bluenile.com):"
},
{
"code": null,
"e": 7354,
"s": 7258,
"text": "Next we need to convert non-numerics (Cut, Color, Clarity). You have a few options on encoding:"
},
{
"code": null,
"e": 7551,
"s": 7354,
"text": "Onehot encoding (maybe most common, convert categories to binary columns)Ordinal mapping if its ranked/sequential (ie for Color, D->0, E->1, F->2 ...) or flipped other way around (K->0, J->1, ...)"
},
{
"code": null,
"e": 7625,
"s": 7551,
"text": "Onehot encoding (maybe most common, convert categories to binary columns)"
},
{
"code": null,
"e": 7749,
"s": 7625,
"text": "Ordinal mapping if its ranked/sequential (ie for Color, D->0, E->1, F->2 ...) or flipped other way around (K->0, J->1, ...)"
},
{
"code": null,
"e": 7810,
"s": 7749,
"text": "I went with Onehot using sklearn’s Pandas.get_dummies() call"
},
{
"code": null,
"e": 7972,
"s": 7810,
"text": "cut = pd.get_dummies( diamonds5b['cut'], prefix='cut_')# result: cut__Astor Ideal', 'cut__Good', 'cut__Ideal','cut__Very Good'# do the same for color, clarity..."
},
{
"code": null,
"e": 8017,
"s": 7972,
"text": "OneHot Encoded our data now looks like this:"
},
{
"code": null,
"e": 8239,
"s": 8017,
"text": "One tricky thing I learned is if you encode all columns OneHot you can create a linear algebra problem of having col-linearity & being “singular” which short story screws up the model. Read this article on the Dummy Trap."
},
{
"code": null,
"e": 8370,
"s": 8239,
"text": "This is the net result of applying one-hot to all columns and measuring the coefficients (think of it as weights of each feature):"
},
{
"code": null,
"e": 8406,
"s": 8370,
"text": "Exact weights below from reg._coeff"
},
{
"code": null,
"e": 8721,
"s": 8406,
"text": "coefficients: [ 1122.35088004 -957.70046613 471.56252273 3604.24362627 3443.65378177 3128.96414383 2340.71261083 1717.39519952 1673.9767721 590.1060328 10566.54997464 1383.32878002 -1131.5953868 -1340.53213295 -457.74564551 -848.77484115 540.46973926 15014.89306894]intercept: -8389.974398175218"
},
{
"code": null,
"e": 8872,
"s": 8721,
"text": "What this means is the linear prediction model is heavily based on carat (makes sense), and flawless diamonds. The equation results in something like:"
},
{
"code": null,
"e": 8938,
"s": 8872,
"text": "y = -8389 + 1122*(cut == Astor ? 1: 0) + ..... + carat*15014)...."
},
{
"code": null,
"e": 9019,
"s": 8938,
"text": "Ie if we are pricing a 1.0 carat, cut Ideal, color G, clarity VVS1, the calc is:"
},
{
"code": null,
"e": 9104,
"s": 9019,
"text": "y = -8389 + 1*15014 (carats)+ 1*471 (cut)+ 1*2340 (color)+ 1*540 (clarity) = $9,976 "
},
{
"code": null,
"e": 9266,
"s": 9104,
"text": "To train a model in SKLearn — most of the code is like this. Caveat — you can spend a lot of time debugging wrong shapes & orientation of your arrays & matrices!"
},
{
"code": null,
"e": 9463,
"s": 9266,
"text": "regr = linear_model.LinearRegression()regr.fit(X_train, y_train) # trainingy_pred = regr.predict(X_test) # inferencer2score = regr.score(X_test, y_test) # get r2 score"
},
{
"code": null,
"e": 9616,
"s": 9463,
"text": "R2 score is worth mentioning — it is not an “accuracy” score so don’t expect to get 99%. It is a measure of accuracy/variance, read more here @ R2 Wiki."
},
{
"code": null,
"e": 9921,
"s": 9616,
"text": "I tested other SKLearn models: ridge regression, lasso regression, isotonic regression (single feature on carat), elastic regular regression. Newer AutoML frameworks (H2O, DataRobot, Azure AutoML, SageMaker, etc) test all models & hyperparams simultaneously .. putting a lot of amateur DS’s out of work.."
},
{
"code": null,
"e": 10079,
"s": 9921,
"text": "Next I apply tree and ensemble methods again using the same dataset. The best performance (R2) after trying various hyperparam combos is no surprise XGBoost:"
},
{
"code": null,
"e": 10245,
"s": 10079,
"text": "est = GradientBoostingRegressor(n_estimators=ne, learning_rate=lr, max_depth=md, random_state=8, loss='ls').fit(X_train, y_train)score = est.score(X_test, y_test)"
},
{
"code": null,
"e": 10409,
"s": 10245,
"text": "See the feature weights — carat is the highest, with others having modest impact (interestingly Flawless clarity not as impactful as it was for linear regression)."
},
{
"code": null,
"e": 10536,
"s": 10409,
"text": "Coefficients may not be optimal to determine “importance” of each feature. Shapley values appear to be more industry standard."
},
{
"code": null,
"e": 10755,
"s": 10536,
"text": "Once trained in notebooks, we export all the trained models for later deployment using SKLearn’s joblib library (which “pickles” or serializes files into a proprietary format (read about some bad aspects to pickling))."
},
{
"code": null,
"e": 10985,
"s": 10755,
"text": "joblib.dump(value=regr_full, filename='regr_model.pkl')joblib.dump(value=model, filename='xgb_model.pkl')joblib.dump(value=rfr, filename='randomforest_model.pkl')joblib.dump(value=iso_reg, filename='isoridgelineartreg_model.pkl')"
},
{
"code": null,
"e": 11056,
"s": 10985,
"text": "Taking one step back — we have a few ways to run models in production:"
},
{
"code": null,
"e": 11440,
"s": 11056,
"text": "Embed a pre-trained model into the backend. In our case, we are using Express (Javascript) which isn’t the best for embedding..Publish the pre-trained model somewhere (like a Python Flask container) and expose via a webservice.Use an API like Azure ML to publish and deploy into their containers.Use a framework like Azure ML Studio to design, train and publish (semi-automatically)."
},
{
"code": null,
"e": 11568,
"s": 11440,
"text": "Embed a pre-trained model into the backend. In our case, we are using Express (Javascript) which isn’t the best for embedding.."
},
{
"code": null,
"e": 11669,
"s": 11568,
"text": "Publish the pre-trained model somewhere (like a Python Flask container) and expose via a webservice."
},
{
"code": null,
"e": 11739,
"s": 11669,
"text": "Use an API like Azure ML to publish and deploy into their containers."
},
{
"code": null,
"e": 11827,
"s": 11739,
"text": "Use a framework like Azure ML Studio to design, train and publish (semi-automatically)."
},
{
"code": null,
"e": 11856,
"s": 11827,
"text": "We’ll be doing #2, #3 and #4"
},
{
"code": null,
"e": 11940,
"s": 11856,
"text": "The first step is to get set up on Azure — if this is new to you a few basic steps:"
},
{
"code": null,
"e": 12104,
"s": 11940,
"text": "Create an account on portal.azure.comYou can get a free subscription for some period, but eventually you may need to create a paid one (with which be careful $$$)."
},
{
"code": null,
"e": 12142,
"s": 12104,
"text": "Create an account on portal.azure.com"
},
{
"code": null,
"e": 12269,
"s": 12142,
"text": "You can get a free subscription for some period, but eventually you may need to create a paid one (with which be careful $$$)."
},
{
"code": null,
"e": 12520,
"s": 12269,
"text": "We can use the new Azure ML API (though you should take a look at the ML GUI Workspace — you can launch Jupyter notebooks, try their menu driven AutoML, the ML Studio Visual GUI (pic below), and other things which are constantly changing right now..."
},
{
"code": null,
"e": 12593,
"s": 12520,
"text": "There are a few steps to setting up your services on Azure using the API"
},
{
"code": null,
"e": 12771,
"s": 12593,
"text": "Register your models (your pickle [.pkl] files)Setup an env file & scoring callback file (.py interface)Setup the WebService (AciWebService), Model, InferenceConfig, and deploy."
},
{
"code": null,
"e": 12819,
"s": 12771,
"text": "Register your models (your pickle [.pkl] files)"
},
{
"code": null,
"e": 12877,
"s": 12819,
"text": "Setup an env file & scoring callback file (.py interface)"
},
{
"code": null,
"e": 12951,
"s": 12877,
"text": "Setup the WebService (AciWebService), Model, InferenceConfig, and deploy."
},
{
"code": null,
"e": 13012,
"s": 12951,
"text": "Registering is really easy, do it once per model (pkl file):"
},
{
"code": null,
"e": 13218,
"s": 13012,
"text": "ws = Workspace.get(name='DiamondMLWS', subscription_id='****',resource_group='diamond-ml')new_model = Model.register(model_path=\"mymodel.pkl\"model_name=name, description=\"mymodel descr\",workspace=ws)"
},
{
"code": null,
"e": 13278,
"s": 13218,
"text": "Env file can be generated w/ a script like this (one time):"
},
{
"code": null,
"e": 13426,
"s": 13278,
"text": "myenv = CondaDependencies.create(conda_packages=['numpy', 'scikit-learn'])with open(\"myenv.yml\",\"w\") as f: f.write(myenv.serialize_to_string())"
},
{
"code": null,
"e": 13501,
"s": 13426,
"text": "Scoring file looks like this implementing init() and run() for each model:"
},
{
"code": null,
"e": 13781,
"s": 13501,
"text": "#score_mymodel.pydef init(): global model model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'mymodel.pkl') model = joblib.load(model_path)def run(raw_data): data = np.array(json.loads(raw_data)['data']) y_hat = model.predict(data) return y_hat.tolist()"
},
{
"code": null,
"e": 13866,
"s": 13781,
"text": "The final step involves setting up the Service, Model, and deploying once per model:"
},
{
"code": null,
"e": 14441,
"s": 13866,
"text": "aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1,tags={\"data\": \"diamonds\",\"method\": \"sklearn\"}, description='Predict Diamonds with sklearn')ws = Workspace.get(name='DiamondMLWS', subscription_id='****', resource_group='diamond-ml')model = Model(ws, name)inference_config = InferenceConfig(runtime= \"python\", entry_script=\"score_mymodel.py\", conda_file=\"myenv.yml\")service = Model.deploy(workspace=ws, name=svcname, models=[model], inference_config=inference_config, deployment_config=aciconfig)service.wait_for_deployment(show_output=True)"
},
{
"code": null,
"e": 14601,
"s": 14441,
"text": "That is it! You should see output declaring that the service has been deployed and returns the URI to access, and check on the Azure portal to see it is there."
},
{
"code": null,
"e": 14750,
"s": 14601,
"text": "Running.......................ACI service creation operation finished, operation \"Succeeded\"http://dds2f-97f5eb5c4163.eastus.azurecontainer.io/score"
},
{
"code": null,
"e": 14932,
"s": 14750,
"text": "That is pretty much it. The input format and output is defined by the model specifics that you created in part2. You can test the API with Postman or curl — make sure it is pricing:"
},
{
"code": null,
"e": 15045,
"s": 14932,
"text": "POST to azure webservice — price a 1.1carat, F color, unspec cut, VVS2 clarity diamond → $11,272 is the predict!"
},
{
"code": null,
"e": 15330,
"s": 15045,
"text": "I won’t go into details of using the GUI driven Azure ML Studio. You drag, drop, train and ultimately publishes a webservice URL (with a different input/output format). For my app I published 3 models in GUI ML Studio and 4 from SKLearn. See output of pricing requests on the web GUI:"
},
{
"code": null,
"e": 15411,
"s": 15330,
"text": "Notice the NN model is totally whacked... not sure if I will bother fixing it..."
},
{
"code": null,
"e": 15729,
"s": 15411,
"text": "Due to Azure ML container cost I opted to move the models to an Azure hosted Flask Python service. It is very minimal code — and cost is a fraction of Azure ML ACI [$2/day per service, so w/ 4 models deployed, it was like $8 a day.. quickly bankrupting old Doug Foo]. It was super easy to re-deploy the .pkl in Flask:"
},
{
"code": null,
"e": 16376,
"s": 15729,
"text": "app = Flask(__name__)models = {}models['XGB2'] = joblib.load('models/sklearn_diamond_xgb_model.pkl')models['ISO'] = joblib.load('models/sklearn_diamond_iso_model.pkl')models['LR3'] = joblib.load('models/sklearn_diamond_regr_model.pkl')print('loaded models', models)@app.route('/models/<model>', methods=['POST'])def predict(model): if (models.get(model) is None): print('model not found: ',model) return jsonify(\"[-1]\") j_data = np.array(request.get_json()['data']) y_hat = np.array2string(models[model].predict(j_data)) print('input: ',j_data, ', results:', y_hat) return y_hatif __name__ == '__main__': app.run(debug=True)"
},
{
"code": null,
"e": 16487,
"s": 16376,
"text": "Again, there are countless stories on starting a React project & Express.js project, so I’ll skip some steps.."
},
{
"code": null,
"e": 16537,
"s": 16487,
"text": "install express into my project folder ~/diamonds"
},
{
"code": null,
"e": 16643,
"s": 16537,
"text": "install react, create the starter project with create-react-app in a subdir called ~/diamonds/diamond-app"
},
{
"code": null,
"e": 16721,
"s": 16643,
"text": "for prod deployment these are merged via webpack into a single express bundle"
},
{
"code": null,
"e": 17030,
"s": 16721,
"text": "I’m pretty familiar w/ Web dev on old stuff like Perl-CGI, Php, JSP, ASP and all those “Web 2.0” frameworks including old school AJAX. I’ve also used Django and looked closely at Angular. React is different — there is a learning curve. After a bit of struggle — I’m now a big fan! Key things to keep in mind:"
},
{
"code": null,
"e": 17291,
"s": 17030,
"text": "Components — Coding is in JSX which looks like Javascript but is slightly different. You code components (<Tags/>) by way of a JSX Class or Function. The top level component is usually App.js is where you add your custom JSX and other components like <MyTag/>."
},
{
"code": null,
"e": 17407,
"s": 17291,
"text": "class MyTag extends React.Component { const constvar = \"Text\" render() { return (<div>Hi {constvar}</div>) }}"
},
{
"code": null,
"e": 17738,
"s": 17407,
"text": "State — dynamic rendering flow is very different than what you may be used to. React has its own lifecycle mostly controlled by “state” (special variable) changes. Declare a set of state variables and React refreshes impacted components like magic. See below, as the value of dynamic changes the GUI component will refresh itself."
},
{
"code": null,
"e": 18222,
"s": 17738,
"text": "class MyTag extends React.Component { constructor(props) { super(props); this.state = { dynamic: 'Dyn txt' } } const constvar = \"Const Txt\"; render() { return (<div>Hi {constvar} and {this.state.dynamic} </div> )}}// equiv as a function, bit tighter ? also use MyTagfunction MyTag2() { const constvar = \"Const Txt\"; const [dynamic, setDynamic] = React.useState('Dyn Txt'); return (<div>Hi {constvar} and {dynamic} and <MyTag/> </div>);}"
},
{
"code": null,
"e": 18434,
"s": 18222,
"text": "Props — props are tag attributes and children of your component/tag — a way to pass data. You can pass data down via props, but calls up need a callback function (eg myCallbackFunc defined in the caller/parent)."
},
{
"code": null,
"e": 18877,
"s": 18434,
"text": "function MyTag2(props) { const constvar = \"Const Txt\"; const [dynamic, setDynamic] = React.useState('Dyn Txt'); return ( <div> Hi {constvar} and {dynamic} Hi {props.var1} <Button onClick={props.callback} /> </div>); }}function App() { function myCallbackFunc() { // do something on button click } return ( <div> <MyTag2 var1=’var' callback={myCallbackFunc}>Text</MyTag2> </div>); }}"
},
{
"code": null,
"e": 18997,
"s": 18877,
"text": "Above example — your app root is <App/>, inside it, we call MyTag w/ “props” var1 and callback and the internal “Text”."
},
{
"code": null,
"e": 19075,
"s": 18997,
"text": "It takes some fiddling to learn but it is actually very elegant — try it out!"
},
{
"code": null,
"e": 19116,
"s": 19075,
"text": "Kickstarting the UI with Material-Design"
},
{
"code": null,
"e": 19339,
"s": 19116,
"text": "Google’s Material-UI is a component lib/framework for React that gives you great widgets & default themes so that anyone can make a site look good! I looked thru the gallery and picked the Dashboard (on the left) to start."
},
{
"code": null,
"e": 19493,
"s": 19339,
"text": "Material-UI has components like a <Grid> layout and <Paper> container to manage reactive/auto-resizing components. A nice side-menu <Drawer> is included."
},
{
"code": null,
"e": 19544,
"s": 19493,
"text": "Main things I did on top of the default Dashboard:"
},
{
"code": null,
"e": 19641,
"s": 19544,
"text": "Set left drawer to be closed by default, added <Modal> help pop-ups for links to external sites."
},
{
"code": null,
"e": 19708,
"s": 19641,
"text": "Updated top bar w/ new text and replaced notification bell w/ Help"
},
{
"code": null,
"e": 19820,
"s": 19708,
"text": "Implemented 3 main “paper” containers in the Grid: Random Diamond, Inventory Chooser/Filter, and the ML Pricer."
},
{
"code": null,
"e": 20056,
"s": 19820,
"text": "This is the easiest one to build. Assuming a server REST endpoint exists at /diamonds/daily/ which returns a json (data.price, data.carat, etc..) — we just fetch on component load (useEffect()) and set the state variables from results."
},
{
"code": null,
"e": 20610,
"s": 20056,
"text": "export default function Daily() { const [diamond, setDiamond] = useState({ price:0.0,carat:0.0,color:'',cut:'',clarity: '',skus: '' }); useEffect(() => { axios.get('/diamonds/daily/').then(response => { setDiamond({ price: response.data.price, carat: response.data.carat, ... }); })}, []); return ( <React.Fragment><Title>Random Diamond Featured</Title> <Typography>Price: {diamond.price}</Typography> <Typography>Carats: {diamond.carat}</Typography> ... </React.Fragment> );}"
},
{
"code": null,
"e": 20709,
"s": 20610,
"text": "I wanted a basic search form to let me filter thru the 140k diamonds — graph + details in a table."
},
{
"code": null,
"e": 21032,
"s": 20709,
"text": "I choose Victory for my graphing/plotting since it works w/ ReactNative (also in consideration was React-Viz and Re-Chart). I didn’t like the material-ui data table (lack of higher level abstraction) so went with the smaller open-source Material-Table project. Lots of components you can pick from out there in React-land!"
},
{
"code": null,
"e": 21071,
"s": 21032,
"text": "Main steps in creating this component:"
},
{
"code": null,
"e": 21347,
"s": 21071,
"text": "Using Material-UI Form components, added checkboxes into form groups and implementing a Slider for carats.Implement the onClick of the SearchButtonMock or build your backend to return a JSON of diamonds in a list which we render in a graph + table (via tabs) — more in Part 5"
},
{
"code": null,
"e": 21454,
"s": 21347,
"text": "Using Material-UI Form components, added checkboxes into form groups and implementing a Slider for carats."
},
{
"code": null,
"e": 21496,
"s": 21454,
"text": "Implement the onClick of the SearchButton"
},
{
"code": null,
"e": 21625,
"s": 21496,
"text": "Mock or build your backend to return a JSON of diamonds in a list which we render in a graph + table (via tabs) — more in Part 5"
},
{
"code": null,
"e": 21712,
"s": 21625,
"text": "Refer to github for full source. Below shows how the options are passed to the server:"
},
{
"code": null,
"e": 22401,
"s": 21712,
"text": "class Chooser extends Component { constructor(props) { super(props); this.state = { D: true, E: true, F: true, G: true, H: true, AstorIdeal: false, Ideal: true, diamonds: [], ... } handleSubmit = event => { // call REST api, setState of return diamonds[] etc } render() { return ( <React.Fragment > <Title>Filter Diamonds</Title> <FormControl component=\"fieldset\" > ... checkboxes and button </FormControl> <Paper square className={classes.root}> <Chart diamonds={this.state.diamonds}/> <DiamondsTable diamonds={this.state.diamonds} /> </Paper> </React.Fragment> )}"
},
{
"code": null,
"e": 22602,
"s": 22401,
"text": "DiamondsTable is a 3rd party table component to view a grid of data. Just pass the diamonds[] as a prop. Any change in the diamonds[] state and it forces re-rendering on its own. React refresh magic !"
},
{
"code": null,
"e": 22704,
"s": 22602,
"text": "We are close to the goal — to predict diamond pricing based on the 140k diamonds in our training set."
},
{
"code": null,
"e": 22798,
"s": 22704,
"text": "The control is really simple — much like the Filter/Chooser, we have a basic form and button."
},
{
"code": null,
"e": 22830,
"s": 22798,
"text": "Code structure is very similar:"
},
{
"code": null,
"e": 23199,
"s": 22830,
"text": "FormGroup and Button with a submitPrice callbacksubmitPrice calls a REST service passing the inputs {carat, clarity, cut, color} and returning a list of diamonds[] which are set as state variables.diamonds[] are passed to the charts and tables as props.The initial and any subsequent change in diamonds[] state triggers re-rendering of sub-components using diamonds[]."
},
{
"code": null,
"e": 23248,
"s": 23199,
"text": "FormGroup and Button with a submitPrice callback"
},
{
"code": null,
"e": 23398,
"s": 23248,
"text": "submitPrice calls a REST service passing the inputs {carat, clarity, cut, color} and returning a list of diamonds[] which are set as state variables."
},
{
"code": null,
"e": 23455,
"s": 23398,
"text": "diamonds[] are passed to the charts and tables as props."
},
{
"code": null,
"e": 23571,
"s": 23455,
"text": "The initial and any subsequent change in diamonds[] state triggers re-rendering of sub-components using diamonds[]."
},
{
"code": null,
"e": 23839,
"s": 23571,
"text": "Filter from prior step (Chooser.js) and Pricer.js are very similar. Pricer is implemented as a Function instead of a Class hence syntax has slight differences. Functions with state are new “Hooks” added to React and makes for a nice higher substitute to full classes."
},
{
"code": null,
"e": 24090,
"s": 23839,
"text": "Express is the JavaScript Node.js webserver. I’d still prefer backends in Python, but I guess this tutorial is MERN so I must use/learn Express (which isn’t too hard). A key advantage is re-use when you have the same front-end and back-end libraries."
},
{
"code": null,
"e": 24218,
"s": 24090,
"text": "Again I won’t go into basics of install. I’ll jump to the server.js script that hosts my API logic. The main REST calls I need:"
},
{
"code": null,
"e": 24266,
"s": 24218,
"text": "GET /diamonds/daily — random diamond of the day"
},
{
"code": null,
"e": 24329,
"s": 24266,
"text": "POST /diamonds/q/ — to fetch a list w/ some filtering criteria"
},
{
"code": null,
"e": 24399,
"s": 24329,
"text": "POST /diamonds/q2/ — to fetch a list w/ matching the pricing criteria"
},
{
"code": null,
"e": 24459,
"s": 24399,
"text": "POST /diamonds/price — to price diamonds using my ML models"
},
{
"code": null,
"e": 24529,
"s": 24459,
"text": "Setup a Mongoose model for Express, create a DB and bulk load the DB."
},
{
"code": null,
"e": 24689,
"s": 24529,
"text": "Setup Express endpointsMongoDB free on MLab — FYI Azure has CosmoDB which is (mostly) wire compliant/compatible to MongoDB. CosmoDB cheapest plan is $24/month!"
},
{
"code": null,
"e": 24713,
"s": 24689,
"text": "Setup Express endpoints"
},
{
"code": null,
"e": 24850,
"s": 24713,
"text": "MongoDB free on MLab — FYI Azure has CosmoDB which is (mostly) wire compliant/compatible to MongoDB. CosmoDB cheapest plan is $24/month!"
},
{
"code": null,
"e": 25061,
"s": 24850,
"text": "Once you create a DB, you need to upload data or hand enter them. The easiest way for me was to use a bulk loader script — requires you to install MongoDB client on your PC and point to the MLAB connect string."
},
{
"code": null,
"e": 25190,
"s": 25061,
"text": "mongoimport --uri mongodb://user:[email protected]:12122/diamonds --collection myc --type csv --headerline --file jsonfile.csv"
},
{
"code": null,
"e": 25295,
"s": 25190,
"text": "Uploading 150k diamond entries was fast, a few minutes and does use close to the 0.5gb limit. All done !"
},
{
"code": null,
"e": 25405,
"s": 25295,
"text": "2. Mongoose Model — create a script that defines a schema that matches your MongoDB collection’s JSON format:"
},
{
"code": null,
"e": 25635,
"s": 25405,
"text": "#diamond.model.jslet Diamond = new Schema({ carat: { type: Number, default: -1 }, color: { type: String, default: 'Default' }, ...}, { collection: 'myc' });module.exports = mongoose.model('Diamond', Diamond);"
},
{
"code": null,
"e": 25695,
"s": 25635,
"text": "3. Express.js REST Endpoints (server.js) are the next step."
},
{
"code": null,
"e": 25923,
"s": 25695,
"text": "There, most of it is boilerplate. Open a connection to be shared, set any alternate mappings (react path in this case), and listen to a port. In between, we create routes for various GET/POST handlers (defined in next section)."
},
{
"code": null,
"e": 26602,
"s": 25923,
"text": "app.use(cors());app.use(bodyParser.json());mongoose.connect('mongodb://user:pass@host:port/diamonds', { useNewUrlParser: true, useUnifiedTopology: true });const connection = mongoose.connection;connection.once('open', function() { console.log(\"MongoDB connection established successfully\");})//-- fill w/ diamondRoutes start... see below//-- fill endapp.use('/diamonds', diamondRoutes);// for webpack'd react front end app.use(express.static(\"./diamond-app/build\")); app.get(\"*\", (req, res) => { res.sendFile(path.resolve(__dirname, \"./diamond-app\", \"build\", \"index.html\"));});app.listen(PORT, function() { console.log(\"Server is running on Port..: \" + PORT);});"
},
{
"code": null,
"e": 26791,
"s": 26602,
"text": "Next we fill in the diamondRoutes — /daily /q /q2 and /price. ‘/daily’ is easy — just a hack randomized query that returns 1 diamond (using json schema defined earlier in diamond.model.js)"
},
{
"code": null,
"e": 27006,
"s": 26791,
"text": "diamondRoutes.route('/daily').get(function(req, res) { let random = Math.floor(Math.random() * 140000); // skip n Diamond.findOne().skip(random).exec(function(err, diamonds) { res.json(diamonds); });});"
},
{
"code": null,
"e": 27175,
"s": 27006,
"text": "The /q and /q2 are all similar query searches that take in POST params and map to a Mongoose query — the POST input is a JSON like{carat:3, color:’D’,cut:’’,clarity:’’}"
},
{
"code": null,
"e": 27672,
"s": 27175,
"text": "diamondRoutes.route('/q2').post(function(req, res) { const qobj = req.body; query = Diamond.find(); query = query.where('carat'). gt(qobj.carat-0.05).lt(qobj.carat+0.05); if (qobj.cut !== '') query = query.where('cut').equals(qobj.cut); if (qobj.color !== '') query = query.where('color').equals(qobj.color); if (qobj.clarity !== '') query = query.where('clarity').equals(qobj.clarity); query.exec(function(err, diamonds) { res.json(diamonds); });});"
},
{
"code": null,
"e": 27825,
"s": 27672,
"text": "Calling /price — the Machine Learning Inference call is done via another REST API callout to Azure ML Studio’s farm (now most to an Azure Flask server)."
},
{
"code": null,
"e": 27932,
"s": 27825,
"text": "The request chain: React Client -> Express.js -> ML Services-> back to Express.js -> back to React Client."
},
{
"code": null,
"e": 28116,
"s": 27932,
"text": "I think showing the code in chunks will be confusing, so just look at the key step which is to use an ‘asynch’ call to the callSvc function, then ‘await’ them all to join the results:"
},
{
"code": null,
"e": 28243,
"s": 28116,
"text": "let r0 = await callSvc(p2.XGB.url, p2.XGB.token, reqJson);let r1 = await callSvc(p2.LR.url, p2.LR.token, reqJson);let r2 = ..."
},
{
"code": null,
"e": 28403,
"s": 28243,
"text": "callSvc just does an axios http POST to get the ML predictions. Notice the ‘async’ def on the function, and the await call above that pairs up the async calls."
},
{
"code": null,
"e": 28691,
"s": 28403,
"text": "async function callSvc(apiurl, token, reqJson) { return axios.post(apiurl, reqJson, { headers: { 'Content-Type': 'application/json', 'Authorization': token, } }) .catch(function (error){ console.log(error); });}"
},
{
"code": null,
"e": 28826,
"s": 28691,
"text": "The responses are rolled into a single response JSON for the front end, notice ML Studio format differs from my custom SKLearn models:"
},
{
"code": null,
"e": 29199,
"s": 28826,
"text": "res.json([ { price:r0.data.Results.output1.value.Values[0][6],model:'XGB' }, { price:r1.data.Results.output1.value.Values[0][6],model:'LR' }, { price:r2.data.Results.output1.value.Values[0][6],model:'NN' }, { price: r3.data[0], model: 'ISO' }, { price: r4.data[0], model: 'XGB2' }, { price: r5.data[0], model: 'LR3' }, { price: r6.data[0], model: 'RF' },]);"
},
{
"code": null,
"e": 29318,
"s": 29199,
"text": "See how the chain looks via POSTMAN (calling express which calls ML services aggregating the results of all 7 models):"
},
{
"code": null,
"e": 29426,
"s": 29318,
"text": "Look at the full source code for the full story. That's mostly it — we’ve now built the express.js backend!"
},
{
"code": null,
"e": 29584,
"s": 29426,
"text": "Deploying to an Azure site is really simple (when it works which it usually does) — and frustrating as heck when there is a build or deploy error. Good luck!"
},
{
"code": null,
"e": 29658,
"s": 29584,
"text": "First, you should understand in development you may be running 2 servers:"
},
{
"code": null,
"e": 29733,
"s": 29658,
"text": "React dev engine (default port 3000)Express dev server (default port 4000)"
},
{
"code": null,
"e": 29770,
"s": 29733,
"text": "React dev engine (default port 3000)"
},
{
"code": null,
"e": 29809,
"s": 29770,
"text": "Express dev server (default port 4000)"
},
{
"code": null,
"e": 29957,
"s": 29809,
"text": "In prod you only run a single server (Express) and the React stuff is “bundled” into a webpack via “npm build” which results i something like this:"
},
{
"code": null,
"e": 30019,
"s": 29957,
"text": "Your express.js has code pointing to this build/static folder"
},
{
"code": null,
"e": 30199,
"s": 30019,
"text": "app.use(express.static(\"./diamond-app/build\"));app.get(\"*\", (req, res) => { res.sendFile(path.resolve(__dirname, \"./diamond-app\", \"build\", \"index.html\"));});"
},
{
"code": null,
"e": 30358,
"s": 30199,
"text": "Check this project into github and you are ready to go! (.gitignore the node_modules at both express.js (~diamonds) and react (~diamonds/diamond-app) levels)."
},
{
"code": null,
"e": 30405,
"s": 30358,
"text": "Login into Azure Portal and Create the Web App"
},
{
"code": null,
"e": 30633,
"s": 30405,
"text": "“testwebapp23” will become http://testwebapp23.azurewebsites.net so name it carefully, it can’t be changed later (you can externally DNS alias it if you own a domain). Pick the cheapest size, B1 will cost you about $15 a month!"
},
{
"code": null,
"e": 30707,
"s": 30633,
"text": "I would check the Config panel in Azure Web App, a few things to confirm:"
},
{
"code": null,
"e": 30912,
"s": 30707,
"text": "Next, you need to create a project in Azure DevOps (https://dev.azure.com) to host the build env. Afterward, go to the Project Settings (bottom-left) and link it to your GitHub repo, and enable Pipelines:"
},
{
"code": null,
"e": 31182,
"s": 30912,
"text": "Pipelines will enable your CI/CD setup so check-ins to GitHub trigger a build and deployment. There are several ways to set this up and each has its pitfalls. The weird but semi-simple way is to jump back to Azure Portal and finish with their webapp->Deployment Center."
},
{
"code": null,
"e": 31406,
"s": 31182,
"text": "You have the choice of Kudu App Build or Azure Pipelines. Pipelines is the latest Azure CI/CD toolset (replaces TFS). Both are buggy.. but I found for node.js Pipeline deployment works better (and for Python I prefer Kudu)."
},
{
"code": null,
"e": 31537,
"s": 31406,
"text": "Finish and this creates your first build and deployment. If you are lucky it will work and you can view your app online like this:"
},
{
"code": null,
"e": 31636,
"s": 31537,
"text": "Jump back to Azure DevOps and you’ll see it generated a Pipeline (build) and Release (deployment):"
},
{
"code": null,
"e": 31687,
"s": 31636,
"text": "If that passes, it goes onto Release (Deployment):"
},
{
"code": null,
"e": 31979,
"s": 31687,
"text": "You can customize each step and add some nifty stuff like pre/post scripts or an approval flow like below to propagate changes thru your environments. A change triggers a pre-prod (Demo) build then I have to manually approve to release to PROD (diamonds.foostack.ai) once I verify the build."
},
{
"code": null,
"e": 32039,
"s": 31979,
"text": "My top list of things I learned and want to warn you about:"
},
{
"code": null,
"e": 32223,
"s": 32039,
"text": "Azure Insights is great to track usage statistics (more difficult to setup than you’d think, you have to hook in code to each of your components but then you get some great telemetry)"
},
{
"code": null,
"e": 32462,
"s": 32223,
"text": "Azure is evolving (and breaking) so be prepared to have some annoyances esp with newer things like Machine Learning and Pipelines (node.js releases on linux broke suddenly.. for weeks now the Azure team is trying to clean up the debacle):"
},
{
"code": null,
"e": 32601,
"s": 32462,
"text": "Scrum Boards and ticket management can be done in Azure DevOps and integrates with GitHub. It is very new but not bad for a small project."
},
{
"code": null,
"e": 32884,
"s": 32601,
"text": "Cost Management — track it closely. The cost per Machine Learning model is a bit crazy ($2 per model container / day cost me $100+ for just 12 days). This motivated me to migrate to Flask. On another project SQL Warehouse for like 2 days was over $100 ! Be careful, set cost alarms!"
},
{
"code": null,
"e": 33096,
"s": 32884,
"text": "Python Flask Deploy — I added this late because of the cost issue above. I used the traditional Kudu build from WebApp->Deployment rather than Azure Pipelines due to some errors I kept having w/ Azure Pipelines."
},
{
"code": null,
"e": 33227,
"s": 33096,
"text": "Domain name setup is really easy — Azure doesn't do this, go to namecheap.com — then just link on Azure. Very simple instructions."
},
{
"code": null,
"e": 33338,
"s": 33227,
"text": "Happy coding! Peruse the live http://diamonds.foostack.ai site, github project or the Jupyter notebook online."
}
] |
How to change the root directory of an Apache server on Linux? | Apache web server is one of the most used web servers across all the platforms even after including different Linux distributions and windows. Apache server is an open source HTTP server that is mainly used to deliver web content and can also be used to serve many queries at once.
In this article, I will try to explain how to change the root directory for Apache web server.
It is usually the case that to change the root directory we must first be aware of its exact location and in the case of the Apache server, the root directory which is also known as DocumentRoot is present inside the folder −
/var/www/html
The DocumentRoot is the directory from which the Apache server will read the contents that the visitor will access over the internet.
Sometimes it is the case that the default DocumentRoot can also be present inside the directory.
/var/www
Now the next step is to locate the file in which this DocumentRoot is configured. Just type the following command in the terminal −
/etc/apache2/sites-available/000-default.conf
Now next step is to open this .conf file in your favorite text editor, I am making use of nano, and so the command for me looks something like this −
sudo nano /etc/apache2/sites-available/000-default.conf
and now we need to find the text “DocumentRoot” in the above file and change the location that might look something like this −
DocumentRoot /var/www/html
To whatever destination you want.
We also need to make a similar change in the apache2.conf file, for that just type the following command to the terminal
sudo nano /etc/apache2/apache2.conf
And then, try to find the following content in the above file
<Directory /var/www/html/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Now just change the /var/www/html to the directory that you changed to in the default.conf file and save your file and restart the server with the command shown below −
sudo service apache2 start | [
{
"code": null,
"e": 1344,
"s": 1062,
"text": "Apache web server is one of the most used web servers across all the platforms even after including different Linux distributions and windows. Apache server is an open source HTTP server that is mainly used to deliver web content and can also be used to serve many queries at once."
},
{
"code": null,
"e": 1439,
"s": 1344,
"text": "In this article, I will try to explain how to change the root directory for Apache web server."
},
{
"code": null,
"e": 1665,
"s": 1439,
"text": "It is usually the case that to change the root directory we must first be aware of its exact location and in the case of the Apache server, the root directory which is also known as DocumentRoot is present inside the folder −"
},
{
"code": null,
"e": 1679,
"s": 1665,
"text": "/var/www/html"
},
{
"code": null,
"e": 1813,
"s": 1679,
"text": "The DocumentRoot is the directory from which the Apache server will read the contents that the visitor will access over the internet."
},
{
"code": null,
"e": 1910,
"s": 1813,
"text": "Sometimes it is the case that the default DocumentRoot can also be present inside the directory."
},
{
"code": null,
"e": 1919,
"s": 1910,
"text": "/var/www"
},
{
"code": null,
"e": 2051,
"s": 1919,
"text": "Now the next step is to locate the file in which this DocumentRoot is configured. Just type the following command in the terminal −"
},
{
"code": null,
"e": 2097,
"s": 2051,
"text": "/etc/apache2/sites-available/000-default.conf"
},
{
"code": null,
"e": 2247,
"s": 2097,
"text": "Now next step is to open this .conf file in your favorite text editor, I am making use of nano, and so the command for me looks something like this −"
},
{
"code": null,
"e": 2303,
"s": 2247,
"text": "sudo nano /etc/apache2/sites-available/000-default.conf"
},
{
"code": null,
"e": 2431,
"s": 2303,
"text": "and now we need to find the text “DocumentRoot” in the above file and change the location that might look something like this −"
},
{
"code": null,
"e": 2458,
"s": 2431,
"text": "DocumentRoot /var/www/html"
},
{
"code": null,
"e": 2492,
"s": 2458,
"text": "To whatever destination you want."
},
{
"code": null,
"e": 2613,
"s": 2492,
"text": "We also need to make a similar change in the apache2.conf file, for that just type the following command to the terminal"
},
{
"code": null,
"e": 2649,
"s": 2613,
"text": "sudo nano /etc/apache2/apache2.conf"
},
{
"code": null,
"e": 2711,
"s": 2649,
"text": "And then, try to find the following content in the above file"
},
{
"code": null,
"e": 2830,
"s": 2711,
"text": "<Directory /var/www/html/>\n Options Indexes FollowSymLinks\n AllowOverride None\n Require all granted\n</Directory>"
},
{
"code": null,
"e": 2999,
"s": 2830,
"text": "Now just change the /var/www/html to the directory that you changed to in the default.conf file and save your file and restart the server with the command shown below −"
},
{
"code": null,
"e": 3026,
"s": 2999,
"text": "sudo service apache2 start"
}
] |
Roll the characters of a String | Practice | GeeksforGeeks | Given a string S and an array roll where roll[i] represents rolling first roll[i] characters in the string, the task is to apply every roll[i] on the string and output the final string. Rolling means increasing the ASCII value of character, like rolling ‘z’ would result in ‘a’, rolling ‘b’ would result in ‘c’, etc.
Example 1:
Input: s = "bca"
roll[] = {1, 2, 3}
Output: eeb
Explanation: arr[0] = 1 means roll
first character of string -> cca
arr[1] = 2 means roll
first two characters of string -> dda
arr[2] = 3 means roll
first three characters of string -> eeb
So final ans is "eeb".
Example 2:
Input: s = "zcza"
roll[] = {1, 1, 3, 4}
Explanation: debb
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function findRollOut() that takes String S, array roll, and integer N as parameters and returns the modified string.
Note- The length of the array roll and length of the string are equal.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N ≤ 107
0
chessnoobdj4 months ago
Easiest c++ 8 lines
string findRollOut(string s, long long arr[], int n)
{
long long int hash[n+2] = {0};
for(int i=0; i<n; i++)
hash[arr[i]]++;
for(int i=n; i>=0; i--)
hash[i] += hash[i+1];
for(int i=1; i<=n; i++)
s[i-1] = ((s[i-1]-'a')+hash[i])%26 + 'a';
return s;
}
0
pandasibasis747 months ago
string findRollOut(string s, long long arr[], int n){ // Your code goes here int brr[n+1] = {0};for(int i = 0; i < n; i++){ brr[0] += 1; brr[arr[i]] -= 1;}for(int i = 1; i < n; i++){ brr[i] += brr[i-1];}char ch[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};for(int i = 0; i < n; i++){ int x = brr[i] % 26; int y = s[i] - 97; s[i] = ch[(x+y)%26];} return s;}
0
mathav raj1 year ago
mathav raj
https://uploads.disquscdn.c...
-1
Pramod Vajire2 years ago
Pramod Vajire
Ahjj
0
rojan sudev2 years ago
rojan sudev
O(n) Codehttps://ide.geeksforgeeks.o...
0
Anish M N2 years ago
Anish M N
https://uploads.disquscdn.c...
0
Shivam Kumar Jha2 years ago
Shivam Kumar Jha
accepted soin and easy to understanc (cpp)https://ide.geeksforgeeks.o...
0
Bicky2 years ago
Bicky
simple cpp soln 0.06s
https://ide.geeksforgeeks.o...
0
MD. TASNIN TANVIR2 years ago
MD. TASNIN TANVIR
cpp solutionhttps://ide.geeksforgeeks.o...
0
Lohit Jat2 years ago
Lohit Jat
How this is happening?For Input:12bca3 3Output of Online Judge is:dea
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": 543,
"s": 226,
"text": "Given a string S and an array roll where roll[i] represents rolling first roll[i] characters in the string, the task is to apply every roll[i] on the string and output the final string. Rolling means increasing the ASCII value of character, like rolling ‘z’ would result in ‘a’, rolling ‘b’ would result in ‘c’, etc."
},
{
"code": null,
"e": 556,
"s": 545,
"text": "Example 1:"
},
{
"code": null,
"e": 820,
"s": 556,
"text": "Input: s = \"bca\"\nroll[] = {1, 2, 3} \nOutput: eeb\nExplanation: arr[0] = 1 means roll \nfirst character of string -> cca\narr[1] = 2 means roll \nfirst two characters of string -> dda\narr[2] = 3 means roll\nfirst three characters of string -> eeb\nSo final ans is \"eeb\"."
},
{
"code": null,
"e": 833,
"s": 820,
"text": " \nExample 2:"
},
{
"code": null,
"e": 891,
"s": 833,
"text": "Input: s = \"zcza\"\nroll[] = {1, 1, 3, 4}\nExplanation: debb"
},
{
"code": null,
"e": 1235,
"s": 893,
"text": "Your Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function findRollOut() that takes String S, array roll, and integer N as parameters and returns the modified string.\n\nNote- The length of the array roll and length of the string are equal."
},
{
"code": null,
"e": 1302,
"s": 1237,
"text": "Expected Time Complexity: O(N). \nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 1329,
"s": 1304,
"text": "Constraints:\n1 ≤ N ≤ 107"
},
{
"code": null,
"e": 1331,
"s": 1329,
"text": "0"
},
{
"code": null,
"e": 1355,
"s": 1331,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 1375,
"s": 1355,
"text": "Easiest c++ 8 lines"
},
{
"code": null,
"e": 1678,
"s": 1375,
"text": "string findRollOut(string s, long long arr[], int n)\n\t{\n\t long long int hash[n+2] = {0};\n\t for(int i=0; i<n; i++)\n\t hash[arr[i]]++;\n\t for(int i=n; i>=0; i--)\n\t hash[i] += hash[i+1];\n\t for(int i=1; i<=n; i++)\n\t s[i-1] = ((s[i-1]-'a')+hash[i])%26 + 'a';\n\t return s;\n\t}"
},
{
"code": null,
"e": 1680,
"s": 1678,
"text": "0"
},
{
"code": null,
"e": 1707,
"s": 1680,
"text": "pandasibasis747 months ago"
},
{
"code": null,
"e": 2147,
"s": 1707,
"text": " string findRollOut(string s, long long arr[], int n){ // Your code goes here int brr[n+1] = {0};for(int i = 0; i < n; i++){ brr[0] += 1; brr[arr[i]] -= 1;}for(int i = 1; i < n; i++){ brr[i] += brr[i-1];}char ch[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};for(int i = 0; i < n; i++){ int x = brr[i] % 26; int y = s[i] - 97; s[i] = ch[(x+y)%26];} return s;}"
},
{
"code": null,
"e": 2149,
"s": 2147,
"text": "0"
},
{
"code": null,
"e": 2170,
"s": 2149,
"text": "mathav raj1 year ago"
},
{
"code": null,
"e": 2181,
"s": 2170,
"text": "mathav raj"
},
{
"code": null,
"e": 2212,
"s": 2181,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2215,
"s": 2212,
"text": "-1"
},
{
"code": null,
"e": 2240,
"s": 2215,
"text": "Pramod Vajire2 years ago"
},
{
"code": null,
"e": 2254,
"s": 2240,
"text": "Pramod Vajire"
},
{
"code": null,
"e": 2259,
"s": 2254,
"text": "Ahjj"
},
{
"code": null,
"e": 2261,
"s": 2259,
"text": "0"
},
{
"code": null,
"e": 2284,
"s": 2261,
"text": "rojan sudev2 years ago"
},
{
"code": null,
"e": 2296,
"s": 2284,
"text": "rojan sudev"
},
{
"code": null,
"e": 2336,
"s": 2296,
"text": "O(n) Codehttps://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2338,
"s": 2336,
"text": "0"
},
{
"code": null,
"e": 2359,
"s": 2338,
"text": "Anish M N2 years ago"
},
{
"code": null,
"e": 2369,
"s": 2359,
"text": "Anish M N"
},
{
"code": null,
"e": 2400,
"s": 2369,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2402,
"s": 2400,
"text": "0"
},
{
"code": null,
"e": 2430,
"s": 2402,
"text": "Shivam Kumar Jha2 years ago"
},
{
"code": null,
"e": 2447,
"s": 2430,
"text": "Shivam Kumar Jha"
},
{
"code": null,
"e": 2520,
"s": 2447,
"text": "accepted soin and easy to understanc (cpp)https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2522,
"s": 2520,
"text": "0"
},
{
"code": null,
"e": 2539,
"s": 2522,
"text": "Bicky2 years ago"
},
{
"code": null,
"e": 2545,
"s": 2539,
"text": "Bicky"
},
{
"code": null,
"e": 2567,
"s": 2545,
"text": "simple cpp soln 0.06s"
},
{
"code": null,
"e": 2598,
"s": 2567,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2600,
"s": 2598,
"text": "0"
},
{
"code": null,
"e": 2629,
"s": 2600,
"text": "MD. TASNIN TANVIR2 years ago"
},
{
"code": null,
"e": 2647,
"s": 2629,
"text": "MD. TASNIN TANVIR"
},
{
"code": null,
"e": 2690,
"s": 2647,
"text": "cpp solutionhttps://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2692,
"s": 2690,
"text": "0"
},
{
"code": null,
"e": 2713,
"s": 2692,
"text": "Lohit Jat2 years ago"
},
{
"code": null,
"e": 2723,
"s": 2713,
"text": "Lohit Jat"
},
{
"code": null,
"e": 2793,
"s": 2723,
"text": "How this is happening?For Input:12bca3 3Output of Online Judge is:dea"
},
{
"code": null,
"e": 2939,
"s": 2793,
"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": 2975,
"s": 2939,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2985,
"s": 2975,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2995,
"s": 2985,
"text": "\nContest\n"
},
{
"code": null,
"e": 3058,
"s": 2995,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3206,
"s": 3058,
"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": 3414,
"s": 3206,
"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": 3520,
"s": 3414,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Deterministic PDA | Theory of Computation
The Deterministic Pushdown Automata is a variation of pushdown automata that accepts the deterministic context-free languages.
A language L(A) is accepted by a deterministic pushdown automata if and only if there is a single computation from the initial configuration until an accepting one for all strings belonging to L(A). It is not as powerful as non-deterministic finite automata. That's why it is less in use and used only where determinism is much easier to implement.
A PDA is said to be deterministic if its transition function δ(q,a,X) has at most one member for -
a ∈ Σ U {ε}
So, for a deterministic PDA, there is at most one transition possible in any combination of state, input symbol and stack top.
A Deterministic PDA is 5 tuple -
M = (Σ,Γ,Q,δ,q)
Σ - It is a finite set which does not contain a blank symbol, Γ - a finite set of stack alphabet, Q - set of states, q - start state, δ - a transition function, denoted as - | [
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 239,
"s": 112,
"text": "The Deterministic Pushdown Automata is a variation of pushdown automata that accepts the deterministic context-free languages."
},
{
"code": null,
"e": 588,
"s": 239,
"text": "A language L(A) is accepted by a deterministic pushdown automata if and only if there is a single computation from the initial configuration until an accepting one for all strings belonging to L(A). It is not as powerful as non-deterministic finite automata. That's why it is less in use and used only where determinism is much easier to implement."
},
{
"code": null,
"e": 687,
"s": 588,
"text": "A PDA is said to be deterministic if its transition function δ(q,a,X) has at most one member for -"
},
{
"code": null,
"e": 699,
"s": 687,
"text": "a ∈ Σ U {ε}"
},
{
"code": null,
"e": 826,
"s": 699,
"text": "So, for a deterministic PDA, there is at most one transition possible in any combination of state, input symbol and stack top."
},
{
"code": null,
"e": 859,
"s": 826,
"text": "A Deterministic PDA is 5 tuple -"
},
{
"code": null,
"e": 875,
"s": 859,
"text": "M = (Σ,Γ,Q,δ,q)"
}
] |
Array of ArrayList in Java - GeeksforGeeks | 11 Dec, 2018
We often come across 2D arrays where most of the part in the array is empty. Since space is a huge problem, we try different things to reduce the space. One such solution is to use jagged array when we know the length of each row in the array, but the problem arises when we do not specifically know the length of each of the rows. Here we use ArrayList since the length is unknown.Following is a Java program to demonstrate the above concept.
// Java code to demonstrate the concept of // array of ArrayList import java.util.*;public class Arraylist { public static void main(String[] args) { int n = 5; // Here al is an array of arraylist having // n number of rows.The number of columns on // each row depends on the user. // al[i].size() will give the size of the // i'th row ArrayList<Integer>[] al = new ArrayList[n]; // initializing for (int i = 0; i < n; i++) { al[i] = new ArrayList<Integer>(); } // We can add any number of columns to each // rows as per our wish al[0].add(1); al[0].add(2); al[1].add(5); al[2].add(10); al[2].add(20); al[2].add(30); al[3].add(56); al[4].add(34); al[4].add(67); al[4].add(89); al[4].add(12); for (int i = 0; i < n; i++) { for (int j = 0; j < al[i].size(); j++) { System.out.print(al[i].get(j) + " "); } System.out.println(); } }}
Output :
1 2
5
10 20 30
56
34 67 89 12
The above code works fine, but shows below warning.
prog.java:15: warning: [unchecked] unchecked conversion
ArrayList[] al = new ArrayList[n];
^
required: ArrayList[]
found: ArrayList[]
1 warning
The warning comes basically due to below line.
ArrayList<Integer>[] al = new ArrayList[n];
How to fix above warning?We cannot use array of ArrayList without warning. We basically need to use ArrayList of ArrayList.
Java - util package
Java-Array-Programs
Java-ArrayList
Java-Arrays
Java-Collections
Java-List-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Multidimensional Arrays in Java
Collections in Java
Set in Java
Initializing a List in Java | [
{
"code": null,
"e": 26162,
"s": 26134,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 26606,
"s": 26162,
"text": "We often come across 2D arrays where most of the part in the array is empty. Since space is a huge problem, we try different things to reduce the space. One such solution is to use jagged array when we know the length of each row in the array, but the problem arises when we do not specifically know the length of each of the rows. Here we use ArrayList since the length is unknown.Following is a Java program to demonstrate the above concept."
},
{
"code": "// Java code to demonstrate the concept of // array of ArrayList import java.util.*;public class Arraylist { public static void main(String[] args) { int n = 5; // Here al is an array of arraylist having // n number of rows.The number of columns on // each row depends on the user. // al[i].size() will give the size of the // i'th row ArrayList<Integer>[] al = new ArrayList[n]; // initializing for (int i = 0; i < n; i++) { al[i] = new ArrayList<Integer>(); } // We can add any number of columns to each // rows as per our wish al[0].add(1); al[0].add(2); al[1].add(5); al[2].add(10); al[2].add(20); al[2].add(30); al[3].add(56); al[4].add(34); al[4].add(67); al[4].add(89); al[4].add(12); for (int i = 0; i < n; i++) { for (int j = 0; j < al[i].size(); j++) { System.out.print(al[i].get(j) + \" \"); } System.out.println(); } }}",
"e": 27688,
"s": 26606,
"text": null
},
{
"code": null,
"e": 27697,
"s": 27688,
"text": "Output :"
},
{
"code": null,
"e": 27733,
"s": 27697,
"text": "1 2 \n5 \n10 20 30 \n56 \n34 67 89 12 \n"
},
{
"code": null,
"e": 27785,
"s": 27733,
"text": "The above code works fine, but shows below warning."
},
{
"code": null,
"e": 27979,
"s": 27785,
"text": "prog.java:15: warning: [unchecked] unchecked conversion\n ArrayList[] al = new ArrayList[n];\n ^\n required: ArrayList[]\n found: ArrayList[]\n1 warning\n"
},
{
"code": null,
"e": 28026,
"s": 27979,
"text": "The warning comes basically due to below line."
},
{
"code": "ArrayList<Integer>[] al = new ArrayList[n];",
"e": 28070,
"s": 28026,
"text": null
},
{
"code": null,
"e": 28194,
"s": 28070,
"text": "How to fix above warning?We cannot use array of ArrayList without warning. We basically need to use ArrayList of ArrayList."
},
{
"code": null,
"e": 28214,
"s": 28194,
"text": "Java - util package"
},
{
"code": null,
"e": 28234,
"s": 28214,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 28249,
"s": 28234,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 28261,
"s": 28249,
"text": "Java-Arrays"
},
{
"code": null,
"e": 28278,
"s": 28261,
"text": "Java-Collections"
},
{
"code": null,
"e": 28297,
"s": 28278,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 28302,
"s": 28297,
"text": "Java"
},
{
"code": null,
"e": 28307,
"s": 28302,
"text": "Java"
},
{
"code": null,
"e": 28324,
"s": 28307,
"text": "Java-Collections"
},
{
"code": null,
"e": 28422,
"s": 28324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28437,
"s": 28422,
"text": "Stream In Java"
},
{
"code": null,
"e": 28456,
"s": 28437,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28488,
"s": 28456,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28508,
"s": 28488,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28532,
"s": 28508,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28555,
"s": 28532,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 28587,
"s": 28555,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28607,
"s": 28587,
"text": "Collections in Java"
},
{
"code": null,
"e": 28619,
"s": 28607,
"text": "Set in Java"
}
] |
Scala | Sealed Trait - GeeksforGeeks | 19 Oct, 2020
Sealed provides exhaustive checking for our application. Exhaustive checking allows to check that all members of a sealed trait must be declared in the same file as of the source file. That means that all the possible known members of a trait that must be included are known by the compiler in advance. So this gives us advantage to prevent mistakes in our code.
Syntax :
sealed trait X
class A extends X
class B extends X
class C extends X
Exhaustive checking is mostly used in type / pattern matching in scala. Let’s say we have a sealed trait X and classes that extends trait X. On matching sub-types of trait X we have to make sure that we inclusion of all known sub-types is a must. Below method would give us a warning. Though we would get the correct output, but this may could be lead to unexpected runtime crashes in our application.
Warning: match may not be exhaustive
def obj(item: X) = item match {
case A => //
case B => //
}
Correct implementation would be like-
def obj(item: X) = item match{
case A => //
case B => //
case C => //
or
case _ => //for covering all the remaining cases
}
Let us take a view on below program in file saves as language.scala:-
Example :
Scala
// Scala Program that illustrates sealed trait// language.scalasealed trait Geeks{ val article="not done"} // Class extends traitclass Scala extends Geeks{ override val article = "scala article"} // Class extends traitclass Java extends Geeks{ override val article = "java article"} // Class extends traitclass Csharp extends Geeks{ override val article = "csharp article"} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { val s = new Scala val j = new Java val c = new Csharp println(checkArticle(s)) println(checkArticle(j)) println(checkArticle(c)) } // Defined function def checkArticle(Article: Geeks): String = Article match { case s: Scala => s.article case j: Java => j.article case c: Csharp => c.article //exclusion of <strong>line 45</strong> would lead to warning }}
Output :
scala article
java article
csharp article
Sub-types of a trait are known in advance- Not including any of the sub-type of sealed class C in pattern match would give us warning. Such a warning tells you that there’s a risk your code might produce a Match Error exception because some possible patterns are not handled. The warning points to a potential source of run-time faults, so it is usually a welcome help in getting your program right.
Sealed traits can only extend in the same source file as of sub-types- In above example, we have another class python in another scala file. Importing the trait geeks from language.scala we would get error message as below.
illegal inheritance from sealed trait bag
import geeks
class python extends geeks{
val article="python article";
}
Sealed class is also mostly used in enums– Preventing illegal inheritance and using all the sub-type so to avoid exhaustive matching warnings. Example :
Scala
// Scala Program that illustrates sealed trait// By using Enumerationsealed trait card extends Enumeration // Class extends traitcase object CLUB extends card // Class extends traitcase object HEART extends card // Class extends traitcase object DIAMOND extends card // Class extends traitcase object SPADE extends card // Creating objectobject obj1{ // Main method def main(args: Array[String]) { val card1 = HEART val card2 = CLUB val card3 = SPADE val card4 = DIAMOND println(checkcard(card1)) println(checkcard(card2)) println(checkcard(card3)) println(checkcard(card4)) } // Defined function def checkcard(x: card): String = x match { case HEART =>"heart" case CLUB =>"club" case SPADE =>"spade" case DIAMOND =>"diamond" }}
Output :
heart
club
spade
diamond
testergo9
Picked
Scala
scala-traits
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | flatMap Method
Scala | map() method
Scala | reduce() Function
Scala List filter() method with example
String concatenation in Scala
Type Casting in Scala
Scala List contains() method with example
Scala Tutorial – Learn Scala with Step By Step Guide
Scala String substring() method with example | [
{
"code": null,
"e": 26173,
"s": 26145,
"text": "\n19 Oct, 2020"
},
{
"code": null,
"e": 26537,
"s": 26173,
"text": "Sealed provides exhaustive checking for our application. Exhaustive checking allows to check that all members of a sealed trait must be declared in the same file as of the source file. That means that all the possible known members of a trait that must be included are known by the compiler in advance. So this gives us advantage to prevent mistakes in our code. "
},
{
"code": null,
"e": 26547,
"s": 26537,
"text": "Syntax : "
},
{
"code": null,
"e": 26617,
"s": 26547,
"text": "sealed trait X\nclass A extends X\nclass B extends X\nclass C extends X\n"
},
{
"code": null,
"e": 27020,
"s": 26617,
"text": "Exhaustive checking is mostly used in type / pattern matching in scala. Let’s say we have a sealed trait X and classes that extends trait X. On matching sub-types of trait X we have to make sure that we inclusion of all known sub-types is a must. Below method would give us a warning. Though we would get the correct output, but this may could be lead to unexpected runtime crashes in our application. "
},
{
"code": null,
"e": 27058,
"s": 27020,
"text": "Warning: match may not be exhaustive\n"
},
{
"code": null,
"e": 27125,
"s": 27058,
"text": "def obj(item: X) = item match {\n case A => //\n case B => //\n}\n"
},
{
"code": null,
"e": 27164,
"s": 27125,
"text": "Correct implementation would be like- "
},
{
"code": null,
"e": 27305,
"s": 27164,
"text": "def obj(item: X) = item match{\n case A => //\n case B => //\n case C => //\n or \n case _ => //for covering all the remaining cases\n}\n"
},
{
"code": null,
"e": 27376,
"s": 27305,
"text": "Let us take a view on below program in file saves as language.scala:- "
},
{
"code": null,
"e": 27387,
"s": 27376,
"text": "Example : "
},
{
"code": null,
"e": 27393,
"s": 27387,
"text": "Scala"
},
{
"code": "// Scala Program that illustrates sealed trait// language.scalasealed trait Geeks{ val article=\"not done\"} // Class extends traitclass Scala extends Geeks{ override val article = \"scala article\"} // Class extends traitclass Java extends Geeks{ override val article = \"java article\"} // Class extends traitclass Csharp extends Geeks{ override val article = \"csharp article\"} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { val s = new Scala val j = new Java val c = new Csharp println(checkArticle(s)) println(checkArticle(j)) println(checkArticle(c)) } // Defined function def checkArticle(Article: Geeks): String = Article match { case s: Scala => s.article case j: Java => j.article case c: Csharp => c.article //exclusion of <strong>line 45</strong> would lead to warning }}",
"e": 28314,
"s": 27393,
"text": null
},
{
"code": null,
"e": 28324,
"s": 28314,
"text": "Output : "
},
{
"code": null,
"e": 28367,
"s": 28324,
"text": "scala article\njava article\ncsharp article\n"
},
{
"code": null,
"e": 28769,
"s": 28367,
"text": "Sub-types of a trait are known in advance- Not including any of the sub-type of sealed class C in pattern match would give us warning. Such a warning tells you that there’s a risk your code might produce a Match Error exception because some possible patterns are not handled. The warning points to a potential source of run-time faults, so it is usually a welcome help in getting your program right. "
},
{
"code": null,
"e": 28993,
"s": 28769,
"text": "Sealed traits can only extend in the same source file as of sub-types- In above example, we have another class python in another scala file. Importing the trait geeks from language.scala we would get error message as below."
},
{
"code": null,
"e": 29036,
"s": 28993,
"text": "illegal inheritance from sealed trait bag\n"
},
{
"code": null,
"e": 29114,
"s": 29036,
"text": "import geeks\nclass python extends geeks{\n val article=\"python article\";\n}\n"
},
{
"code": null,
"e": 29267,
"s": 29114,
"text": "Sealed class is also mostly used in enums– Preventing illegal inheritance and using all the sub-type so to avoid exhaustive matching warnings. Example :"
},
{
"code": null,
"e": 29273,
"s": 29267,
"text": "Scala"
},
{
"code": "// Scala Program that illustrates sealed trait// By using Enumerationsealed trait card extends Enumeration // Class extends traitcase object CLUB extends card // Class extends traitcase object HEART extends card // Class extends traitcase object DIAMOND extends card // Class extends traitcase object SPADE extends card // Creating objectobject obj1{ // Main method def main(args: Array[String]) { val card1 = HEART val card2 = CLUB val card3 = SPADE val card4 = DIAMOND println(checkcard(card1)) println(checkcard(card2)) println(checkcard(card3)) println(checkcard(card4)) } // Defined function def checkcard(x: card): String = x match { case HEART =>\"heart\" case CLUB =>\"club\" case SPADE =>\"spade\" case DIAMOND =>\"diamond\" }}",
"e": 30133,
"s": 29273,
"text": null
},
{
"code": null,
"e": 30143,
"s": 30133,
"text": "Output : "
},
{
"code": null,
"e": 30169,
"s": 30143,
"text": "heart\nclub\nspade\ndiamond\n"
},
{
"code": null,
"e": 30181,
"s": 30171,
"text": "testergo9"
},
{
"code": null,
"e": 30188,
"s": 30181,
"text": "Picked"
},
{
"code": null,
"e": 30194,
"s": 30188,
"text": "Scala"
},
{
"code": null,
"e": 30207,
"s": 30194,
"text": "scala-traits"
},
{
"code": null,
"e": 30213,
"s": 30207,
"text": "Scala"
},
{
"code": null,
"e": 30311,
"s": 30213,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30329,
"s": 30311,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 30352,
"s": 30329,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 30373,
"s": 30352,
"text": "Scala | map() method"
},
{
"code": null,
"e": 30399,
"s": 30373,
"text": "Scala | reduce() Function"
},
{
"code": null,
"e": 30439,
"s": 30399,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 30469,
"s": 30439,
"text": "String concatenation in Scala"
},
{
"code": null,
"e": 30491,
"s": 30469,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 30533,
"s": 30491,
"text": "Scala List contains() method with example"
},
{
"code": null,
"e": 30586,
"s": 30533,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
}
] |
8086 program to convert 8 bit ASCII to BCD number - GeeksforGeeks | 10 Sep, 2018
Problem – Write a program to convert ASCII to BCD 8-bit number where starting address is 2000 and the number is stored at 2050 memory address and store result into 3050 memory address.
Example-
Input : location: 2050
Data : 37
Output : location: 3050
Data : 07
Algorithm –
Move value at [2050] into ALPerform AND operation on AL with 0FMove content of accumulator AL into 3050Stop
Move value at [2050] into AL
Perform AND operation on AL with 0F
Move content of accumulator AL into 3050
Stop
Program –
Explanation – Registers AL is used for general purpose
MOV is used to transfer the dataAND is used for multiplication (logically)HLT is used to halt the program
MOV is used to transfer the data
AND is used for multiplication (logically)
HLT is used to halt the program
Ankit_Bisht
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
Difference between Hardwired and Micro-programmed Control Unit | Set 2
I2C Communication Protocol
Memory mapped I/O and Isolated I/O
Computer Architecture | Flynn's taxonomy
Introduction to memory and memory units
Introduction of Control Unit and its Design | [
{
"code": null,
"e": 24878,
"s": 24850,
"text": "\n10 Sep, 2018"
},
{
"code": null,
"e": 25063,
"s": 24878,
"text": "Problem – Write a program to convert ASCII to BCD 8-bit number where starting address is 2000 and the number is stored at 2050 memory address and store result into 3050 memory address."
},
{
"code": null,
"e": 25174,
"s": 25063,
"text": "Example-\nInput : location: 2050\n Data : 37\nOutput : location: 3050 \n Data : 07 "
},
{
"code": null,
"e": 25186,
"s": 25174,
"text": "Algorithm –"
},
{
"code": null,
"e": 25294,
"s": 25186,
"text": "Move value at [2050] into ALPerform AND operation on AL with 0FMove content of accumulator AL into 3050Stop"
},
{
"code": null,
"e": 25323,
"s": 25294,
"text": "Move value at [2050] into AL"
},
{
"code": null,
"e": 25359,
"s": 25323,
"text": "Perform AND operation on AL with 0F"
},
{
"code": null,
"e": 25400,
"s": 25359,
"text": "Move content of accumulator AL into 3050"
},
{
"code": null,
"e": 25405,
"s": 25400,
"text": "Stop"
},
{
"code": null,
"e": 25415,
"s": 25405,
"text": "Program –"
},
{
"code": null,
"e": 25470,
"s": 25415,
"text": "Explanation – Registers AL is used for general purpose"
},
{
"code": null,
"e": 25576,
"s": 25470,
"text": "MOV is used to transfer the dataAND is used for multiplication (logically)HLT is used to halt the program"
},
{
"code": null,
"e": 25609,
"s": 25576,
"text": "MOV is used to transfer the data"
},
{
"code": null,
"e": 25652,
"s": 25609,
"text": "AND is used for multiplication (logically)"
},
{
"code": null,
"e": 25684,
"s": 25652,
"text": "HLT is used to halt the program"
},
{
"code": null,
"e": 25696,
"s": 25684,
"text": "Ankit_Bisht"
},
{
"code": null,
"e": 25711,
"s": 25696,
"text": "microprocessor"
},
{
"code": null,
"e": 25730,
"s": 25711,
"text": "system-programming"
},
{
"code": null,
"e": 25767,
"s": 25730,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 25782,
"s": 25767,
"text": "microprocessor"
},
{
"code": null,
"e": 25880,
"s": 25782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25942,
"s": 25880,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 26033,
"s": 25942,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 26069,
"s": 26033,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 26104,
"s": 26069,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 26175,
"s": 26104,
"text": "Difference between Hardwired and Micro-programmed Control Unit | Set 2"
},
{
"code": null,
"e": 26202,
"s": 26175,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 26237,
"s": 26202,
"text": "Memory mapped I/O and Isolated I/O"
},
{
"code": null,
"e": 26278,
"s": 26237,
"text": "Computer Architecture | Flynn's taxonomy"
},
{
"code": null,
"e": 26318,
"s": 26278,
"text": "Introduction to memory and memory units"
}
] |
Find the factorial of a number in pl/sql - GeeksforGeeks | 06 May, 2018
Given a number, your task to print the factorial of that number using pl/sql.
Examples:
Input : 5
Output : 120
Explanation:5! = 5 * 4 * 3 * 2 * 1 = 120
Input : 4
Output : 24
Basic structure of pl/sql block
declare
-- declare all the variables
begin -- for start block
-- make a program here
end -- for end block
The program of factorial of a number in pl/sql is given below:
declare -- it gives the final answer after computationfac number :=1; -- given number n-- taking input from usern number := &1; -- start blockbegin -- start while loop while n > 0 loop -- multiple with n and decrease n's valuefac:=n*fac; n:=n-1; end loop; -- end loop -- print result of facdbms_output.put_line(fac); -- end the begin blockend;
Output:(if given input as 5)
120
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n06 May, 2018"
},
{
"code": null,
"e": 25725,
"s": 25647,
"text": "Given a number, your task to print the factorial of that number using pl/sql."
},
{
"code": null,
"e": 25735,
"s": 25725,
"text": "Examples:"
},
{
"code": null,
"e": 25759,
"s": 25735,
"text": "Input : 5\nOutput : 120\n"
},
{
"code": null,
"e": 25800,
"s": 25759,
"text": "Explanation:5! = 5 * 4 * 3 * 2 * 1 = 120"
},
{
"code": null,
"e": 25823,
"s": 25800,
"text": "Input : 4\nOutput : 24\n"
},
{
"code": null,
"e": 25855,
"s": 25823,
"text": "Basic structure of pl/sql block"
},
{
"code": null,
"e": 25965,
"s": 25855,
"text": "declare\n-- declare all the variables\n\nbegin -- for start block\n-- make a program here\n\nend -- for end block\n"
},
{
"code": null,
"e": 26028,
"s": 25965,
"text": "The program of factorial of a number in pl/sql is given below:"
},
{
"code": "declare -- it gives the final answer after computationfac number :=1; -- given number n-- taking input from usern number := &1; -- start blockbegin -- start while loop while n > 0 loop -- multiple with n and decrease n's valuefac:=n*fac; n:=n-1; end loop; -- end loop -- print result of facdbms_output.put_line(fac); -- end the begin blockend; ",
"e": 26439,
"s": 26028,
"text": null
},
{
"code": null,
"e": 26468,
"s": 26439,
"text": "Output:(if given input as 5)"
},
{
"code": null,
"e": 26473,
"s": 26468,
"text": "120\n"
},
{
"code": null,
"e": 26484,
"s": 26473,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 26488,
"s": 26484,
"text": "SQL"
},
{
"code": null,
"e": 26492,
"s": 26488,
"text": "SQL"
},
{
"code": null,
"e": 26590,
"s": 26492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26656,
"s": 26590,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26713,
"s": 26656,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 26745,
"s": 26713,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26760,
"s": 26745,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26796,
"s": 26760,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26874,
"s": 26796,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26891,
"s": 26874,
"text": "SQL using Python"
},
{
"code": null,
"e": 26953,
"s": 26891,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 27019,
"s": 26953,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
}
] |
Convert a String into Date Format in R Programming - as.Date() Function - GeeksforGeeks | 30 Jun, 2020
as.Date() function in R Language is used to convert a string into date format.
Syntax: as.Date(x, format)
Parameters:x: string variableformat: Format in which string is declared(%m/%d/%y)
Example 1:
# R program to convert string into date # Creating a string vectordates <- c("27 / 02 / 92") # Conversion into date format result<-as.Date(dates, "% d/% m/% y") # Print result print(result)
Output:
[1] "1992-02-27"
Example 2:
# R program to convert string into date # Creating a string vectordates <- c("02 / 27 / 92", "02 / 27 / 92", "01 / 14 / 92", "02 / 28 / 92", "02 / 01 / 92") # Conversion into date format result<-as.Date(dates, "% m/% d/% y") # Print result print(result)
Output:
[1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28" "1992-02-01"
R Date-Function
R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
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?
K-Means Clustering in R Programming
Replace Specific Characters in String in R | [
{
"code": null,
"e": 26249,
"s": 26221,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 26328,
"s": 26249,
"text": "as.Date() function in R Language is used to convert a string into date format."
},
{
"code": null,
"e": 26355,
"s": 26328,
"text": "Syntax: as.Date(x, format)"
},
{
"code": null,
"e": 26437,
"s": 26355,
"text": "Parameters:x: string variableformat: Format in which string is declared(%m/%d/%y)"
},
{
"code": null,
"e": 26448,
"s": 26437,
"text": "Example 1:"
},
{
"code": "# R program to convert string into date # Creating a string vectordates <- c(\"27 / 02 / 92\") # Conversion into date format result<-as.Date(dates, \"% d/% m/% y\") # Print result print(result) ",
"e": 26648,
"s": 26448,
"text": null
},
{
"code": null,
"e": 26656,
"s": 26648,
"text": "Output:"
},
{
"code": null,
"e": 26674,
"s": 26656,
"text": "[1] \"1992-02-27\"\n"
},
{
"code": null,
"e": 26685,
"s": 26674,
"text": "Example 2:"
},
{
"code": "# R program to convert string into date # Creating a string vectordates <- c(\"02 / 27 / 92\", \"02 / 27 / 92\", \"01 / 14 / 92\", \"02 / 28 / 92\", \"02 / 01 / 92\") # Conversion into date format result<-as.Date(dates, \"% m/% d/% y\") # Print result print(result) ",
"e": 26973,
"s": 26685,
"text": null
},
{
"code": null,
"e": 26981,
"s": 26973,
"text": "Output:"
},
{
"code": null,
"e": 27051,
"s": 26981,
"text": "[1] \"1992-02-27\" \"1992-02-27\" \"1992-01-14\" \"1992-02-28\" \"1992-02-01\"\n"
},
{
"code": null,
"e": 27067,
"s": 27051,
"text": "R Date-Function"
},
{
"code": null,
"e": 27086,
"s": 27067,
"text": "R String-Functions"
},
{
"code": null,
"e": 27097,
"s": 27086,
"text": "R Language"
},
{
"code": null,
"e": 27195,
"s": 27097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27253,
"s": 27195,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 27305,
"s": 27253,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27337,
"s": 27305,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27381,
"s": 27337,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27433,
"s": 27381,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27468,
"s": 27433,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27506,
"s": 27468,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27564,
"s": 27506,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27600,
"s": 27564,
"text": "K-Means Clustering in R Programming"
}
] |
How to check whether the enter key is pressed in a textbox or not using JavaScript / jQuery ? - GeeksforGeeks | 30 May, 2019
Given a textarea element and the task is to check the user presses enter key with the help of JQuery.
jQuery keyup() Method: This method triggers the keyup event or adds a function to run when a keyup event occurs. The keyup event occurs when a keyboard key is released.Syntax:Trigger the keyup event for the selected elements:$(selector).keyup()
Attach a function to the keyup event:$(selector).keyup(function)
Parameters: It contains single parameter event which is optional. It specifies the function to run when the keyup event is triggered.
Syntax:
Trigger the keyup event for the selected elements:$(selector).keyup()
$(selector).keyup()
Attach a function to the keyup event:$(selector).keyup(function)
$(selector).keyup(function)
Parameters: It contains single parameter event which is optional. It specifies the function to run when the keyup event is triggered.
jQuery trigger() Method: This method triggers the defined event and the default behavior of an event for the selected elements.Syntax:$(selector).trigger(event, eventObj, param1, param2, ...)
Parameters:event: This parameter is required. It specifies the event to trigger for the specified element. Event can be a custom or any of the standard.param1, param2, ...: This parameter is optional. It specifies the extra parameters to pass on to the event handler. Additional parameters are especially useful in case of custom events.
Syntax:
$(selector).trigger(event, eventObj, param1, param2, ...)
Parameters:
event: This parameter is required. It specifies the event to trigger for the specified element. Event can be a custom or any of the standard.
param1, param2, ...: This parameter is optional. It specifies the extra parameters to pass on to the event handler. Additional parameters are especially useful in case of custom events.
jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)
Parameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens.
Syntax:
$(selector).on(event, childSelector, data, function, map)
Parameters:
event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.
childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.
data: This parameter is optional. It specifies additional data to pass to the function.
function: This parameter is required. It specifies the function to run when the event occurs.
map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens.
Example 1: In this example, the keyup event is added to the textarea, when it occurs then a new event enterKey is triggered by keyup event.
<!DOCTYPE HTML> <html> <head> <title> Event for user pressing enter button in a textbox </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 id = "h" style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> click the Enter Key inside the textarea. </p> <textarea></textarea> <br> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('textarea').keyup(function(e) { if(e.keyCode == 13) { $(this).trigger("enterKey"); } }); $('textarea').on("enterKey", function(e){ $("#GFG_DOWN").text("Enter key pressed inside textarea"); }); </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: In this example, the keyup event is added to the textarea, when it occurs then a message-Enter key pressed inside textarea is printed on the screen without triggering a new event to handle it.
<!DOCTYPE HTML> <html> <head> <title> Check enter key pressed in a textbox using JavaScript </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 id = "h" style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> click the Enter Key inside the textarea. </p> <textarea></textarea> <br> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> $('textarea').keyup(function(e) { if(e.keyCode == 13) { $("#GFG_DOWN").text("Enter key pressed inside textarea"); } }); </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
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 append HTML code to a div 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": 26415,
"s": 26387,
"text": "\n30 May, 2019"
},
{
"code": null,
"e": 26517,
"s": 26415,
"text": "Given a textarea element and the task is to check the user presses enter key with the help of JQuery."
},
{
"code": null,
"e": 26961,
"s": 26517,
"text": "jQuery keyup() Method: This method triggers the keyup event or adds a function to run when a keyup event occurs. The keyup event occurs when a keyboard key is released.Syntax:Trigger the keyup event for the selected elements:$(selector).keyup()\nAttach a function to the keyup event:$(selector).keyup(function)\nParameters: It contains single parameter event which is optional. It specifies the function to run when the keyup event is triggered."
},
{
"code": null,
"e": 26969,
"s": 26961,
"text": "Syntax:"
},
{
"code": null,
"e": 27040,
"s": 26969,
"text": "Trigger the keyup event for the selected elements:$(selector).keyup()\n"
},
{
"code": null,
"e": 27061,
"s": 27040,
"text": "$(selector).keyup()\n"
},
{
"code": null,
"e": 27127,
"s": 27061,
"text": "Attach a function to the keyup event:$(selector).keyup(function)\n"
},
{
"code": null,
"e": 27156,
"s": 27127,
"text": "$(selector).keyup(function)\n"
},
{
"code": null,
"e": 27290,
"s": 27156,
"text": "Parameters: It contains single parameter event which is optional. It specifies the function to run when the keyup event is triggered."
},
{
"code": null,
"e": 27820,
"s": 27290,
"text": "jQuery trigger() Method: This method triggers the defined event and the default behavior of an event for the selected elements.Syntax:$(selector).trigger(event, eventObj, param1, param2, ...)\nParameters:event: This parameter is required. It specifies the event to trigger for the specified element. Event can be a custom or any of the standard.param1, param2, ...: This parameter is optional. It specifies the extra parameters to pass on to the event handler. Additional parameters are especially useful in case of custom events."
},
{
"code": null,
"e": 27828,
"s": 27820,
"text": "Syntax:"
},
{
"code": null,
"e": 27887,
"s": 27828,
"text": "$(selector).trigger(event, eventObj, param1, param2, ...)\n"
},
{
"code": null,
"e": 27899,
"s": 27887,
"text": "Parameters:"
},
{
"code": null,
"e": 28041,
"s": 27899,
"text": "event: This parameter is required. It specifies the event to trigger for the specified element. Event can be a custom or any of the standard."
},
{
"code": null,
"e": 28227,
"s": 28041,
"text": "param1, param2, ...: This parameter is optional. It specifies the extra parameters to pass on to the event handler. Additional parameters are especially useful in case of custom events."
},
{
"code": null,
"e": 29101,
"s": 28227,
"text": "jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)\nParameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens."
},
{
"code": null,
"e": 29109,
"s": 29101,
"text": "Syntax:"
},
{
"code": null,
"e": 29168,
"s": 29109,
"text": "$(selector).on(event, childSelector, data, function, map)\n"
},
{
"code": null,
"e": 29180,
"s": 29168,
"text": "Parameters:"
},
{
"code": null,
"e": 29386,
"s": 29180,
"text": "event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid."
},
{
"code": null,
"e": 29520,
"s": 29386,
"text": "childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements."
},
{
"code": null,
"e": 29608,
"s": 29520,
"text": "data: This parameter is optional. It specifies additional data to pass to the function."
},
{
"code": null,
"e": 29702,
"s": 29608,
"text": "function: This parameter is required. It specifies the function to run when the event occurs."
},
{
"code": null,
"e": 29873,
"s": 29702,
"text": "map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens."
},
{
"code": null,
"e": 30013,
"s": 29873,
"text": "Example 1: In this example, the keyup event is added to the textarea, when it occurs then a new event enterKey is triggered by keyup event."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Event for user pressing enter button in a textbox </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 id = \"h\" style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> click the Enter Key inside the textarea. </p> <textarea></textarea> <br> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $('textarea').keyup(function(e) { if(e.keyCode == 13) { $(this).trigger(\"enterKey\"); } }); $('textarea').on(\"enterKey\", function(e){ $(\"#GFG_DOWN\").text(\"Enter key pressed inside textarea\"); }); </script> </body> </html> ",
"e": 31174,
"s": 30013,
"text": null
},
{
"code": null,
"e": 31182,
"s": 31174,
"text": "Output:"
},
{
"code": null,
"e": 31213,
"s": 31182,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 31243,
"s": 31213,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 31447,
"s": 31243,
"text": "Example 2: In this example, the keyup event is added to the textarea, when it occurs then a message-Enter key pressed inside textarea is printed on the screen without triggering a new event to handle it."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Check enter key pressed in a textbox using JavaScript </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 id = \"h\" style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> click the Enter Key inside the textarea. </p> <textarea></textarea> <br> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> $('textarea').keyup(function(e) { if(e.keyCode == 13) { $(\"#GFG_DOWN\").text(\"Enter key pressed inside textarea\"); } }); </script> </body> </html> ",
"e": 32482,
"s": 31447,
"text": null
},
{
"code": null,
"e": 32490,
"s": 32482,
"text": "Output:"
},
{
"code": null,
"e": 32521,
"s": 32490,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 32551,
"s": 32521,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 32562,
"s": 32551,
"text": "JavaScript"
},
{
"code": null,
"e": 32579,
"s": 32562,
"text": "Web Technologies"
},
{
"code": null,
"e": 32606,
"s": 32579,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32704,
"s": 32606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32744,
"s": 32704,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32789,
"s": 32744,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32850,
"s": 32789,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32922,
"s": 32850,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 32974,
"s": 32922,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 33014,
"s": 32974,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33047,
"s": 33014,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33092,
"s": 33047,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33135,
"s": 33092,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to handle duplicates in Binary Search Tree? - GeeksforGeeks | 28 Feb, 2022
In a Binary Search Tree (BST), all keys in left subtree of a key must be smaller and all keys in right subtree must be greater. So a Binary Search Tree by definition has distinct keys. How to allow duplicates where every insertion inserts one more key with a value and every deletion deletes one occurrence?A Simple Solution is to allow same keys on right side (we could also choose left side). For example consider insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree
12
/ \
10 20
/ \ /
9 11 12
/ \
10 12
A Better Solution is to augment every tree node to store count together with regular fields like key, left and right pointers. Insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree would create following.
12(3)
/ \
10(2) 20(1)
/ \
9(1) 11(1)
Count of a key is shown in bracket
This approach has following advantages over above simple approach.1) Height of tree is small irrespective of number of duplicates. Note that most of the BST operations (search, insert and delete) have time complexity as O(h) where h is height of BST. So if we are able to keep the height small, we get advantage of less number of key comparisons.2) Search, Insert and Delete become easier to do. We can use same insert, search and delete algorithms with small modifications (see below code). 3) This approach is suited for self-balancing BSTs (AVL Tree, Red-Black Tree, etc) also. These trees involve rotations, and a rotation may violate BST property of simple solution as a same key can be in either left side or right side after rotation.Below is implementation of normal Binary Search Tree with count with every key. This code basically is taken from code for insert and delete in BST. The changes made for handling duplicates are highlighted, rest of the code is same.
C++
C
Java
Python3
C#
Javascript
// C++ program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every node#include<bits/stdc++.h>using namespace std; struct node{ int key; int count; struct node *left, *right;}; // A utility function to create a new BST nodestruct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; temp->count = 1; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct node *root){ if (root != NULL) { inorder(root->left); cout << root->key << "(" << root->count << ") "; inorder(root->right); }} /* A utility function to insert a newnode with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); // If key already exists in BST, // increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, returnthe node with minimum key value found in thattree. Note that the entire tree does not needto be searched. */struct node * minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key,this function deletes a given key andreturns root of modified tree */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root->count > 1) { (root->count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root->left == NULL) { struct node *temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node *temp = root->left; free(root); return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's // content to this node root->key = temp->key; root->count = temp->count; // To ensure successor gets deleted by // deleteNode call, set count to 0. temp->count = 0; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Codeint main(){ /* Let us create following BST 12(3) / \ 10(2) 20(1) / \ 9(1) 11(1) */ struct node *root = NULL; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); cout << "Inorder traversal of the given tree " << endl; inorder(root); cout << "\nDelete 20\n"; root = deleteNode(root, 20); cout << "Inorder traversal of the modified tree \n"; inorder(root); cout << "\nDelete 12\n" ; root = deleteNode(root, 12); cout << "Inorder traversal of the modified tree \n"; inorder(root); cout << "\nDelete 9\n"; root = deleteNode(root, 9); cout << "Inorder traversal of the modified tree \n"; inorder(root); return 0;} // This code is contributed by Akanksha Rai
// C program to implement basic operations (search, insert and delete)// on a BST that handles duplicates by storing count with every node#include<stdio.h>#include<stdlib.h> struct node{ int key; int count; struct node *left, *right;}; // A utility function to create a new BST nodestruct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; temp->count = 1; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct node *root){ if (root != NULL) { inorder(root->left); printf("%d(%d) ", root->key, root->count); inorder(root->right); }} /* A utility function to insert a new node with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); // If key already exists in BST, increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node * minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key, this function deletes a given key and returns root of modified tree */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key else { // If key is present more than once, simply decrement // count and return if (root->count > 1) { (root->count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root->left == NULL) { struct node *temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node *temp = root->left; free(root); return temp; } // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->key = temp->key; root->count = temp->count; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Program to test above functionsint main(){ /* Let us create following BST 12(3) / \ 10(2) 20(1) / \ 9(1) 11(1) */ struct node *root = NULL; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); printf("Inorder traversal of the given tree \n"); inorder(root); printf("\nDelete 20\n"); root = deleteNode(root, 20); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 12\n"); root = deleteNode(root, 12); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 9\n"); root = deleteNode(root, 9); printf("Inorder traversal of the modified tree \n"); inorder(root); return 0;}
// Java program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every nodeclass GFG{static class node{ int key; int count; node left, right;}; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; temp.count = 1; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(node root){ if (root != null) { inorder(root.left); System.out.print(root.key + "(" + root.count + ") "); inorder(root.right); }} /* A utility function to insert a newnode with given key in BST */static node insert(node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, returnthe node with minimum key value found in thattree. Note that the entire tree does not needto be searched. */static node minValueNode(node node){ node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current;} /* Given a binary search tree and a key,this function deletes a given key andreturns root of modified tree */static node deleteNode(node root, int key){ // base case if (root == null) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root.count > 1) { (root.count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root.left == null) { node temp = root.right; root=null; return temp; } else if (root.right == null) { node temp = root.left; root = null; return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) node temp = minValueNode(root.right); // Copy the inorder successor's // content to this node root.key = temp.key; root.count = temp.count; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } return root;} // Driver Codepublic static void main(String[] args){ /* Let us create following BST 12(3) / \ 10(2) 20(1) / \ 9(1) 11(1) */ node root = null; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); System.out.print("Inorder traversal of " + "the given tree " + "\n"); inorder(root); System.out.print("\nDelete 20\n"); root = deleteNode(root, 20); System.out.print("Inorder traversal of " + "the modified tree \n"); inorder(root); System.out.print("\nDelete 12\n"); root = deleteNode(root, 12); System.out.print("Inorder traversal of " + "the modified tree \n"); inorder(root); System.out.print("\nDelete 9\n"); root = deleteNode(root, 9); System.out.print("Inorder traversal of " + "the modified tree \n"); inorder(root);}} // This code is contributed by 29AjayKumar
# Python3 program to implement basic operations# (search, insert and delete) on a BST that handles# duplicates by storing count with every node # A utility function to create a new BST nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.count = 1 self.left = None self.right = None # A utility function to do inorder# traversal of BSTdef inorder(root): if root != None: inorder(root.left) print(root.key,"(", root.count,")", end = " ") inorder(root.right) # A utility function to insert a new node# with given key in BSTdef insert(node, key): # If the tree is empty, return a new node if node == None: k = newNode(key) return k # If key already exists in BST, increment # count and return if key == node.key: (node.count) += 1 return node # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Given a non-empty binary search tree, return# the node with minimum key value found in that# tree. Note that the entire tree does not need# to be searched.def minValueNode(node): current = node # loop down to find the leftmost leaf while current.left != None: current = current.left return current # Given a binary search tree and a key,# this function deletes a given key and# returns root of modified treedef deleteNode(root, key): # base case if root == None: return root # If the key to be deleted is smaller than the # root's key, then it lies in left subtree if key < root.key: root.left = deleteNode(root.left, key) # If the key to be deleted is greater than # the root's key, then it lies in right subtree else if key > root.key: root.right = deleteNode(root.right, key) # if key is same as root's key else: # If key is present more than once, # simply decrement count and return if root.count > 1: root.count -= 1 return root # ElSE, delete the node with # only one child or no child if root.left == None: temp = root.right return temp else if root.right == None: temp = root.left return temp # node with two children: Get the inorder # successor (smallest in the right subtree) temp = minValueNode(root.right) # Copy the inorder successor's content # to this node root.key = temp.key root.count = temp.count # Delete the inorder successor root.right = deleteNode(root.right, temp.key) return root # Driver Codeif __name__ == '__main__': # Let us create following BST # 12(3) # / \ # 10(2) 20(1) # / \ # 9(1) 11(1) root = None root = insert(root, 12) root = insert(root, 10) root = insert(root, 20) root = insert(root, 9) root = insert(root, 11) root = insert(root, 10) root = insert(root, 12) root = insert(root, 12) print("Inorder traversal of the given tree") inorder(root) print() print("Delete 20") root = deleteNode(root, 20) print("Inorder traversal of the modified tree") inorder(root) print() print("Delete 12") root = deleteNode(root, 12) print("Inorder traversal of the modified tree") inorder(root) print() print("Delete 9") root = deleteNode(root, 9) print("Inorder traversal of the modified tree") inorder(root) # This code is contributed by PranchalK
// C# program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every nodeusing System; class GFG{public class node{ public int key; public int count; public node left, right;}; // A utility function to create// a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; temp.count = 1; return temp;} // A utility function to do inorder// traversal of BSTstatic void inorder(node root){ if (root != null) { inorder(root.left); Console.Write(root.key + "(" + root.count + ") "); inorder(root.right); }} /* A utility function to insert a newnode with given key in BST */static node insert(node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree,return the node with minimum key valuefound in that tree. Note that the entire treedoes not need to be searched. */static node minValueNode(node node){ node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current;} /* Given a binary search tree and a key,this function deletes a given key andreturns root of modified tree */static node deleteNode(node root, int key){ // base case if (root == null) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root.count > 1) { (root.count)--; return root; } // ElSE, delete the node node temp = null; // node with only one child or no child if (root.left == null) { temp = root.right; root = null; return temp; } else if (root.right == null) { temp = root.left; root = null; return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) temp = minValueNode(root.right); // Copy the inorder successor's // content to this node root.key = temp.key; root.count = temp.count; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } return root;} // Driver Codepublic static void Main(String[] args){ /* Let us create following BST 12(3) / \ 10(2) 20(1) / \ 9(1) 11(1) */ node root = null; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); Console.Write("Inorder traversal of " + "the given tree " + "\n"); inorder(root); Console.Write("\nDelete 20\n"); root = deleteNode(root, 20); Console.Write("Inorder traversal of " + "the modified tree \n"); inorder(root); Console.Write("\nDelete 12\n"); root = deleteNode(root, 12); Console.Write("Inorder traversal of " + "the modified tree \n"); inorder(root); Console.Write("\nDelete 9\n"); root = deleteNode(root, 9); Console.Write("Inorder traversal of " + "the modified tree \n"); inorder(root);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every node class node { constructor() { this.key = 0; this.count = 0; this.left = null; this.right = null; } } // A utility function to create a new BST node function newNode(item) { var temp = new node(); temp.key = item; temp.left = temp.right = null; temp.count = 1; return temp; } // A utility function to do inorder // traversal of BST function inorder( root) { if (root != null) { inorder(root.left); document.write(root.key + "(" + root.count + ") "); inorder(root.right); } } /* * A utility function to insert a new node with given key in BST */ function insert( node , key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } /* * Given a non-empty binary search tree, return the node with minimum key value * found in that tree. Note that the entire tree does not need to be searched. */ function minValueNode( node) { var current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } /* * Given a binary search tree and a key, this function deletes a given key and * returns root of modified tree */ function deleteNode( root , key) { // base case if (root == null) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root.count > 1) { (root.count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root.left == null) { var temp = root.right; root = null; return temp; } else if (root.right == null) { var temp = root.left; root = null; return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) var temp = minValueNode(root.right); // Copy the inorder successor's // content to this node root.key = temp.key; root.count = temp.count; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } return root; } // Driver Code /* * Let us create following BST 12(3) / \ 10(2) 20(1) / \ 9(1) 11(1) */ var root = null; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); document.write("Inorder traversal of " + "the given tree " + "<br/>"); inorder(root); document.write("<br/>Delete 20<br/>"); root = deleteNode(root, 20); document.write("Inorder traversal of " + "the modified tree <br/>"); inorder(root); document.write("<br/>Delete 12<br/>"); root = deleteNode(root, 12); document.write("Inorder traversal of " + "the modified tree <br/>"); inorder(root); document.write("<br/>Delete 9<br/>"); root = deleteNode(root, 9); document.write("Inorder traversal of " + "the modified tree <br/>"); inorder(root); // This code contributed by aashish1995 </script>
Output:
Inorder traversal of the given tree
9(1) 10(2) 11(1) 12(3) 20(1)
Delete 20
Inorder traversal of the modified tree
9(1) 10(2) 11(1) 12(3)
Delete 12
Inorder traversal of the modified tree
9(1) 10(2) 11(1) 12(2)
Delete 9
Inorder traversal of the modified tree
10(2) 11(1) 12(2)
We will soon be discussing AVL and Red Black Trees with duplicates allowed.This article is contributed by Chirag. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
PranchalKatiyar
Akanksha_Rai
29AjayKumar
Rajput-Ji
aashish1995
kanagselvi
anishmm1997
simmytarika5
surinderdawra388
Self-Balancing-BST
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorted Array to Balanced BST
Inorder Successor in Binary Search Tree
Optimal Binary Search Tree | DP-24
Find the node with minimum value in a Binary Search Tree
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Difference between Binary Tree and Binary Search Tree
Lowest Common Ancestor in a Binary Search Tree.
Binary Tree to Binary Search Tree Conversion
Find k-th smallest element in BST (Order Statistics in BST)
Convert a normal BST to Balanced BST | [
{
"code": null,
"e": 26081,
"s": 26053,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26577,
"s": 26081,
"text": "In a Binary Search Tree (BST), all keys in left subtree of a key must be smaller and all keys in right subtree must be greater. So a Binary Search Tree by definition has distinct keys. How to allow duplicates where every insertion inserts one more key with a value and every deletion deletes one occurrence?A Simple Solution is to allow same keys on right side (we could also choose left side). For example consider insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree "
},
{
"code": null,
"e": 26683,
"s": 26577,
"text": " 12\n / \\\n 10 20\n / \\ /\n 9 11 12 \n / \\\n 10 12"
},
{
"code": null,
"e": 26914,
"s": 26683,
"text": "A Better Solution is to augment every tree node to store count together with regular fields like key, left and right pointers. Insertion of keys 12, 10, 20, 9, 11, 10, 12, 12 in an empty Binary Search Tree would create following. "
},
{
"code": null,
"e": 27041,
"s": 26914,
"text": " 12(3)\n / \\\n 10(2) 20(1)\n / \\ \n 9(1) 11(1) \n\nCount of a key is shown in bracket"
},
{
"code": null,
"e": 28016,
"s": 27041,
"text": "This approach has following advantages over above simple approach.1) Height of tree is small irrespective of number of duplicates. Note that most of the BST operations (search, insert and delete) have time complexity as O(h) where h is height of BST. So if we are able to keep the height small, we get advantage of less number of key comparisons.2) Search, Insert and Delete become easier to do. We can use same insert, search and delete algorithms with small modifications (see below code). 3) This approach is suited for self-balancing BSTs (AVL Tree, Red-Black Tree, etc) also. These trees involve rotations, and a rotation may violate BST property of simple solution as a same key can be in either left side or right side after rotation.Below is implementation of normal Binary Search Tree with count with every key. This code basically is taken from code for insert and delete in BST. The changes made for handling duplicates are highlighted, rest of the code is same. "
},
{
"code": null,
"e": 28020,
"s": 28016,
"text": "C++"
},
{
"code": null,
"e": 28022,
"s": 28020,
"text": "C"
},
{
"code": null,
"e": 28027,
"s": 28022,
"text": "Java"
},
{
"code": null,
"e": 28035,
"s": 28027,
"text": "Python3"
},
{
"code": null,
"e": 28038,
"s": 28035,
"text": "C#"
},
{
"code": null,
"e": 28049,
"s": 28038,
"text": "Javascript"
},
{
"code": "// C++ program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every node#include<bits/stdc++.h>using namespace std; struct node{ int key; int count; struct node *left, *right;}; // A utility function to create a new BST nodestruct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; temp->count = 1; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct node *root){ if (root != NULL) { inorder(root->left); cout << root->key << \"(\" << root->count << \") \"; inorder(root->right); }} /* A utility function to insert a newnode with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); // If key already exists in BST, // increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, returnthe node with minimum key value found in thattree. Note that the entire tree does not needto be searched. */struct node * minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key,this function deletes a given key andreturns root of modified tree */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root->count > 1) { (root->count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root->left == NULL) { struct node *temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node *temp = root->left; free(root); return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's // content to this node root->key = temp->key; root->count = temp->count; // To ensure successor gets deleted by // deleteNode call, set count to 0. temp->count = 0; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Codeint main(){ /* Let us create following BST 12(3) / \\ 10(2) 20(1) / \\ 9(1) 11(1) */ struct node *root = NULL; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); cout << \"Inorder traversal of the given tree \" << endl; inorder(root); cout << \"\\nDelete 20\\n\"; root = deleteNode(root, 20); cout << \"Inorder traversal of the modified tree \\n\"; inorder(root); cout << \"\\nDelete 12\\n\" ; root = deleteNode(root, 12); cout << \"Inorder traversal of the modified tree \\n\"; inorder(root); cout << \"\\nDelete 9\\n\"; root = deleteNode(root, 9); cout << \"Inorder traversal of the modified tree \\n\"; inorder(root); return 0;} // This code is contributed by Akanksha Rai",
"e": 32437,
"s": 28049,
"text": null
},
{
"code": "// C program to implement basic operations (search, insert and delete)// on a BST that handles duplicates by storing count with every node#include<stdio.h>#include<stdlib.h> struct node{ int key; int count; struct node *left, *right;}; // A utility function to create a new BST nodestruct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; temp->count = 1; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(struct node *root){ if (root != NULL) { inorder(root->left); printf(\"%d(%d) \", root->key, root->count); inorder(root->right); }} /* A utility function to insert a new node with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); // If key already exists in BST, increment count and return if (key == node->key) { (node->count)++; return node; } /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */struct node * minValueNode(struct node* node){ struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} /* Given a binary search tree and a key, this function deletes a given key and returns root of modified tree */struct node* deleteNode(struct node* root, int key){ // base case if (root == NULL) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key else { // If key is present more than once, simply decrement // count and return if (root->count > 1) { (root->count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root->left == NULL) { struct node *temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node *temp = root->left; free(root); return temp; } // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->key = temp->key; root->count = temp->count; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root;} // Driver Program to test above functionsint main(){ /* Let us create following BST 12(3) / \\ 10(2) 20(1) / \\ 9(1) 11(1) */ struct node *root = NULL; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); printf(\"Inorder traversal of the given tree \\n\"); inorder(root); printf(\"\\nDelete 20\\n\"); root = deleteNode(root, 20); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); printf(\"\\nDelete 12\\n\"); root = deleteNode(root, 12); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); printf(\"\\nDelete 9\\n\"); root = deleteNode(root, 9); printf(\"Inorder traversal of the modified tree \\n\"); inorder(root); return 0;}",
"e": 36587,
"s": 32437,
"text": null
},
{
"code": "// Java program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every nodeclass GFG{static class node{ int key; int count; node left, right;}; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; temp.count = 1; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(node root){ if (root != null) { inorder(root.left); System.out.print(root.key + \"(\" + root.count + \") \"); inorder(root.right); }} /* A utility function to insert a newnode with given key in BST */static node insert(node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree, returnthe node with minimum key value found in thattree. Note that the entire tree does not needto be searched. */static node minValueNode(node node){ node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current;} /* Given a binary search tree and a key,this function deletes a given key andreturns root of modified tree */static node deleteNode(node root, int key){ // base case if (root == null) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root.count > 1) { (root.count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root.left == null) { node temp = root.right; root=null; return temp; } else if (root.right == null) { node temp = root.left; root = null; return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) node temp = minValueNode(root.right); // Copy the inorder successor's // content to this node root.key = temp.key; root.count = temp.count; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } return root;} // Driver Codepublic static void main(String[] args){ /* Let us create following BST 12(3) / \\ 10(2) 20(1) / \\ 9(1) 11(1) */ node root = null; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); System.out.print(\"Inorder traversal of \" + \"the given tree \" + \"\\n\"); inorder(root); System.out.print(\"\\nDelete 20\\n\"); root = deleteNode(root, 20); System.out.print(\"Inorder traversal of \" + \"the modified tree \\n\"); inorder(root); System.out.print(\"\\nDelete 12\\n\"); root = deleteNode(root, 12); System.out.print(\"Inorder traversal of \" + \"the modified tree \\n\"); inorder(root); System.out.print(\"\\nDelete 9\\n\"); root = deleteNode(root, 9); System.out.print(\"Inorder traversal of \" + \"the modified tree \\n\"); inorder(root);}} // This code is contributed by 29AjayKumar",
"e": 40820,
"s": 36587,
"text": null
},
{
"code": "# Python3 program to implement basic operations# (search, insert and delete) on a BST that handles# duplicates by storing count with every node # A utility function to create a new BST nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.count = 1 self.left = None self.right = None # A utility function to do inorder# traversal of BSTdef inorder(root): if root != None: inorder(root.left) print(root.key,\"(\", root.count,\")\", end = \" \") inorder(root.right) # A utility function to insert a new node# with given key in BSTdef insert(node, key): # If the tree is empty, return a new node if node == None: k = newNode(key) return k # If key already exists in BST, increment # count and return if key == node.key: (node.count) += 1 return node # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Given a non-empty binary search tree, return# the node with minimum key value found in that# tree. Note that the entire tree does not need# to be searched.def minValueNode(node): current = node # loop down to find the leftmost leaf while current.left != None: current = current.left return current # Given a binary search tree and a key,# this function deletes a given key and# returns root of modified treedef deleteNode(root, key): # base case if root == None: return root # If the key to be deleted is smaller than the # root's key, then it lies in left subtree if key < root.key: root.left = deleteNode(root.left, key) # If the key to be deleted is greater than # the root's key, then it lies in right subtree else if key > root.key: root.right = deleteNode(root.right, key) # if key is same as root's key else: # If key is present more than once, # simply decrement count and return if root.count > 1: root.count -= 1 return root # ElSE, delete the node with # only one child or no child if root.left == None: temp = root.right return temp else if root.right == None: temp = root.left return temp # node with two children: Get the inorder # successor (smallest in the right subtree) temp = minValueNode(root.right) # Copy the inorder successor's content # to this node root.key = temp.key root.count = temp.count # Delete the inorder successor root.right = deleteNode(root.right, temp.key) return root # Driver Codeif __name__ == '__main__': # Let us create following BST # 12(3) # / \\ # 10(2) 20(1) # / \\ # 9(1) 11(1) root = None root = insert(root, 12) root = insert(root, 10) root = insert(root, 20) root = insert(root, 9) root = insert(root, 11) root = insert(root, 10) root = insert(root, 12) root = insert(root, 12) print(\"Inorder traversal of the given tree\") inorder(root) print() print(\"Delete 20\") root = deleteNode(root, 20) print(\"Inorder traversal of the modified tree\") inorder(root) print() print(\"Delete 12\") root = deleteNode(root, 12) print(\"Inorder traversal of the modified tree\") inorder(root) print() print(\"Delete 9\") root = deleteNode(root, 9) print(\"Inorder traversal of the modified tree\") inorder(root) # This code is contributed by PranchalK",
"e": 44527,
"s": 40820,
"text": null
},
{
"code": "// C# program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every nodeusing System; class GFG{public class node{ public int key; public int count; public node left, right;}; // A utility function to create// a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; temp.count = 1; return temp;} // A utility function to do inorder// traversal of BSTstatic void inorder(node root){ if (root != null) { inorder(root.left); Console.Write(root.key + \"(\" + root.count + \") \"); inorder(root.right); }} /* A utility function to insert a newnode with given key in BST */static node insert(node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree,return the node with minimum key valuefound in that tree. Note that the entire treedoes not need to be searched. */static node minValueNode(node node){ node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current;} /* Given a binary search tree and a key,this function deletes a given key andreturns root of modified tree */static node deleteNode(node root, int key){ // base case if (root == null) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root.count > 1) { (root.count)--; return root; } // ElSE, delete the node node temp = null; // node with only one child or no child if (root.left == null) { temp = root.right; root = null; return temp; } else if (root.right == null) { temp = root.left; root = null; return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) temp = minValueNode(root.right); // Copy the inorder successor's // content to this node root.key = temp.key; root.count = temp.count; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } return root;} // Driver Codepublic static void Main(String[] args){ /* Let us create following BST 12(3) / \\ 10(2) 20(1) / \\ 9(1) 11(1) */ node root = null; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); Console.Write(\"Inorder traversal of \" + \"the given tree \" + \"\\n\"); inorder(root); Console.Write(\"\\nDelete 20\\n\"); root = deleteNode(root, 20); Console.Write(\"Inorder traversal of \" + \"the modified tree \\n\"); inorder(root); Console.Write(\"\\nDelete 12\\n\"); root = deleteNode(root, 12); Console.Write(\"Inorder traversal of \" + \"the modified tree \\n\"); inorder(root); Console.Write(\"\\nDelete 9\\n\"); root = deleteNode(root, 9); Console.Write(\"Inorder traversal of \" + \"the modified tree \\n\"); inorder(root);}} // This code is contributed by Rajput-Ji",
"e": 48783,
"s": 44527,
"text": null
},
{
"code": "<script> // JavaScript program to implement basic operations// (search, insert and delete) on a BST that// handles duplicates by storing count with// every node class node { constructor() { this.key = 0; this.count = 0; this.left = null; this.right = null; } } // A utility function to create a new BST node function newNode(item) { var temp = new node(); temp.key = item; temp.left = temp.right = null; temp.count = 1; return temp; } // A utility function to do inorder // traversal of BST function inorder( root) { if (root != null) { inorder(root.left); document.write(root.key + \"(\" + root.count + \") \"); inorder(root.right); } } /* * A utility function to insert a new node with given key in BST */ function insert( node , key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); // If key already exists in BST, // increment count and return if (key == node.key) { (node.count)++; return node; } /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } /* * Given a non-empty binary search tree, return the node with minimum key value * found in that tree. Note that the entire tree does not need to be searched. */ function minValueNode( node) { var current = node; /* loop down to find the leftmost leaf */ while (current.left != null) current = current.left; return current; } /* * Given a binary search tree and a key, this function deletes a given key and * returns root of modified tree */ function deleteNode( root , key) { // base case if (root == null) return root; // If the key to be deleted is smaller than the // root's key, then it lies in left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key to be deleted is greater than // the root's key, then it lies in right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key else { // If key is present more than once, // simply decrement count and return if (root.count > 1) { (root.count)--; return root; } // ElSE, delete the node // node with only one child or no child if (root.left == null) { var temp = root.right; root = null; return temp; } else if (root.right == null) { var temp = root.left; root = null; return temp; } // node with two children: Get the inorder // successor (smallest in the right subtree) var temp = minValueNode(root.right); // Copy the inorder successor's // content to this node root.key = temp.key; root.count = temp.count; // Delete the inorder successor root.right = deleteNode(root.right, temp.key); } return root; } // Driver Code /* * Let us create following BST 12(3) / \\ 10(2) 20(1) / \\ 9(1) 11(1) */ var root = null; root = insert(root, 12); root = insert(root, 10); root = insert(root, 20); root = insert(root, 9); root = insert(root, 11); root = insert(root, 10); root = insert(root, 12); root = insert(root, 12); document.write(\"Inorder traversal of \" + \"the given tree \" + \"<br/>\"); inorder(root); document.write(\"<br/>Delete 20<br/>\"); root = deleteNode(root, 20); document.write(\"Inorder traversal of \" + \"the modified tree <br/>\"); inorder(root); document.write(\"<br/>Delete 12<br/>\"); root = deleteNode(root, 12); document.write(\"Inorder traversal of \" + \"the modified tree <br/>\"); inorder(root); document.write(\"<br/>Delete 9<br/>\"); root = deleteNode(root, 9); document.write(\"Inorder traversal of \" + \"the modified tree <br/>\"); inorder(root); // This code contributed by aashish1995 </script>",
"e": 53464,
"s": 48783,
"text": null
},
{
"code": null,
"e": 53474,
"s": 53464,
"text": "Output: "
},
{
"code": null,
"e": 53749,
"s": 53474,
"text": "Inorder traversal of the given tree\n9(1) 10(2) 11(1) 12(3) 20(1)\nDelete 20\nInorder traversal of the modified tree\n9(1) 10(2) 11(1) 12(3)\nDelete 12\nInorder traversal of the modified tree\n9(1) 10(2) 11(1) 12(2)\nDelete 9\nInorder traversal of the modified tree\n10(2) 11(1) 12(2)"
},
{
"code": null,
"e": 53988,
"s": 53749,
"text": "We will soon be discussing AVL and Red Black Trees with duplicates allowed.This article is contributed by Chirag. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 54004,
"s": 53988,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 54017,
"s": 54004,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 54029,
"s": 54017,
"text": "29AjayKumar"
},
{
"code": null,
"e": 54039,
"s": 54029,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 54051,
"s": 54039,
"text": "aashish1995"
},
{
"code": null,
"e": 54062,
"s": 54051,
"text": "kanagselvi"
},
{
"code": null,
"e": 54074,
"s": 54062,
"text": "anishmm1997"
},
{
"code": null,
"e": 54087,
"s": 54074,
"text": "simmytarika5"
},
{
"code": null,
"e": 54104,
"s": 54087,
"text": "surinderdawra388"
},
{
"code": null,
"e": 54123,
"s": 54104,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 54142,
"s": 54123,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 54161,
"s": 54142,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 54259,
"s": 54161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 54288,
"s": 54259,
"text": "Sorted Array to Balanced BST"
},
{
"code": null,
"e": 54328,
"s": 54288,
"text": "Inorder Successor in Binary Search Tree"
},
{
"code": null,
"e": 54363,
"s": 54328,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 54420,
"s": 54363,
"text": "Find the node with minimum value in a Binary Search Tree"
},
{
"code": null,
"e": 54490,
"s": 54420,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 54544,
"s": 54490,
"text": "Difference between Binary Tree and Binary Search Tree"
},
{
"code": null,
"e": 54592,
"s": 54544,
"text": "Lowest Common Ancestor in a Binary Search Tree."
},
{
"code": null,
"e": 54637,
"s": 54592,
"text": "Binary Tree to Binary Search Tree Conversion"
},
{
"code": null,
"e": 54697,
"s": 54637,
"text": "Find k-th smallest element in BST (Order Statistics in BST)"
}
] |
Nvidia Interview Experience for Compiler Engineer - GeeksforGeeks | 18 Oct, 2021
My Background: I worked in the compiler frontend (Clang) during my thesis developing a compiler-like tool for static analysis of C language. Basically a linter for C programming language. I am from Tier 1 college (IIT). I am 1+ years experienced.
Hiring Manager Round: He worked in the GPU compiler optimization team at NVIDIA. Talked about stuff he does related to compiler optimizations. Asked questions about compiler optimizations like loop optimizations and peephole optimizations since I knew he is from the optimization team I prepared this stuff in advance. But I clearly told him that I have never worked in the optimizations field. Note: Compiler optimization is a compiler backend where you also need architecture-related knowledge.
Round 1: Coding
Print all the permutations of string? I told him to change the question since I didn’t revise backtracking for this interview.
He was humble enough to change the question.
Merge sort on the linked list with detailed runtime analysis?
I answered the question successfully but made mistake in analyzing the runtime. I implemented the approach of dividing the linked list into two halves and merging the two halves and recursively applying quicksort I told him it is O(n^2) which was wrong. But even he didn’t know that I made a mistake in analysis and he kept on suggesting a method to reduce it to O(N log N) which was wrong.
How to implement hashmap? Possible approaches in defining the hash function for mapping keys?
Round 2: Coding
Find min element in a binary tree?
C code to extract words from a sentence and copying it to 2d array where each row contains a word. The code was a little complex. There he was copying the strings by breaking the whole sentence and also memory manipulation with really was done to handle the case of insufficient memory if the allocated memory is less than allocated earlier.
E.g:
I/p: Nvidia is a cool organization.
O/p: Nvidia
is
a
cool
organization
There is a 3×3 matrix of storing apps like
A1 A2 A3
A4 A5 A6
A7 A8 A9
You need to maintain the top 9 apps in this matrix. How will you do it?
Now he didn’t mention anything apart from this. I didn’t ask him any questions and moved forward with the solution which was a mistake. I said I will do it using the priority queue. Then he said how the priority queue will work so I explained to him the insertion and deletion of a node in heap for 20 mins then he said “ohh” but it will not be maintaining the order right? I was like what. He said can you think of other data structures for this?
Then again after thinking for 10 mins I said I will store it using a linked list and map. Basically, it is Implement LRU cache standard problem. Which I saw a day back but couldn’t think about it at the actual moment. I told him how I will implement it and he didn’t ask me to code it and this interview was done.
Round 3: Design Skills
How do you reduce the cache misses in the case of multiplying 2 very large matrices? I couldn’t answer it since I had no idea how cache will work in this case.
Then he asked a long cryptic compiler-related problem. It goes like this....
Let’s say compiler A calls compiler B’s “invoke” module 15 times and during that it performs some steps where the percentage of time consumed is written alongside
Initializing a compiler instance 15%
Preprocessing 25%
Syntax analysis 25%
Optimizations 35%
How will you minimize the time consumed? Now, what do you get by this problem?
Do I need to make 15% to 10%? What is the meaning of reducing the time? It took me 25 mins to clarify the problem from the interviewer. Basically, he wanted to know like do we need to initialize the compiler instance for all 15 calls or do we need to perform preprocessing again and again or not?
So after I finally understood the problem I answered all his questions successfully. I told him we can have an if check if the compiler is already initialized. We can pass the argument to the invoke function to take the compiler instance. We can store a map to store the preprocessor-related data and can use flags to know if syntax analysis was done already or not then he asked followup like can we remove if conditions then I said like checking the map size and stuff. So basically I handled his questions well.
Round 4: Clang knowledge
This was the most sensible interview. She asked me all the details about my project and how I approached the problem and what data structures and design patterns I used for it.
So basically she was interested in the work and since I did my project really well I knew each and every stuff she asked me regarding it.
Round 6: Compiler Director Round (Cultural Fit)
He asked questions about my project and some things like why do you want to join this difficult and boring field. Basically, after his demotivation, I decided I don’t want to join this field.
After a week they said they were not satisfied with coding rounds so they want one more coding round.
Round 7: Coding
Given a tree convert it to a sum tree?
E.g: 2 19
/ \ / \
3 4 ———-> 15 4
/ \ / \
5 7 5 7
I gave him O(n^2) approach. He wanted to reduce it to O(n) which I was not able to do.
Verdict: Rejected.
Conclusion:
I felt relaxed. Because they contacted me in May 2021 and scheduled the first round in 17th Sept 2021 which they rescheduled at the end moment to next week since they were not available. Thank god I didn’t take leave early from my current organization. Then on the interview day, the first round didn’t happen because the guy was not available. The coding people didn’t give any hints. The last interviewer was horrific. He became dead silent after asking the question. When he spoke he had too much arrogance in his voice. Please dont keep such people who are there to satisfy their ego. Thank god I didn’t answer properly.
Marketing
Nvidia
Interview Experiences
Nvidia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
EPAM Interview Experience (Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience for SDE-1 (On-Campus) | [
{
"code": null,
"e": 26025,
"s": 25997,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 26272,
"s": 26025,
"text": "My Background: I worked in the compiler frontend (Clang) during my thesis developing a compiler-like tool for static analysis of C language. Basically a linter for C programming language. I am from Tier 1 college (IIT). I am 1+ years experienced."
},
{
"code": null,
"e": 26769,
"s": 26272,
"text": "Hiring Manager Round: He worked in the GPU compiler optimization team at NVIDIA. Talked about stuff he does related to compiler optimizations. Asked questions about compiler optimizations like loop optimizations and peephole optimizations since I knew he is from the optimization team I prepared this stuff in advance. But I clearly told him that I have never worked in the optimizations field. Note: Compiler optimization is a compiler backend where you also need architecture-related knowledge."
},
{
"code": null,
"e": 26786,
"s": 26769,
"text": "Round 1: Coding "
},
{
"code": null,
"e": 26913,
"s": 26786,
"text": "Print all the permutations of string? I told him to change the question since I didn’t revise backtracking for this interview."
},
{
"code": null,
"e": 26958,
"s": 26913,
"text": "He was humble enough to change the question."
},
{
"code": null,
"e": 27020,
"s": 26958,
"text": "Merge sort on the linked list with detailed runtime analysis?"
},
{
"code": null,
"e": 27411,
"s": 27020,
"text": "I answered the question successfully but made mistake in analyzing the runtime. I implemented the approach of dividing the linked list into two halves and merging the two halves and recursively applying quicksort I told him it is O(n^2) which was wrong. But even he didn’t know that I made a mistake in analysis and he kept on suggesting a method to reduce it to O(N log N) which was wrong."
},
{
"code": null,
"e": 27505,
"s": 27411,
"text": "How to implement hashmap? Possible approaches in defining the hash function for mapping keys?"
},
{
"code": null,
"e": 27522,
"s": 27505,
"text": "Round 2: Coding "
},
{
"code": null,
"e": 27557,
"s": 27522,
"text": "Find min element in a binary tree?"
},
{
"code": null,
"e": 27899,
"s": 27557,
"text": "C code to extract words from a sentence and copying it to 2d array where each row contains a word. The code was a little complex. There he was copying the strings by breaking the whole sentence and also memory manipulation with really was done to handle the case of insufficient memory if the allocated memory is less than allocated earlier."
},
{
"code": null,
"e": 28029,
"s": 27899,
"text": "E.g:\nI/p: Nvidia is a cool organization.\nO/p: Nvidia\n is\n a\n cool\n organization"
},
{
"code": null,
"e": 28072,
"s": 28029,
"text": "There is a 3×3 matrix of storing apps like"
},
{
"code": null,
"e": 28120,
"s": 28072,
"text": " A1 A2 A3\n A4 A5 A6\n A7 A8 A9"
},
{
"code": null,
"e": 28192,
"s": 28120,
"text": "You need to maintain the top 9 apps in this matrix. How will you do it?"
},
{
"code": null,
"e": 28640,
"s": 28192,
"text": "Now he didn’t mention anything apart from this. I didn’t ask him any questions and moved forward with the solution which was a mistake. I said I will do it using the priority queue. Then he said how the priority queue will work so I explained to him the insertion and deletion of a node in heap for 20 mins then he said “ohh” but it will not be maintaining the order right? I was like what. He said can you think of other data structures for this?"
},
{
"code": null,
"e": 28954,
"s": 28640,
"text": "Then again after thinking for 10 mins I said I will store it using a linked list and map. Basically, it is Implement LRU cache standard problem. Which I saw a day back but couldn’t think about it at the actual moment. I told him how I will implement it and he didn’t ask me to code it and this interview was done."
},
{
"code": null,
"e": 28978,
"s": 28954,
"text": "Round 3: Design Skills "
},
{
"code": null,
"e": 29138,
"s": 28978,
"text": "How do you reduce the cache misses in the case of multiplying 2 very large matrices? I couldn’t answer it since I had no idea how cache will work in this case."
},
{
"code": null,
"e": 29215,
"s": 29138,
"text": "Then he asked a long cryptic compiler-related problem. It goes like this...."
},
{
"code": null,
"e": 29378,
"s": 29215,
"text": "Let’s say compiler A calls compiler B’s “invoke” module 15 times and during that it performs some steps where the percentage of time consumed is written alongside"
},
{
"code": null,
"e": 29542,
"s": 29378,
"text": "Initializing a compiler instance 15%\nPreprocessing 25%\nSyntax analysis 25%\nOptimizations 35%"
},
{
"code": null,
"e": 29621,
"s": 29542,
"text": "How will you minimize the time consumed? Now, what do you get by this problem?"
},
{
"code": null,
"e": 29918,
"s": 29621,
"text": "Do I need to make 15% to 10%? What is the meaning of reducing the time? It took me 25 mins to clarify the problem from the interviewer. Basically, he wanted to know like do we need to initialize the compiler instance for all 15 calls or do we need to perform preprocessing again and again or not?"
},
{
"code": null,
"e": 30433,
"s": 29918,
"text": "So after I finally understood the problem I answered all his questions successfully. I told him we can have an if check if the compiler is already initialized. We can pass the argument to the invoke function to take the compiler instance. We can store a map to store the preprocessor-related data and can use flags to know if syntax analysis was done already or not then he asked followup like can we remove if conditions then I said like checking the map size and stuff. So basically I handled his questions well."
},
{
"code": null,
"e": 30459,
"s": 30433,
"text": "Round 4: Clang knowledge "
},
{
"code": null,
"e": 30637,
"s": 30459,
"text": "This was the most sensible interview. She asked me all the details about my project and how I approached the problem and what data structures and design patterns I used for it. "
},
{
"code": null,
"e": 30775,
"s": 30637,
"text": "So basically she was interested in the work and since I did my project really well I knew each and every stuff she asked me regarding it."
},
{
"code": null,
"e": 30823,
"s": 30775,
"text": "Round 6: Compiler Director Round (Cultural Fit)"
},
{
"code": null,
"e": 31015,
"s": 30823,
"text": "He asked questions about my project and some things like why do you want to join this difficult and boring field. Basically, after his demotivation, I decided I don’t want to join this field."
},
{
"code": null,
"e": 31117,
"s": 31015,
"text": "After a week they said they were not satisfied with coding rounds so they want one more coding round."
},
{
"code": null,
"e": 31134,
"s": 31117,
"text": "Round 7: Coding "
},
{
"code": null,
"e": 31173,
"s": 31134,
"text": "Given a tree convert it to a sum tree?"
},
{
"code": null,
"e": 31265,
"s": 31173,
"text": "E.g: 2 19"
},
{
"code": null,
"e": 31364,
"s": 31265,
"text": " / \\ / \\"
},
{
"code": null,
"e": 31451,
"s": 31364,
"text": " 3 4 ———-> 15 4"
},
{
"code": null,
"e": 31545,
"s": 31451,
"text": " / \\ / \\"
},
{
"code": null,
"e": 31637,
"s": 31545,
"text": " 5 7 5 7"
},
{
"code": null,
"e": 31724,
"s": 31637,
"text": "I gave him O(n^2) approach. He wanted to reduce it to O(n) which I was not able to do."
},
{
"code": null,
"e": 31744,
"s": 31724,
"text": "Verdict: Rejected. "
},
{
"code": null,
"e": 31756,
"s": 31744,
"text": "Conclusion:"
},
{
"code": null,
"e": 32381,
"s": 31756,
"text": "I felt relaxed. Because they contacted me in May 2021 and scheduled the first round in 17th Sept 2021 which they rescheduled at the end moment to next week since they were not available. Thank god I didn’t take leave early from my current organization. Then on the interview day, the first round didn’t happen because the guy was not available. The coding people didn’t give any hints. The last interviewer was horrific. He became dead silent after asking the question. When he spoke he had too much arrogance in his voice. Please dont keep such people who are there to satisfy their ego. Thank god I didn’t answer properly."
},
{
"code": null,
"e": 32391,
"s": 32381,
"text": "Marketing"
},
{
"code": null,
"e": 32398,
"s": 32391,
"text": "Nvidia"
},
{
"code": null,
"e": 32420,
"s": 32398,
"text": "Interview Experiences"
},
{
"code": null,
"e": 32427,
"s": 32420,
"text": "Nvidia"
},
{
"code": null,
"e": 32525,
"s": 32427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32576,
"s": 32525,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 32618,
"s": 32576,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 32654,
"s": 32618,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 32710,
"s": 32654,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 32738,
"s": 32710,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 32776,
"s": 32738,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 32815,
"s": 32776,
"text": "EPAM Interview Experience (Off-Campus)"
},
{
"code": null,
"e": 32861,
"s": 32815,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 32933,
"s": 32861,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
}
] |
How to Structure my Application in Express.js ? - GeeksforGeeks | 07 Dec, 2021
Express is a minimalistic framework that is used to create web servers. It is built upon the HTTP module of node.js and provides a much easier way to manage the code related to the server.
In this article, we are going to discuss how we can structure our express application.
Create Node Project:
Step 1: As the express application is built upon NodeJS so first of all, we have to initialize a node project, write the command below in your terminal.
npm init
Step 2: Install Packages
npm install express
Step 3: Create an app.js file. In this file, we write the entire code of the server.
touch app.js
Project Structure: After all of this, our project structure will look like this.
Configure the environment variable: While writing server code several times we need some constant variable in the entire codebase, so we should set some kind of environment variable so that it can be available in all files.This module is used to load environment variables from the .env file to the process object so that later we can easily use these variables anywhere in the codebase.
npm install dotenv
.env
PORT=3000 // This will be available as process.env.PORT // You can write any variable here.
Structure of app.js file: Imports are the first thing that should be written inside this file and then some kind of initialization can be there, and later there should be middlewares which are related to entire routes. For example, it can be the express.json() middleware which is used to parse the incoming requests as JSON. After all of this, we can write our routes to execute the particular functionality when the user requests the URL which is starting from the string given inside the middleware.In the end, we can start our server to listen to the client requests. It is safer to establish the database connection first if we are concerned about data persistence.
app.js
// 3rd Party Modulesconst express = require('express');require('dotenv/config'); // Local Modulesconst myRoute = require('./routes/myRoute.js'); // Server Initializationconst app = express();const PORT = process.env.PORT; // Middlewaresapp.use(express.json()); // Routes will be written hereapp.use('/route', myRoute); // Server Listen Along with Database // connection(in case of data persistence)app.listen(PORT, (error) =>{ if(!error) console.log("Server is Successfully Running, and App is listening on port "+ PORT) else console.log("Error occured, server can't start", error); });
Setting up Controllers and Route: Routes are the endpoints of HTTP requests to the server or can say a few ways through which a client can interact with the server, we often need a lot of routes in our app so it is a convenient way to set them up beforehand.The controllers are nothing but the code which is going to execute when a client accesses some route. This code can consist of several lines that’s why we separate it from routes files.
myController.j
// Methods to be executed on routesconst method1 = (req, res)=>{ res.send("Hello, Welcome to our Page");} const method2 = (req, res)=>{ res.send("Hello, This was a post Request");} // Export of all methods as objectmodule.exports = { method1, method2}
myRoute.js
// 3rd Party Modulesconst { Router } = require('express'); // Local Modulesconst myController = require('../controllers/myController'); // Initializationconst router = Router(); // Requests router.get('/', myController.method1);router.post('/', myController.method2); module.exports = router;
Step to run the application: We can run our express application with the command below, The app.js is the entry point of this application.
node app.js
After the server is successfully running we can start interacting with it, here is one example of GET request via browser,
Output:
Additional Points:
While running the server with node command it keeps running on the basis of the last saved files, if you want the server to be interactive and want to re-run the server every time the code changes, you can use nodemon.Usually, the server is made up of several APIs so that clients can interact, in case if you want to log details of requests which are striking on the server, you can use morgan. It’s just a convenient way to know what’s going on the server.
While running the server with node command it keeps running on the basis of the last saved files, if you want the server to be interactive and want to re-run the server every time the code changes, you can use nodemon.
Usually, the server is made up of several APIs so that clients can interact, in case if you want to log details of requests which are striking on the server, you can use morgan. It’s just a convenient way to know what’s going on the server.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 26456,
"s": 26267,
"text": "Express is a minimalistic framework that is used to create web servers. It is built upon the HTTP module of node.js and provides a much easier way to manage the code related to the server."
},
{
"code": null,
"e": 26543,
"s": 26456,
"text": "In this article, we are going to discuss how we can structure our express application."
},
{
"code": null,
"e": 26564,
"s": 26543,
"text": "Create Node Project:"
},
{
"code": null,
"e": 26717,
"s": 26564,
"text": "Step 1: As the express application is built upon NodeJS so first of all, we have to initialize a node project, write the command below in your terminal."
},
{
"code": null,
"e": 26726,
"s": 26717,
"text": "npm init"
},
{
"code": null,
"e": 26753,
"s": 26728,
"text": "Step 2: Install Packages"
},
{
"code": null,
"e": 26773,
"s": 26753,
"text": "npm install express"
},
{
"code": null,
"e": 26858,
"s": 26773,
"text": "Step 3: Create an app.js file. In this file, we write the entire code of the server."
},
{
"code": null,
"e": 26871,
"s": 26858,
"text": "touch app.js"
},
{
"code": null,
"e": 26952,
"s": 26871,
"text": "Project Structure: After all of this, our project structure will look like this."
},
{
"code": null,
"e": 27340,
"s": 26952,
"text": "Configure the environment variable: While writing server code several times we need some constant variable in the entire codebase, so we should set some kind of environment variable so that it can be available in all files.This module is used to load environment variables from the .env file to the process object so that later we can easily use these variables anywhere in the codebase."
},
{
"code": null,
"e": 27360,
"s": 27340,
"text": "npm install dotenv "
},
{
"code": null,
"e": 27365,
"s": 27360,
"text": ".env"
},
{
"code": "PORT=3000 // This will be available as process.env.PORT // You can write any variable here.",
"e": 27458,
"s": 27365,
"text": null
},
{
"code": null,
"e": 28129,
"s": 27458,
"text": "Structure of app.js file: Imports are the first thing that should be written inside this file and then some kind of initialization can be there, and later there should be middlewares which are related to entire routes. For example, it can be the express.json() middleware which is used to parse the incoming requests as JSON. After all of this, we can write our routes to execute the particular functionality when the user requests the URL which is starting from the string given inside the middleware.In the end, we can start our server to listen to the client requests. It is safer to establish the database connection first if we are concerned about data persistence."
},
{
"code": null,
"e": 28136,
"s": 28129,
"text": "app.js"
},
{
"code": "// 3rd Party Modulesconst express = require('express');require('dotenv/config'); // Local Modulesconst myRoute = require('./routes/myRoute.js'); // Server Initializationconst app = express();const PORT = process.env.PORT; // Middlewaresapp.use(express.json()); // Routes will be written hereapp.use('/route', myRoute); // Server Listen Along with Database // connection(in case of data persistence)app.listen(PORT, (error) =>{ if(!error) console.log(\"Server is Successfully Running, and App is listening on port \"+ PORT) else console.log(\"Error occured, server can't start\", error); });",
"e": 28772,
"s": 28136,
"text": null
},
{
"code": null,
"e": 29216,
"s": 28772,
"text": "Setting up Controllers and Route: Routes are the endpoints of HTTP requests to the server or can say a few ways through which a client can interact with the server, we often need a lot of routes in our app so it is a convenient way to set them up beforehand.The controllers are nothing but the code which is going to execute when a client accesses some route. This code can consist of several lines that’s why we separate it from routes files."
},
{
"code": null,
"e": 29231,
"s": 29216,
"text": "myController.j"
},
{
"code": "// Methods to be executed on routesconst method1 = (req, res)=>{ res.send(\"Hello, Welcome to our Page\");} const method2 = (req, res)=>{ res.send(\"Hello, This was a post Request\");} // Export of all methods as objectmodule.exports = { method1, method2}",
"e": 29497,
"s": 29231,
"text": null
},
{
"code": null,
"e": 29508,
"s": 29497,
"text": "myRoute.js"
},
{
"code": "// 3rd Party Modulesconst { Router } = require('express'); // Local Modulesconst myController = require('../controllers/myController'); // Initializationconst router = Router(); // Requests router.get('/', myController.method1);router.post('/', myController.method2); module.exports = router;",
"e": 29805,
"s": 29508,
"text": null
},
{
"code": null,
"e": 29944,
"s": 29805,
"text": "Step to run the application: We can run our express application with the command below, The app.js is the entry point of this application."
},
{
"code": null,
"e": 29956,
"s": 29944,
"text": "node app.js"
},
{
"code": null,
"e": 30079,
"s": 29956,
"text": "After the server is successfully running we can start interacting with it, here is one example of GET request via browser,"
},
{
"code": null,
"e": 30087,
"s": 30079,
"text": "Output:"
},
{
"code": null,
"e": 30106,
"s": 30087,
"text": "Additional Points:"
},
{
"code": null,
"e": 30565,
"s": 30106,
"text": "While running the server with node command it keeps running on the basis of the last saved files, if you want the server to be interactive and want to re-run the server every time the code changes, you can use nodemon.Usually, the server is made up of several APIs so that clients can interact, in case if you want to log details of requests which are striking on the server, you can use morgan. It’s just a convenient way to know what’s going on the server."
},
{
"code": null,
"e": 30784,
"s": 30565,
"text": "While running the server with node command it keeps running on the basis of the last saved files, if you want the server to be interactive and want to re-run the server every time the code changes, you can use nodemon."
},
{
"code": null,
"e": 31025,
"s": 30784,
"text": "Usually, the server is made up of several APIs so that clients can interact, in case if you want to log details of requests which are striking on the server, you can use morgan. It’s just a convenient way to know what’s going on the server."
},
{
"code": null,
"e": 31036,
"s": 31025,
"text": "Express.js"
},
{
"code": null,
"e": 31053,
"s": 31036,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 31060,
"s": 31053,
"text": "Picked"
},
{
"code": null,
"e": 31068,
"s": 31060,
"text": "Node.js"
},
{
"code": null,
"e": 31085,
"s": 31068,
"text": "Web Technologies"
},
{
"code": null,
"e": 31183,
"s": 31085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31253,
"s": 31183,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 31292,
"s": 31253,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 31314,
"s": 31292,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 31339,
"s": 31314,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 31366,
"s": 31339,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 31406,
"s": 31366,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31451,
"s": 31406,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31494,
"s": 31451,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31544,
"s": 31494,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Scroll to the top of the page using JavaScript/jQuery - GeeksforGeeks | 03 Aug, 2021
A scrollable page can be scrolled to the top using 2 approaches:
Method 1: Using window.scrollTo()The scrollTo() method of the window Interface can be used to scroll to a specified location on the page. It accepts 2 parameters the x and y coordinate of the page to scroll to. Passing both the parameters as 0 will scroll the page to the topmost and leftmost point.
Syntax:
window.scrollTo(x-coordinate, y-coordinate)
Example:
<!DOCTYPE html><html> <head> <title> Scroll to the top of the page using JavaScript/jQuery? </title> <style> .scroll { height: 1000px; background-color: lightgreen; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>Scroll to the top of the page using JavaScript/jQuery?</b> <p>Click on the button below to scroll to the top of the page.</p> <p class="scroll">GeeksforGeeks is a computer science portal. This is a large scrollable area.</p> <button onclick="scrollToTop()"> Click to scroll to top </button> <script> function scrollToTop() { window.scrollTo(0, 0); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Using scrollTo() in jQuery
In jQuery, the scrollTo() method is used to set or return the vertical scrollbar position for a selected element. This behavior can be used to scroll to the top of the page by applying this method on the window property. Setting the position parameter to 0 scrolls the page to the top.
Syntax:
$(window).scrollTop(position);
Example:
<!DOCTYPE html><html> <head> <title> Scroll to the top of the page using JavaScript/jQuery? </title> <style> .scroll { height: 1000px; background-color: lightgreen; } </style> </head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Scroll to the top of the page using JavaScript/jQuery? </b> <p> Click on the button below to scroll to the top of the page. </p> <p class="scroll"> GeeksforGeeks is a computer science portal. This is a large scrollable area. </p> <button onclick="scrollToTop()"> Click to scroll to top </button> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script> function scrollToTop() { $(window).scrollTop(0); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JavaScript
JQuery
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
Difference Between PUT and PATCH Request
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ? | [
{
"code": null,
"e": 26363,
"s": 26335,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 26428,
"s": 26363,
"text": "A scrollable page can be scrolled to the top using 2 approaches:"
},
{
"code": null,
"e": 26728,
"s": 26428,
"text": "Method 1: Using window.scrollTo()The scrollTo() method of the window Interface can be used to scroll to a specified location on the page. It accepts 2 parameters the x and y coordinate of the page to scroll to. Passing both the parameters as 0 will scroll the page to the topmost and leftmost point."
},
{
"code": null,
"e": 26736,
"s": 26728,
"text": "Syntax:"
},
{
"code": null,
"e": 26780,
"s": 26736,
"text": "window.scrollTo(x-coordinate, y-coordinate)"
},
{
"code": null,
"e": 26789,
"s": 26780,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Scroll to the top of the page using JavaScript/jQuery? </title> <style> .scroll { height: 1000px; background-color: lightgreen; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>Scroll to the top of the page using JavaScript/jQuery?</b> <p>Click on the button below to scroll to the top of the page.</p> <p class=\"scroll\">GeeksforGeeks is a computer science portal. This is a large scrollable area.</p> <button onclick=\"scrollToTop()\"> Click to scroll to top </button> <script> function scrollToTop() { window.scrollTo(0, 0); } </script></body> </html>",
"e": 27555,
"s": 26789,
"text": null
},
{
"code": null,
"e": 27563,
"s": 27555,
"text": "Output:"
},
{
"code": null,
"e": 27591,
"s": 27563,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27618,
"s": 27591,
"text": "After clicking the button:"
},
{
"code": null,
"e": 27655,
"s": 27618,
"text": "Method 2: Using scrollTo() in jQuery"
},
{
"code": null,
"e": 27941,
"s": 27655,
"text": "In jQuery, the scrollTo() method is used to set or return the vertical scrollbar position for a selected element. This behavior can be used to scroll to the top of the page by applying this method on the window property. Setting the position parameter to 0 scrolls the page to the top."
},
{
"code": null,
"e": 27949,
"s": 27941,
"text": "Syntax:"
},
{
"code": null,
"e": 27980,
"s": 27949,
"text": "$(window).scrollTop(position);"
},
{
"code": null,
"e": 27989,
"s": 27980,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Scroll to the top of the page using JavaScript/jQuery? </title> <style> .scroll { height: 1000px; background-color: lightgreen; } </style> </head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Scroll to the top of the page using JavaScript/jQuery? </b> <p> Click on the button below to scroll to the top of the page. </p> <p class=\"scroll\"> GeeksforGeeks is a computer science portal. This is a large scrollable area. </p> <button onclick=\"scrollToTop()\"> Click to scroll to top </button> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script> function scrollToTop() { $(window).scrollTop(0); } </script></body> </html>",
"e": 28842,
"s": 27989,
"text": null
},
{
"code": null,
"e": 28850,
"s": 28842,
"text": "Output:"
},
{
"code": null,
"e": 28878,
"s": 28850,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 28905,
"s": 28878,
"text": "After clicking the button:"
},
{
"code": null,
"e": 29124,
"s": 28905,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 29392,
"s": 29124,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 29404,
"s": 29392,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29411,
"s": 29404,
"text": "Picked"
},
{
"code": null,
"e": 29422,
"s": 29411,
"text": "JavaScript"
},
{
"code": null,
"e": 29429,
"s": 29422,
"text": "JQuery"
},
{
"code": null,
"e": 29446,
"s": 29429,
"text": "Web Technologies"
},
{
"code": null,
"e": 29544,
"s": 29446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29584,
"s": 29544,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29629,
"s": 29584,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29690,
"s": 29629,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29762,
"s": 29690,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29803,
"s": 29762,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29849,
"s": 29803,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 29878,
"s": 29849,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29941,
"s": 29878,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 30018,
"s": 29941,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Thread get_id() function in C++ - GeeksforGeeks | 16 Jun, 2021
Thread::get_id() is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the value of std::thread::id thus identifying the thread associated with *this.Syntax:
thread_name.get_id();
Parameters: This function does not accept any parameters.Return Value: This method returns a value of type std::thread::id identifying the thread associated with *this i.e. the thread which was used to call the get_id function is returned. The default constructed std::thread::id is returned when no such thread is identified.Below examples demonstrates the use of std::thread::get_id() method:Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”.
CPP
// C++ program to demonstrate the use of// std::thread::get_id #include <chrono>#include <iostream>#include <thread>using namespace std; // util function for thread creationvoid sleepThread(){ this_thread::sleep_for(chrono::seconds(1));} int main(){ // creating thread1 and thread2 thread thread1(sleepThread); thread thread2(sleepThread); thread::id t1_id = thread1.get_id(); thread::id t2_id = thread2.get_id(); cout << "ID associated with thread1= " << t1_id << endl; cout << "ID associated with thread2= " << t2_id << endl; thread1.join(); thread2.join(); return 0;}
Possible Output:
ID associated with thread1= 139858743162624
ID associated with thread2= 139858734769920
adnanirshad158
CPP-Functions
Processes & Threads
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n16 Jun, 2021"
},
{
"code": null,
"e": 25617,
"s": 25343,
"text": "Thread::get_id() is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the value of std::thread::id thus identifying the thread associated with *this.Syntax: "
},
{
"code": null,
"e": 25639,
"s": 25617,
"text": "thread_name.get_id();"
},
{
"code": null,
"e": 26219,
"s": 25639,
"text": "Parameters: This function does not accept any parameters.Return Value: This method returns a value of type std::thread::id identifying the thread associated with *this i.e. the thread which was used to call the get_id function is returned. The default constructed std::thread::id is returned when no such thread is identified.Below examples demonstrates the use of std::thread::get_id() method:Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”. "
},
{
"code": null,
"e": 26223,
"s": 26219,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate the use of// std::thread::get_id #include <chrono>#include <iostream>#include <thread>using namespace std; // util function for thread creationvoid sleepThread(){ this_thread::sleep_for(chrono::seconds(1));} int main(){ // creating thread1 and thread2 thread thread1(sleepThread); thread thread2(sleepThread); thread::id t1_id = thread1.get_id(); thread::id t2_id = thread2.get_id(); cout << \"ID associated with thread1= \" << t1_id << endl; cout << \"ID associated with thread2= \" << t2_id << endl; thread1.join(); thread2.join(); return 0;}",
"e": 26848,
"s": 26223,
"text": null
},
{
"code": null,
"e": 26867,
"s": 26848,
"text": "Possible Output: "
},
{
"code": null,
"e": 26955,
"s": 26867,
"text": "ID associated with thread1= 139858743162624\nID associated with thread2= 139858734769920"
},
{
"code": null,
"e": 26972,
"s": 26957,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26986,
"s": 26972,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27006,
"s": 26986,
"text": "Processes & Threads"
},
{
"code": null,
"e": 27010,
"s": 27006,
"text": "C++"
},
{
"code": null,
"e": 27023,
"s": 27010,
"text": "C++ Programs"
},
{
"code": null,
"e": 27027,
"s": 27023,
"text": "CPP"
},
{
"code": null,
"e": 27125,
"s": 27027,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27153,
"s": 27125,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27173,
"s": 27153,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27206,
"s": 27173,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27230,
"s": 27206,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27255,
"s": 27230,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27290,
"s": 27255,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27334,
"s": 27290,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 27393,
"s": 27334,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27419,
"s": 27393,
"text": "C++ Program for QuickSort"
}
] |
How to make Tabs using Angular UI Bootstrap ? - GeeksforGeeks | 17 Jun, 2021
In this article we will see how to make Tabs using Angular UI bootstrap. Angular UI Bootstrap is an Angular JS framework created by Angular UI developers for providing better UI which can be used easily.
Download AngularUI from the link:
https://angular-ui.github.io/bootstrap
Approach:
First, add Angular UI bootstrap scripts needed for your project.
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js”></script><script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js”></script><script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js”></script><script src=”https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js”></script>
Make tab with its UIBootStrap classes which will set the UI look for the tab.
Now make different types of tab using different classes and run the code.
Example 1: Making tabs with justified content.
HTML
<!DOCTYPE html><html ng-app="gfg"> <head> <!-- Adding CDN scripts required for our page --> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"> </script> <script src= "https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"> </script> <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script> // Adding Modules angular.module('gfg', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']); angular.module('gfg').controller('tab', function ($scope) { }); </script> </head> <body> <div ng-controller="tab" style="padding: 10px; margin: 10px; border-style: double;"> <!-- making a tab --> <uib-tabset active="activeJustified" justified="true"> <uib-tab index="0" heading="Column-1"> Column-1 Content </uib-tab> <uib-tab index="1" heading="Column-2"> Column-2 Content </uib-tab> <uib-tab index="2" heading="Column-3"> Column-3 Content </uib-tab> </uib-tabset> </div> </body></html>
Output:
Example 2:
HTML
<!DOCTYPE html><html ng-app="gfg"> <head> <!-- Adding CDN scripts required for our page --> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"> </script> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"> </script> <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"> </script> <link href= "https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script> // Adding Modules angular.module('gfg', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']); angular.module('gfg').controller('tab', function ($scope) { }); </script> </head> <body> <div ng-controller="tab" style="padding: 10px; margin: 10px; border-style: double;"> <!-- making a tab --> <uib-tabset active="activePill" vertical="true" type="pills"> <uib-tab index="0" heading="Row-1"> Row-1 Content </uib-tab> <uib-tab index="1" heading="Row-2"> Row-2 Content </uib-tab> <uib-tab index="2" heading="Row-3"> Row-3 Content </uib-tab> </uib-tabset> </div> </body></html>
Output:
Reference: https://angular-ui.github.io/bootstrap/#!#Tabs
AngularUI-Bootstrap
AngularJS
Bootstrap
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
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ? | [
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 26558,
"s": 26354,
"text": "In this article we will see how to make Tabs using Angular UI bootstrap. Angular UI Bootstrap is an Angular JS framework created by Angular UI developers for providing better UI which can be used easily."
},
{
"code": null,
"e": 26592,
"s": 26558,
"text": "Download AngularUI from the link:"
},
{
"code": null,
"e": 26631,
"s": 26592,
"text": "https://angular-ui.github.io/bootstrap"
},
{
"code": null,
"e": 26642,
"s": 26631,
"text": "Approach: "
},
{
"code": null,
"e": 26707,
"s": 26642,
"text": "First, add Angular UI bootstrap scripts needed for your project."
},
{
"code": null,
"e": 27078,
"s": 26707,
"text": "<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js”></script><script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js”></script><script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js”></script><script src=”https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js”></script>"
},
{
"code": null,
"e": 27156,
"s": 27078,
"text": "Make tab with its UIBootStrap classes which will set the UI look for the tab."
},
{
"code": null,
"e": 27230,
"s": 27156,
"text": "Now make different types of tab using different classes and run the code."
},
{
"code": null,
"e": 27279,
"s": 27232,
"text": "Example 1: Making tabs with justified content."
},
{
"code": null,
"e": 27284,
"s": 27279,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html ng-app=\"gfg\"> <head> <!-- Adding CDN scripts required for our page --> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js\"> </script> <script src= \"https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js\"> </script> <link href=\"https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" rel=\"stylesheet\"> <script> // Adding Modules angular.module('gfg', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']); angular.module('gfg').controller('tab', function ($scope) { }); </script> </head> <body> <div ng-controller=\"tab\" style=\"padding: 10px; margin: 10px; border-style: double;\"> <!-- making a tab --> <uib-tabset active=\"activeJustified\" justified=\"true\"> <uib-tab index=\"0\" heading=\"Column-1\"> Column-1 Content </uib-tab> <uib-tab index=\"1\" heading=\"Column-2\"> Column-2 Content </uib-tab> <uib-tab index=\"2\" heading=\"Column-3\"> Column-3 Content </uib-tab> </uib-tabset> </div> </body></html>",
"e": 28613,
"s": 27284,
"text": null
},
{
"code": null,
"e": 28621,
"s": 28613,
"text": "Output:"
},
{
"code": null,
"e": 28632,
"s": 28621,
"text": "Example 2:"
},
{
"code": null,
"e": 28637,
"s": 28632,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html ng-app=\"gfg\"> <head> <!-- Adding CDN scripts required for our page --> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js\"> </script> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js\"> </script> <script src=\"https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js\"> </script> <link href= \"https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" rel=\"stylesheet\"> <script> // Adding Modules angular.module('gfg', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']); angular.module('gfg').controller('tab', function ($scope) { }); </script> </head> <body> <div ng-controller=\"tab\" style=\"padding: 10px; margin: 10px; border-style: double;\"> <!-- making a tab --> <uib-tabset active=\"activePill\" vertical=\"true\" type=\"pills\"> <uib-tab index=\"0\" heading=\"Row-1\"> Row-1 Content </uib-tab> <uib-tab index=\"1\" heading=\"Row-2\"> Row-2 Content </uib-tab> <uib-tab index=\"2\" heading=\"Row-3\"> Row-3 Content </uib-tab> </uib-tabset> </div> </body></html>",
"e": 29995,
"s": 28637,
"text": null
},
{
"code": null,
"e": 30003,
"s": 29995,
"text": "Output:"
},
{
"code": null,
"e": 30061,
"s": 30003,
"text": "Reference: https://angular-ui.github.io/bootstrap/#!#Tabs"
},
{
"code": null,
"e": 30081,
"s": 30061,
"text": "AngularUI-Bootstrap"
},
{
"code": null,
"e": 30091,
"s": 30081,
"text": "AngularJS"
},
{
"code": null,
"e": 30101,
"s": 30091,
"text": "Bootstrap"
},
{
"code": null,
"e": 30118,
"s": 30101,
"text": "Web Technologies"
},
{
"code": null,
"e": 30216,
"s": 30118,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30251,
"s": 30216,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 30286,
"s": 30251,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 30310,
"s": 30286,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 30345,
"s": 30310,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 30398,
"s": 30345,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 30448,
"s": 30398,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 30477,
"s": 30448,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30518,
"s": 30477,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 30574,
"s": 30518,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
}
] |
How to get the first element of an array in PHP? - GeeksforGeeks | 02 Dec, 2021
In this article, we will see how to get access to the first element of an array in PHP, & also understand their implementation through the examples. There are mainly 3 types of arrays in PHP that can be used to fetch the elements from the array:
Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value.
Associative Array: It is used to store key-value pairs.
Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays.
There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.
By direct accessing the 0th index:
PHP
<?php // PHP program to access the first // element of the array $array = array('geeks', 'for', 'computer'); echo $array[0];?>
Output:
geeks
Using foreach loop: The foreach construct works on both array and objects. The foreach loop iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.
Syntax:
foreach( $array as $key => $element) {
// PHP Code to be executed
}
Example: This example illustrates the foreach loop in PHP.
PHP
<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); foreach($array as $name) { echo $name; // Break loop after first iteration break; }?>
Output:
geeks
Using reset() function: The reset() function is used to move the array’s internal pointer to the first element.
Syntax:
reset($array)
Example: This example illustrates the use of the reset() function that helps to move any array’s internal pointer to the first element of that array.
PHP
<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); echo reset($array);?>
Output:
geeks
Using array_slice() function: array_slice() returns the sequence of elements from the array as specified by the offset and length parameters.
Syntax:
array array_slice ( array $array, int $offset [, int $length = NULL [,
bool $preserve_keys = FALSE ]] )
Example: This example illustrates the array_slice() Function to fetch a part of an array by slicing through it, according to the user’s choice.
PHP
<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); echo array_slice($array, 0, 1)[0];?>
Output:
geeks
Using array_values() function: This function return an array of values from another array that may contain key-value pairs or just values.
Syntax:
array array_values ( array $array )
Example: This example describes the use of the array_values() function.
PHP
<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); echo array_values($array)[0];?>
Output:
geeks
Using array_pop() function: This function pop the element off the end of the array.
Syntax:
mixed array_pop ( array &$array )
By default, the array_reverse() function will reset all numerical array keys to start counting from zero while literal keys will remain unchanged unless a second parameter preserve_keys is specified as TRUE. This method is not recommended as it may do unwanted longer processing on larger arrays to reverse them prior to getting the first value.
Example: This example describes the use of the array_pop function.
PHP
<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); $arr = array_reverse($array); echo array_pop($arr);?>
Output:
geeks
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
bhaskargeeksforgeeks
PHP-array
PHP-function
PHP-Questions
Picked
PHP
PHP Programs
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
How to pass JavaScript variables to PHP ? | [
{
"code": null,
"e": 26839,
"s": 26811,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 27085,
"s": 26839,
"text": "In this article, we will see how to get access to the first element of an array in PHP, & also understand their implementation through the examples. There are mainly 3 types of arrays in PHP that can be used to fetch the elements from the array:"
},
{
"code": null,
"e": 27228,
"s": 27085,
"text": "Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value."
},
{
"code": null,
"e": 27284,
"s": 27228,
"text": "Associative Array: It is used to store key-value pairs."
},
{
"code": null,
"e": 27469,
"s": 27284,
"text": "Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays. "
},
{
"code": null,
"e": 27755,
"s": 27469,
"text": "There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially."
},
{
"code": null,
"e": 27790,
"s": 27755,
"text": "By direct accessing the 0th index:"
},
{
"code": null,
"e": 27794,
"s": 27790,
"text": "PHP"
},
{
"code": "<?php // PHP program to access the first // element of the array $array = array('geeks', 'for', 'computer'); echo $array[0];?>",
"e": 27930,
"s": 27794,
"text": null
},
{
"code": null,
"e": 27938,
"s": 27930,
"text": "Output:"
},
{
"code": null,
"e": 27944,
"s": 27938,
"text": "geeks"
},
{
"code": null,
"e": 28150,
"s": 27944,
"text": "Using foreach loop: The foreach construct works on both array and objects. The foreach loop iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively."
},
{
"code": null,
"e": 28158,
"s": 28150,
"text": "Syntax:"
},
{
"code": null,
"e": 28230,
"s": 28158,
"text": "foreach( $array as $key => $element) {\n // PHP Code to be executed\n}"
},
{
"code": null,
"e": 28289,
"s": 28230,
"text": "Example: This example illustrates the foreach loop in PHP."
},
{
"code": null,
"e": 28293,
"s": 28289,
"text": "PHP"
},
{
"code": "<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); foreach($array as $name) { echo $name; // Break loop after first iteration break; }?>",
"e": 28555,
"s": 28293,
"text": null
},
{
"code": null,
"e": 28563,
"s": 28555,
"text": "Output:"
},
{
"code": null,
"e": 28569,
"s": 28563,
"text": "geeks"
},
{
"code": null,
"e": 28681,
"s": 28569,
"text": "Using reset() function: The reset() function is used to move the array’s internal pointer to the first element."
},
{
"code": null,
"e": 28689,
"s": 28681,
"text": "Syntax:"
},
{
"code": null,
"e": 28703,
"s": 28689,
"text": "reset($array)"
},
{
"code": null,
"e": 28853,
"s": 28703,
"text": "Example: This example illustrates the use of the reset() function that helps to move any array’s internal pointer to the first element of that array."
},
{
"code": null,
"e": 28857,
"s": 28853,
"text": "PHP"
},
{
"code": "<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); echo reset($array);?>",
"e": 29032,
"s": 28857,
"text": null
},
{
"code": null,
"e": 29040,
"s": 29032,
"text": "Output:"
},
{
"code": null,
"e": 29046,
"s": 29040,
"text": "geeks"
},
{
"code": null,
"e": 29188,
"s": 29046,
"text": "Using array_slice() function: array_slice() returns the sequence of elements from the array as specified by the offset and length parameters."
},
{
"code": null,
"e": 29196,
"s": 29188,
"text": "Syntax:"
},
{
"code": null,
"e": 29341,
"s": 29196,
"text": "array array_slice ( array $array, int $offset [, int $length = NULL [, \n bool $preserve_keys = FALSE ]] )"
},
{
"code": null,
"e": 29485,
"s": 29341,
"text": "Example: This example illustrates the array_slice() Function to fetch a part of an array by slicing through it, according to the user’s choice."
},
{
"code": null,
"e": 29489,
"s": 29485,
"text": "PHP"
},
{
"code": "<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); echo array_slice($array, 0, 1)[0];?>",
"e": 29682,
"s": 29489,
"text": null
},
{
"code": null,
"e": 29690,
"s": 29682,
"text": "Output:"
},
{
"code": null,
"e": 29696,
"s": 29690,
"text": "geeks"
},
{
"code": null,
"e": 29835,
"s": 29696,
"text": "Using array_values() function: This function return an array of values from another array that may contain key-value pairs or just values."
},
{
"code": null,
"e": 29843,
"s": 29835,
"text": "Syntax:"
},
{
"code": null,
"e": 29879,
"s": 29843,
"text": "array array_values ( array $array )"
},
{
"code": null,
"e": 29951,
"s": 29879,
"text": "Example: This example describes the use of the array_values() function."
},
{
"code": null,
"e": 29955,
"s": 29951,
"text": "PHP"
},
{
"code": "<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); echo array_values($array)[0];?>",
"e": 30143,
"s": 29955,
"text": null
},
{
"code": null,
"e": 30151,
"s": 30143,
"text": "Output:"
},
{
"code": null,
"e": 30157,
"s": 30151,
"text": "geeks"
},
{
"code": null,
"e": 30241,
"s": 30157,
"text": "Using array_pop() function: This function pop the element off the end of the array."
},
{
"code": null,
"e": 30249,
"s": 30241,
"text": "Syntax:"
},
{
"code": null,
"e": 30283,
"s": 30249,
"text": "mixed array_pop ( array &$array )"
},
{
"code": null,
"e": 30629,
"s": 30283,
"text": "By default, the array_reverse() function will reset all numerical array keys to start counting from zero while literal keys will remain unchanged unless a second parameter preserve_keys is specified as TRUE. This method is not recommended as it may do unwanted longer processing on larger arrays to reverse them prior to getting the first value."
},
{
"code": null,
"e": 30696,
"s": 30629,
"text": "Example: This example describes the use of the array_pop function."
},
{
"code": null,
"e": 30700,
"s": 30696,
"text": "PHP"
},
{
"code": "<?php // PHP program to access the first // element of the array $array = array( 33 => 'geeks', 36 => 'for', 42 => 'computer' ); $arr = array_reverse($array); echo array_pop($arr);?>",
"e": 30922,
"s": 30700,
"text": null
},
{
"code": null,
"e": 30930,
"s": 30922,
"text": "Output:"
},
{
"code": null,
"e": 30936,
"s": 30930,
"text": "geeks"
},
{
"code": null,
"e": 31105,
"s": 30936,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 31126,
"s": 31105,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 31136,
"s": 31126,
"text": "PHP-array"
},
{
"code": null,
"e": 31149,
"s": 31136,
"text": "PHP-function"
},
{
"code": null,
"e": 31163,
"s": 31149,
"text": "PHP-Questions"
},
{
"code": null,
"e": 31170,
"s": 31163,
"text": "Picked"
},
{
"code": null,
"e": 31174,
"s": 31170,
"text": "PHP"
},
{
"code": null,
"e": 31187,
"s": 31174,
"text": "PHP Programs"
},
{
"code": null,
"e": 31191,
"s": 31187,
"text": "PHP"
},
{
"code": null,
"e": 31289,
"s": 31191,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31339,
"s": 31289,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 31379,
"s": 31339,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 31424,
"s": 31379,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 31451,
"s": 31424,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 31487,
"s": 31451,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 31537,
"s": 31487,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 31577,
"s": 31537,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 31629,
"s": 31577,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 31656,
"s": 31629,
"text": "Comparing two dates in PHP"
}
] |
Replace a DOM element with another DOM element in place - GeeksforGeeks | 16 Feb, 2021
The task is to replace an element by another element in place using JavaScript. Below are the few methods:
parentNode Property: This property returns the parent node of the defined node, as a Node object.Syntax:node.parentNode
Return value:It returns a node object, which represents the parent node of a node, or null if there is no parent.
node.parentNode
Return value:It returns a node object, which represents the parent node of a node, or null if there is no parent.
replaceChild() Method: This method replaces a child node with a new node. This new node can be an existing node in the document, or can be newly created.Syntax:node.replaceChild(newNode, oldNode)
Parameters:newNode: This parameter is required. It specifies the node object to insert.oldNode: This parameter is required. It specifies the node object to remove.Return value:It returns a node object, which represents the replaced node.
node.replaceChild(newNode, oldNode)
Parameters:
newNode: This parameter is required. It specifies the node object to insert.
oldNode: This parameter is required. It specifies the node object to remove.
Return value:It returns a node object, which represents the replaced node.
Example 1: This example creates a new <span> element and replace it with the <a> element using parentNode property and replace() method.
<!DOCTYPE html><html> <head> <title> JavaScript | Replace dom element in place. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div> <a id="a" href="#">GeeksforGeeks</a> </div> <br> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = 'Click button to replace <a> element in DOM'; el_up.innerHTML = today; function gfg_Run() { var aEl = document.getElementById("a"); var newEl = document.createElement("span"); newEl.innerHTML = "replaced text!"; aEl.parentNode.replaceChild(newEl, aEl); el_down.innerHTML = "<a> element is replaced by the <span> element."; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example creates a new <a> element and replace it with the previous <a> element using parentNode property and replace() method keeping the href property same.
<!DOCTYPE html><html> <head> <title> JavaScript | Replace dom element in place. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div> <a id="a" href="https://www.geeksforgeeks.org">GeeksforGeeks</a> </div> <br> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = 'Click button to replace <a> element in DOM'; el_up.innerHTML = today; function gfg_Run() { var aEl = document.getElementById("a"); var newEl = document.createElement("a"); newEl.innerHTML = "New GFG link!"; newEl.href = "https://www.geeksforgeeks.org"; aEl.parentNode.replaceChild(newEl, aEl); el_down.innerHTML = "<a> element is replaced by the new <a> element."; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Google Chrome
Mozilla Firefox
Internet Explorer
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
arorakashish0911
HTML-DOM
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to 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
Hide or show elements in HTML using display property
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 39213,
"s": 39185,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 39320,
"s": 39213,
"text": "The task is to replace an element by another element in place using JavaScript. Below are the few methods:"
},
{
"code": null,
"e": 39554,
"s": 39320,
"text": "parentNode Property: This property returns the parent node of the defined node, as a Node object.Syntax:node.parentNode\nReturn value:It returns a node object, which represents the parent node of a node, or null if there is no parent."
},
{
"code": null,
"e": 39571,
"s": 39554,
"text": "node.parentNode\n"
},
{
"code": null,
"e": 39685,
"s": 39571,
"text": "Return value:It returns a node object, which represents the parent node of a node, or null if there is no parent."
},
{
"code": null,
"e": 40119,
"s": 39685,
"text": "replaceChild() Method: This method replaces a child node with a new node. This new node can be an existing node in the document, or can be newly created.Syntax:node.replaceChild(newNode, oldNode)\nParameters:newNode: This parameter is required. It specifies the node object to insert.oldNode: This parameter is required. It specifies the node object to remove.Return value:It returns a node object, which represents the replaced node."
},
{
"code": null,
"e": 40156,
"s": 40119,
"text": "node.replaceChild(newNode, oldNode)\n"
},
{
"code": null,
"e": 40168,
"s": 40156,
"text": "Parameters:"
},
{
"code": null,
"e": 40245,
"s": 40168,
"text": "newNode: This parameter is required. It specifies the node object to insert."
},
{
"code": null,
"e": 40322,
"s": 40245,
"text": "oldNode: This parameter is required. It specifies the node object to remove."
},
{
"code": null,
"e": 40397,
"s": 40322,
"text": "Return value:It returns a node object, which represents the replaced node."
},
{
"code": null,
"e": 40534,
"s": 40397,
"text": "Example 1: This example creates a new <span> element and replace it with the <a> element using parentNode property and replace() method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | Replace dom element in place. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div> <a id=\"a\" href=\"#\">GeeksforGeeks</a> </div> <br> <button onclick=\"gfg_Run()\"> Click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = 'Click button to replace <a> element in DOM'; el_up.innerHTML = today; function gfg_Run() { var aEl = document.getElementById(\"a\"); var newEl = document.createElement(\"span\"); newEl.innerHTML = \"replaced text!\"; aEl.parentNode.replaceChild(newEl, aEl); el_down.innerHTML = \"<a> element is replaced by the <span> element.\"; } </script></body> </html>",
"e": 41641,
"s": 40534,
"text": null
},
{
"code": null,
"e": 41649,
"s": 41641,
"text": "Output:"
},
{
"code": null,
"e": 41677,
"s": 41649,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 41704,
"s": 41677,
"text": "After clicking the button:"
},
{
"code": null,
"e": 41878,
"s": 41704,
"text": "Example 2: This example creates a new <a> element and replace it with the previous <a> element using parentNode property and replace() method keeping the href property same."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | Replace dom element in place. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div> <a id=\"a\" href=\"https://www.geeksforgeeks.org\">GeeksforGeeks</a> </div> <br> <button onclick=\"gfg_Run()\"> Click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = 'Click button to replace <a> element in DOM'; el_up.innerHTML = today; function gfg_Run() { var aEl = document.getElementById(\"a\"); var newEl = document.createElement(\"a\"); newEl.innerHTML = \"New GFG link!\"; newEl.href = \"https://www.geeksforgeeks.org\"; aEl.parentNode.replaceChild(newEl, aEl); el_down.innerHTML = \"<a> element is replaced by the new <a> element.\"; } </script></body> </html>",
"e": 43077,
"s": 41878,
"text": null
},
{
"code": null,
"e": 43085,
"s": 43077,
"text": "Output:"
},
{
"code": null,
"e": 43113,
"s": 43085,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 43140,
"s": 43113,
"text": "After clicking the button:"
},
{
"code": null,
"e": 43154,
"s": 43140,
"text": "Google Chrome"
},
{
"code": null,
"e": 43170,
"s": 43154,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 43188,
"s": 43170,
"text": "Internet Explorer"
},
{
"code": null,
"e": 43195,
"s": 43188,
"text": "Safari"
},
{
"code": null,
"e": 43201,
"s": 43195,
"text": "Opera"
},
{
"code": null,
"e": 43338,
"s": 43201,
"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": 43355,
"s": 43338,
"text": "arorakashish0911"
},
{
"code": null,
"e": 43364,
"s": 43355,
"text": "HTML-DOM"
},
{
"code": null,
"e": 43375,
"s": 43364,
"text": "JavaScript"
},
{
"code": null,
"e": 43473,
"s": 43375,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43513,
"s": 43473,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 43558,
"s": 43513,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 43619,
"s": 43558,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 43691,
"s": 43619,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 43760,
"s": 43691,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 43812,
"s": 43760,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 43839,
"s": 43812,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 43892,
"s": 43839,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 43938,
"s": 43892,
"text": "How to Open URL in New Tab using JavaScript ?"
}
] |
Some newly introduced array methods in JavaScript ES6 - GeeksforGeeks | 01 Oct, 2020
An array is used to store the elements of multiple data types in JavaScript altogether. Also, there are certain times when you have to manipulate the response received from the APIs as per the requirements on the webpages. Sometimes, the responses are objects and have to be converted to the arrays to perform the desired operations. These methods of array manipulation can save your time.
map() Method: It iterates over every element of the array and applies some functional condition and return the new array. It does not change the main array but returns the new array of transformed values. Also, it uses the shorthand notation of the arrow function to decrease the code in a single line.JavascriptJavascriptvar abc = [10, 20, 30, 40, 50];let xyz = abc.map(res => res * 2);console.log("The main array: ", abc);console.log("The modified array: ", xyz);Output:The main array: [10, 20, 30, 40, 50]
The modified array: [20, 40, 60, 80, 100]
Filter() Method: This method is useful when you want to find out the elements which pass a certain condition. It iterates over all the elements and returns an array with the ones which satisfy the condition.Also, it does not mutate the main array and creates the new one.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.filter(res => res > 35);console.log("The main array: ", abc);console.log("The modified array: ", xyz); Output:The main array : [10, 20, 30, 40, 50]
The modified array: [40, 50]
Note: The filter() method is widely compatible in IE because it belongs to ES5 and find() is introduced in ES6 so only the latest browsers (IE 11) are compatible with it.Find() Method: This method can be used when you want to find out the element which passes a certain condition. This is very similar to the filter() method but it returns the first element which satisfies the condition and does not iterate further.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50];let xyz = abc.find(res => res > 35);console.log("The main array: ", abc);console.log("The modified array: ", xyz);Output:The main array: [10, 20, 30, 40, 50]
The modified array: [40]
Reduce() Method: This function is useful when you want to reduce all the elements of the array to a single value. It can be used to simply find out the addition of all the elements in an array.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.reduce((element, iterator)=>iterator+element, 0);console.log("The addition is: ", xyz);Output:The addition is: 150
Also, you can initialize the value of the element variable to some other value as well.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50]; let xyz = abc.reduce((element, iterator) => iterator + element, 2000); console.log("The main array: ", abc); console.log("The addition is: ", xyz); Output:The main array: [10, 20, 30, 40, 50]
The addition is: [2150]
map() Method: It iterates over every element of the array and applies some functional condition and return the new array. It does not change the main array but returns the new array of transformed values. Also, it uses the shorthand notation of the arrow function to decrease the code in a single line.JavascriptJavascriptvar abc = [10, 20, 30, 40, 50];let xyz = abc.map(res => res * 2);console.log("The main array: ", abc);console.log("The modified array: ", xyz);Output:The main array: [10, 20, 30, 40, 50]
The modified array: [20, 40, 60, 80, 100]
map() Method: It iterates over every element of the array and applies some functional condition and return the new array. It does not change the main array but returns the new array of transformed values. Also, it uses the shorthand notation of the arrow function to decrease the code in a single line.
Javascript
var abc = [10, 20, 30, 40, 50];let xyz = abc.map(res => res * 2);console.log("The main array: ", abc);console.log("The modified array: ", xyz);
Output:
The main array: [10, 20, 30, 40, 50]
The modified array: [20, 40, 60, 80, 100]
Filter() Method: This method is useful when you want to find out the elements which pass a certain condition. It iterates over all the elements and returns an array with the ones which satisfy the condition.Also, it does not mutate the main array and creates the new one.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.filter(res => res > 35);console.log("The main array: ", abc);console.log("The modified array: ", xyz); Output:The main array : [10, 20, 30, 40, 50]
The modified array: [40, 50]
Note: The filter() method is widely compatible in IE because it belongs to ES5 and find() is introduced in ES6 so only the latest browsers (IE 11) are compatible with it.
Filter() Method: This method is useful when you want to find out the elements which pass a certain condition. It iterates over all the elements and returns an array with the ones which satisfy the condition.Also, it does not mutate the main array and creates the new one.
Javascript
let abc =[10, 20, 30, 40, 50];let xyz = abc.filter(res => res > 35);console.log("The main array: ", abc);console.log("The modified array: ", xyz);
Output:
The main array : [10, 20, 30, 40, 50]
The modified array: [40, 50]
Note: The filter() method is widely compatible in IE because it belongs to ES5 and find() is introduced in ES6 so only the latest browsers (IE 11) are compatible with it.
Find() Method: This method can be used when you want to find out the element which passes a certain condition. This is very similar to the filter() method but it returns the first element which satisfies the condition and does not iterate further.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50];let xyz = abc.find(res => res > 35);console.log("The main array: ", abc);console.log("The modified array: ", xyz);Output:The main array: [10, 20, 30, 40, 50]
The modified array: [40]
Find() Method: This method can be used when you want to find out the element which passes a certain condition. This is very similar to the filter() method but it returns the first element which satisfies the condition and does not iterate further.
Javascript
let abc = [10, 20, 30, 40, 50];let xyz = abc.find(res => res > 35);console.log("The main array: ", abc);console.log("The modified array: ", xyz);
Output:
The main array: [10, 20, 30, 40, 50]
The modified array: [40]
Reduce() Method: This function is useful when you want to reduce all the elements of the array to a single value. It can be used to simply find out the addition of all the elements in an array.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.reduce((element, iterator)=>iterator+element, 0);console.log("The addition is: ", xyz);Output:The addition is: 150
Also, you can initialize the value of the element variable to some other value as well.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50]; let xyz = abc.reduce((element, iterator) => iterator + element, 2000); console.log("The main array: ", abc); console.log("The addition is: ", xyz); Output:The main array: [10, 20, 30, 40, 50]
The addition is: [2150]
Reduce() Method: This function is useful when you want to reduce all the elements of the array to a single value. It can be used to simply find out the addition of all the elements in an array.
Javascript
let abc =[10, 20, 30, 40, 50];let xyz = abc.reduce((element, iterator)=>iterator+element, 0);console.log("The addition is: ", xyz);
Output:
The addition is: 150
Also, you can initialize the value of the element variable to some other value as well.
Javascript
let abc = [10, 20, 30, 40, 50]; let xyz = abc.reduce((element, iterator) => iterator + element, 2000); console.log("The main array: ", abc); console.log("The addition is: ", xyz);
Output:
The main array: [10, 20, 30, 40, 50]
The addition is: [2150]
javascript-basics
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
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 26935,
"s": 26545,
"text": "An array is used to store the elements of multiple data types in JavaScript altogether. Also, there are certain times when you have to manipulate the response received from the APIs as per the requirements on the webpages. Sometimes, the responses are objects and have to be converted to the arrays to perform the desired operations. These methods of array manipulation can save your time."
},
{
"code": null,
"e": 29392,
"s": 26935,
"text": "map() Method: It iterates over every element of the array and applies some functional condition and return the new array. It does not change the main array but returns the new array of transformed values. Also, it uses the shorthand notation of the arrow function to decrease the code in a single line.JavascriptJavascriptvar abc = [10, 20, 30, 40, 50];let xyz = abc.map(res => res * 2);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz);Output:The main array: [10, 20, 30, 40, 50]\nThe modified array: [20, 40, 60, 80, 100]\nFilter() Method: This method is useful when you want to find out the elements which pass a certain condition. It iterates over all the elements and returns an array with the ones which satisfy the condition.Also, it does not mutate the main array and creates the new one.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.filter(res => res > 35);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz); Output:The main array : [10, 20, 30, 40, 50]\nThe modified array: [40, 50]\nNote: The filter() method is widely compatible in IE because it belongs to ES5 and find() is introduced in ES6 so only the latest browsers (IE 11) are compatible with it.Find() Method: This method can be used when you want to find out the element which passes a certain condition. This is very similar to the filter() method but it returns the first element which satisfies the condition and does not iterate further.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50];let xyz = abc.find(res => res > 35);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz);Output:The main array: [10, 20, 30, 40, 50] \nThe modified array: [40]\nReduce() Method: This function is useful when you want to reduce all the elements of the array to a single value. It can be used to simply find out the addition of all the elements in an array.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.reduce((element, iterator)=>iterator+element, 0);console.log(\"The addition is: \", xyz);Output:The addition is: 150\nAlso, you can initialize the value of the element variable to some other value as well.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50]; let xyz = abc.reduce((element, iterator) => iterator + element, 2000); console.log(\"The main array: \", abc); console.log(\"The addition is: \", xyz); Output:The main array: [10, 20, 30, 40, 50]\nThe addition is: [2150]\n"
},
{
"code": null,
"e": 29945,
"s": 29392,
"text": "map() Method: It iterates over every element of the array and applies some functional condition and return the new array. It does not change the main array but returns the new array of transformed values. Also, it uses the shorthand notation of the arrow function to decrease the code in a single line.JavascriptJavascriptvar abc = [10, 20, 30, 40, 50];let xyz = abc.map(res => res * 2);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz);Output:The main array: [10, 20, 30, 40, 50]\nThe modified array: [20, 40, 60, 80, 100]\n"
},
{
"code": null,
"e": 30248,
"s": 29945,
"text": "map() Method: It iterates over every element of the array and applies some functional condition and return the new array. It does not change the main array but returns the new array of transformed values. Also, it uses the shorthand notation of the arrow function to decrease the code in a single line."
},
{
"code": null,
"e": 30259,
"s": 30248,
"text": "Javascript"
},
{
"code": "var abc = [10, 20, 30, 40, 50];let xyz = abc.map(res => res * 2);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz);",
"e": 30403,
"s": 30259,
"text": null
},
{
"code": null,
"e": 30411,
"s": 30403,
"text": "Output:"
},
{
"code": null,
"e": 30492,
"s": 30411,
"text": "The main array: [10, 20, 30, 40, 50]\nThe modified array: [20, 40, 60, 80, 100]\n"
},
{
"code": null,
"e": 31175,
"s": 30492,
"text": "Filter() Method: This method is useful when you want to find out the elements which pass a certain condition. It iterates over all the elements and returns an array with the ones which satisfy the condition.Also, it does not mutate the main array and creates the new one.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.filter(res => res > 35);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz); Output:The main array : [10, 20, 30, 40, 50]\nThe modified array: [40, 50]\nNote: The filter() method is widely compatible in IE because it belongs to ES5 and find() is introduced in ES6 so only the latest browsers (IE 11) are compatible with it."
},
{
"code": null,
"e": 31447,
"s": 31175,
"text": "Filter() Method: This method is useful when you want to find out the elements which pass a certain condition. It iterates over all the elements and returns an array with the ones which satisfy the condition.Also, it does not mutate the main array and creates the new one."
},
{
"code": null,
"e": 31458,
"s": 31447,
"text": "Javascript"
},
{
"code": "let abc =[10, 20, 30, 40, 50];let xyz = abc.filter(res => res > 35);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz); ",
"e": 31606,
"s": 31458,
"text": null
},
{
"code": null,
"e": 31614,
"s": 31606,
"text": "Output:"
},
{
"code": null,
"e": 31682,
"s": 31614,
"text": "The main array : [10, 20, 30, 40, 50]\nThe modified array: [40, 50]\n"
},
{
"code": null,
"e": 31853,
"s": 31682,
"text": "Note: The filter() method is widely compatible in IE because it belongs to ES5 and find() is introduced in ES6 so only the latest browsers (IE 11) are compatible with it."
},
{
"code": null,
"e": 32336,
"s": 31853,
"text": "Find() Method: This method can be used when you want to find out the element which passes a certain condition. This is very similar to the filter() method but it returns the first element which satisfies the condition and does not iterate further.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50];let xyz = abc.find(res => res > 35);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz);Output:The main array: [10, 20, 30, 40, 50] \nThe modified array: [40]\n"
},
{
"code": null,
"e": 32584,
"s": 32336,
"text": "Find() Method: This method can be used when you want to find out the element which passes a certain condition. This is very similar to the filter() method but it returns the first element which satisfies the condition and does not iterate further."
},
{
"code": null,
"e": 32595,
"s": 32584,
"text": "Javascript"
},
{
"code": "let abc = [10, 20, 30, 40, 50];let xyz = abc.find(res => res > 35);console.log(\"The main array: \", abc);console.log(\"The modified array: \", xyz);",
"e": 32741,
"s": 32595,
"text": null
},
{
"code": null,
"e": 32749,
"s": 32741,
"text": "Output:"
},
{
"code": null,
"e": 32813,
"s": 32749,
"text": "The main array: [10, 20, 30, 40, 50] \nThe modified array: [40]\n"
},
{
"code": null,
"e": 33554,
"s": 32813,
"text": "Reduce() Method: This function is useful when you want to reduce all the elements of the array to a single value. It can be used to simply find out the addition of all the elements in an array.JavascriptJavascriptlet abc =[10, 20, 30, 40, 50];let xyz = abc.reduce((element, iterator)=>iterator+element, 0);console.log(\"The addition is: \", xyz);Output:The addition is: 150\nAlso, you can initialize the value of the element variable to some other value as well.JavascriptJavascriptlet abc = [10, 20, 30, 40, 50]; let xyz = abc.reduce((element, iterator) => iterator + element, 2000); console.log(\"The main array: \", abc); console.log(\"The addition is: \", xyz); Output:The main array: [10, 20, 30, 40, 50]\nThe addition is: [2150]\n"
},
{
"code": null,
"e": 33748,
"s": 33554,
"text": "Reduce() Method: This function is useful when you want to reduce all the elements of the array to a single value. It can be used to simply find out the addition of all the elements in an array."
},
{
"code": null,
"e": 33759,
"s": 33748,
"text": "Javascript"
},
{
"code": "let abc =[10, 20, 30, 40, 50];let xyz = abc.reduce((element, iterator)=>iterator+element, 0);console.log(\"The addition is: \", xyz);",
"e": 33891,
"s": 33759,
"text": null
},
{
"code": null,
"e": 33899,
"s": 33891,
"text": "Output:"
},
{
"code": null,
"e": 33921,
"s": 33899,
"text": "The addition is: 150\n"
},
{
"code": null,
"e": 34009,
"s": 33921,
"text": "Also, you can initialize the value of the element variable to some other value as well."
},
{
"code": null,
"e": 34020,
"s": 34009,
"text": "Javascript"
},
{
"code": "let abc = [10, 20, 30, 40, 50]; let xyz = abc.reduce((element, iterator) => iterator + element, 2000); console.log(\"The main array: \", abc); console.log(\"The addition is: \", xyz); ",
"e": 34214,
"s": 34020,
"text": null
},
{
"code": null,
"e": 34222,
"s": 34214,
"text": "Output:"
},
{
"code": null,
"e": 34284,
"s": 34222,
"text": "The main array: [10, 20, 30, 40, 50]\nThe addition is: [2150]\n"
},
{
"code": null,
"e": 34302,
"s": 34284,
"text": "javascript-basics"
},
{
"code": null,
"e": 34313,
"s": 34302,
"text": "JavaScript"
},
{
"code": null,
"e": 34330,
"s": 34313,
"text": "Web Technologies"
},
{
"code": null,
"e": 34428,
"s": 34330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34468,
"s": 34428,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34529,
"s": 34468,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 34570,
"s": 34529,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 34592,
"s": 34570,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 34646,
"s": 34592,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 34686,
"s": 34646,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34719,
"s": 34686,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34762,
"s": 34719,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 34812,
"s": 34762,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Normalize Data in R? - GeeksforGeeks | 19 Dec, 2021
In this article, we will discuss how to normalize data in the R programming language.
Normalizing Data is the approach to scale the data into a fixed range usually 0 to 1 so that it reduces the scale of the variables.
In this approach to normalize the data with its log transformation, the user needs to call the log() which is an inbuilt function and pass the data frame as its parameter to transform the given data to its log and the resulting data will then be transformed to the scale.
log() function is used to compute logarithms, by default natural logarithm.
Syntax:
log(x)
Parameters:
x: a numeric or complex vector.
Example: Normalize data
R
# Create datagfg < - c(244, 753, 596, 645, 874, 141, 639, 465, 999, 654) # normalizing datagfg < -log(gfg)gfg
Output:
[1] 5.497168 6.624065 6.390241 6.469250 6.773080 4.948760 6.459904 6.142037 6.906755 6.483107
In this method to normalize the data, the user simply needs to call the scale() function which is an inbuilt function, and pass the data which is needed to be scaled, and further this will be resulting in normalized data from range -1 to 1 in the R programming language.
Scale() is a generic function whose default method centers and/or scales the columns of a numeric matrix.
Syntax:
scale(x)
Parameters:
x: Data
Example: Normalize data
R
# Create datagfg <- c(244,753,596,645,874,141,639,465,999,654) # normalizing datagfg <- as.data.frame(scale(gfg)) gfg
Output:
V1
1 -1.36039519
2 0.57921588
3 -0.01905315
4 0.16766775
5 1.04030220
6 -1.75289016
7 0.14480397
8 -0.51824578
9 1.51663105
10 0.20196343
In this method to normalize, the user has to first install and import the caret package in the R working console, and then the user needs to call the preProcess() function with the method passed as the range as its parameters, and then the user calls the predict() function to get the final normalize data which will lead to the normalization of the given data to the scale from 0 to 1 in the R programming language.
perProcess() function is used for transformation can be estimated from the training data and applied to any data set with the same variables.
Syntax:
preProcess(x,method)
Parameters:
x: Data
method: a character vector specifying the type of processing.
Example: Normalize data
R
library(caret) # Create datagfg <- c(244,753,596,645,874,141,639,465,999,654) # normalizing datass <- preProcess(as.data.frame(gfg), method=c("range")) gfg <- predict(ss, as.data.frame(gfg))gfg
Output:
gfg
1 0.1200466
2 0.7132867
3 0.5303030
4 0.5874126
5 0.8543124
6 0.0000000
7 0.5804196
8 0.3776224
9 1.0000000
10 0.5979021
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
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?
Printing Output of an R Program
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming | [
{
"code": null,
"e": 26451,
"s": 26423,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 26537,
"s": 26451,
"text": "In this article, we will discuss how to normalize data in the R programming language."
},
{
"code": null,
"e": 26669,
"s": 26537,
"text": "Normalizing Data is the approach to scale the data into a fixed range usually 0 to 1 so that it reduces the scale of the variables."
},
{
"code": null,
"e": 26941,
"s": 26669,
"text": "In this approach to normalize the data with its log transformation, the user needs to call the log() which is an inbuilt function and pass the data frame as its parameter to transform the given data to its log and the resulting data will then be transformed to the scale."
},
{
"code": null,
"e": 27017,
"s": 26941,
"text": "log() function is used to compute logarithms, by default natural logarithm."
},
{
"code": null,
"e": 27025,
"s": 27017,
"text": "Syntax:"
},
{
"code": null,
"e": 27032,
"s": 27025,
"text": "log(x)"
},
{
"code": null,
"e": 27044,
"s": 27032,
"text": "Parameters:"
},
{
"code": null,
"e": 27076,
"s": 27044,
"text": "x: a numeric or complex vector."
},
{
"code": null,
"e": 27101,
"s": 27076,
"text": "Example: Normalize data "
},
{
"code": null,
"e": 27103,
"s": 27101,
"text": "R"
},
{
"code": "# Create datagfg < - c(244, 753, 596, 645, 874, 141, 639, 465, 999, 654) # normalizing datagfg < -log(gfg)gfg",
"e": 27223,
"s": 27103,
"text": null
},
{
"code": null,
"e": 27231,
"s": 27223,
"text": "Output:"
},
{
"code": null,
"e": 27327,
"s": 27231,
"text": " [1] 5.497168 6.624065 6.390241 6.469250 6.773080 4.948760 6.459904 6.142037 6.906755 6.483107"
},
{
"code": null,
"e": 27598,
"s": 27327,
"text": "In this method to normalize the data, the user simply needs to call the scale() function which is an inbuilt function, and pass the data which is needed to be scaled, and further this will be resulting in normalized data from range -1 to 1 in the R programming language."
},
{
"code": null,
"e": 27704,
"s": 27598,
"text": "Scale() is a generic function whose default method centers and/or scales the columns of a numeric matrix."
},
{
"code": null,
"e": 27712,
"s": 27704,
"text": "Syntax:"
},
{
"code": null,
"e": 27721,
"s": 27712,
"text": "scale(x)"
},
{
"code": null,
"e": 27733,
"s": 27721,
"text": "Parameters:"
},
{
"code": null,
"e": 27741,
"s": 27733,
"text": "x: Data"
},
{
"code": null,
"e": 27765,
"s": 27741,
"text": "Example: Normalize data"
},
{
"code": null,
"e": 27767,
"s": 27765,
"text": "R"
},
{
"code": "# Create datagfg <- c(244,753,596,645,874,141,639,465,999,654) # normalizing datagfg <- as.data.frame(scale(gfg)) gfg",
"e": 27886,
"s": 27767,
"text": null
},
{
"code": null,
"e": 27894,
"s": 27886,
"text": "Output:"
},
{
"code": null,
"e": 28059,
"s": 27894,
"text": " V1\n1 -1.36039519\n2 0.57921588\n3 -0.01905315\n4 0.16766775\n5 1.04030220\n6 -1.75289016\n7 0.14480397\n8 -0.51824578\n9 1.51663105\n10 0.20196343"
},
{
"code": null,
"e": 28476,
"s": 28059,
"text": "In this method to normalize, the user has to first install and import the caret package in the R working console, and then the user needs to call the preProcess() function with the method passed as the range as its parameters, and then the user calls the predict() function to get the final normalize data which will lead to the normalization of the given data to the scale from 0 to 1 in the R programming language."
},
{
"code": null,
"e": 28618,
"s": 28476,
"text": "perProcess() function is used for transformation can be estimated from the training data and applied to any data set with the same variables."
},
{
"code": null,
"e": 28626,
"s": 28618,
"text": "Syntax:"
},
{
"code": null,
"e": 28647,
"s": 28626,
"text": "preProcess(x,method)"
},
{
"code": null,
"e": 28659,
"s": 28647,
"text": "Parameters:"
},
{
"code": null,
"e": 28667,
"s": 28659,
"text": "x: Data"
},
{
"code": null,
"e": 28729,
"s": 28667,
"text": "method: a character vector specifying the type of processing."
},
{
"code": null,
"e": 28753,
"s": 28729,
"text": "Example: Normalize data"
},
{
"code": null,
"e": 28755,
"s": 28753,
"text": "R"
},
{
"code": "library(caret) # Create datagfg <- c(244,753,596,645,874,141,639,465,999,654) # normalizing datass <- preProcess(as.data.frame(gfg), method=c(\"range\")) gfg <- predict(ss, as.data.frame(gfg))gfg",
"e": 28952,
"s": 28755,
"text": null
},
{
"code": null,
"e": 28960,
"s": 28952,
"text": "Output:"
},
{
"code": null,
"e": 29103,
"s": 28960,
"text": " gfg\n1 0.1200466\n2 0.7132867\n3 0.5303030\n4 0.5874126\n5 0.8543124\n6 0.0000000\n7 0.5804196\n8 0.3776224\n9 1.0000000\n10 0.5979021"
},
{
"code": null,
"e": 29110,
"s": 29103,
"text": "Picked"
},
{
"code": null,
"e": 29121,
"s": 29110,
"text": "R Language"
},
{
"code": null,
"e": 29219,
"s": 29121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29277,
"s": 29219,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 29329,
"s": 29277,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 29361,
"s": 29329,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 29405,
"s": 29361,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 29457,
"s": 29405,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29492,
"s": 29457,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29530,
"s": 29492,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29562,
"s": 29530,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 29620,
"s": 29562,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
Java - toDegrees() Method | The method converts the argument value to degrees.
double toDegrees(double d)
Here is the detail of parameters −
d − A double data type.
d − A double data type.
This method returns a double value.
public class Test {
public static void main(String args[]) {
double x = 45.0;
double y = 30.0;
System.out.println( Math.toDegrees(x) );
System.out.println( Math.toDegrees(y) );
}
}
This will produce the following result −
2578.3100780887044
1718.8733853924698
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2428,
"s": 2377,
"text": "The method converts the argument value to degrees."
},
{
"code": null,
"e": 2456,
"s": 2428,
"text": "double toDegrees(double d)\n"
},
{
"code": null,
"e": 2491,
"s": 2456,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2515,
"s": 2491,
"text": "d − A double data type."
},
{
"code": null,
"e": 2539,
"s": 2515,
"text": "d − A double data type."
},
{
"code": null,
"e": 2575,
"s": 2539,
"text": "This method returns a double value."
},
{
"code": null,
"e": 2789,
"s": 2575,
"text": "public class Test { \n\n public static void main(String args[]) {\n double x = 45.0;\n double y = 30.0;\n\n System.out.println( Math.toDegrees(x) );\n System.out.println( Math.toDegrees(y) );\n }\n}"
},
{
"code": null,
"e": 2830,
"s": 2789,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2869,
"s": 2830,
"text": "2578.3100780887044\n1718.8733853924698\n"
},
{
"code": null,
"e": 2902,
"s": 2869,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2918,
"s": 2902,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2951,
"s": 2918,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2967,
"s": 2951,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3002,
"s": 2967,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3016,
"s": 3002,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3050,
"s": 3016,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3064,
"s": 3050,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3101,
"s": 3064,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3116,
"s": 3101,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3149,
"s": 3116,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3168,
"s": 3149,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3175,
"s": 3168,
"text": " Print"
},
{
"code": null,
"e": 3186,
"s": 3175,
"text": " Add Notes"
}
] |
Anagram of String | Practice | GeeksforGeeks | Given two strings S1 and S2 in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagram of each other if one of them can be converted into another by rearranging its letters.
Example 1:
Input:
S1 = bcadeh
S2 = hea
Output: 3
Explanation: We need to remove b, c
and d from S1.
Example 2:
Input:
S1 = cddgk
S2 = gcd
Output: 2
Explanation: We need to remove d and
k from S1.
Your Task:
Complete the function remAnagram() which takes two strings S1, S2 as input parameter, and returns minimum characters needs to be deleted.
Expected Time Complexity: O(max(|S1|, |S2|)), where |S| = length of string S.
Expected Auxiliary Space: O(26)
Constraints:
1 <= |S1|, |S2| <= 105
0
radhikamendiratta19944 days ago
python solution
def remAnagram(str1,str2):
count=0
t1=str1[:]
for i in range(len(str1)):
if t1[i] not in str2:
#str1=str1[:i]+str1[i+1:]
#added above statement for debugging
count+=1
if t1[i] in str2:
if str2:
pos = str2.index(t1[i])
str2=str2[:pos]+str2[pos+1:]
if str2:
count+=len(str2)
return count
0
danish_nitdgp2 weeks ago
Basic Solution with constant space.int remAnagram(string str1, string str2){// Your code goes here int n1 = str1.length(); int n2 = str2.length(); vector<int> v1(26,0); vector<int> v2(26,0); for(int i =0;i<n1;i++){ v1[str1[i]-'a']++; } for(int i =0;i<n2;i++){ v2[str2[i]-'a']++; } int count = 0; for(int i =0;i<26;i++){ count+=abs(v1[i]-v2[i]); } return count; }
0
srikavyasri09
This comment was deleted.
+1
itachinamikaze2211 month ago
JAVA
public int remAnagrams(String s,String s1) { HashMap<Character, Integer> map= new HashMap<>(); for(int i=0; i<s.length();i++) { char ch= s.charAt(i); map.put(ch, map.getOrDefault(ch, 0)+1); } for(int i=0; i<s1.length();i++) { char ch= s1.charAt(i); if(map.containsKey(ch)==false) map.put(ch,-1); else map.put(ch, map.get(ch)-1); } int count =0; for(int i: map.values()) { if(i<0) count= count-i; else count=count+i; } return count; }
+2
19bcs21821 month ago
SIMPLE JAVA APPROACH: TIME COMPLEXITY: (0.2)-
class GfG{public int remAnagrams(String s,String s1) { int al []= new int[256]; // int bl []= new int[256]; int index=0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); index = (int) c; al[index]++; } for(int j=0; j<s1.length(); j++) { char c = s1.charAt(j); index = (int) c; al[index]--; } int ans =0; for(int i=0;i<256;i++){ if(al[i] !=0){ ans = ans+ Math.abs(al[i]); } } return ans; }}
+2
atulp2001np2 months ago
int a[26]={0};
int count=0;
int b[26]={0};
for(auto i: str1)
{
a[i-'a']++;
}
for(auto i: str2)
{
b[i-'a']++;
}
for(int i=0;i<26;i++)
{
count+=abs(b[i]-a[i]);
}
return count;
0
codeman99
This comment was deleted.
0
robingangil52 months ago
int remAnagram(string str1, string str2){// Your code goes here()){
int H1[26]={0};int H2[26]={0};for(int i=0;str1[i]!='\0';i++){ H1[str1[i]-97]++;}for(int i=0;str2[i]!='\0';i++){ H2[str2[i]-97]++;}int sum=0;for(int i=0;i<26;i++){ sum+=abs(H1[i]-H2[i]);}return sum;}
0
vikasingle2 months ago
Python
def remAnagram(str1,str2):
#add code here
m = len(str1)
n = len(str2)
i = 0
j = 0
ans = 0
str1 = sorted(str1)
str2 = sorted(str2)
while(i<m and j<n):
if str1[i]==str2[j]:
i+=1
j+=1
elif str1[i] < str2[j]:
i+=1
ans+=1
else:
j+=1
ans+=1
ans += m-i
ans +=n-j
return ans
0
bhushan91682730332 months ago
Simple apporach using two store arrays (C++)
int remAnagram(string str1, string str2) {
// Your code goes here
int count = 0;
vector<int>store1(26, 0);
vector<int>store2(26, 0);
for (int i = 0; i < str1.length(); i++) {
store1[str1[i] - 'a']++;
}
for (int i = 0; i < str2.length(); i++) {
store2[str2[i] - 'a']++;
}
for (int i = 0; i < 26; i++) {
count += abs(store1[i] - store2[i]);
}
return count;
}
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": 587,
"s": 238,
"text": "Given two strings S1 and S2 in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagram of each other if one of them can be converted into another by rearranging its letters."
},
{
"code": null,
"e": 598,
"s": 587,
"text": "Example 1:"
},
{
"code": null,
"e": 688,
"s": 598,
"text": "Input:\nS1 = bcadeh\nS2 = hea\nOutput: 3\nExplanation: We need to remove b, c\nand d from S1.\n"
},
{
"code": null,
"e": 699,
"s": 688,
"text": "Example 2:"
},
{
"code": null,
"e": 784,
"s": 699,
"text": "Input:\nS1 = cddgk\nS2 = gcd\nOutput: 2\nExplanation: We need to remove d and\nk from S1."
},
{
"code": null,
"e": 933,
"s": 784,
"text": "Your Task:\nComplete the function remAnagram() which takes two strings S1, S2 as input parameter, and returns minimum characters needs to be deleted."
},
{
"code": null,
"e": 1043,
"s": 933,
"text": "Expected Time Complexity: O(max(|S1|, |S2|)), where |S| = length of string S.\nExpected Auxiliary Space: O(26)"
},
{
"code": null,
"e": 1079,
"s": 1043,
"text": "Constraints:\n1 <= |S1|, |S2| <= 105"
},
{
"code": null,
"e": 1081,
"s": 1079,
"text": "0"
},
{
"code": null,
"e": 1113,
"s": 1081,
"text": "radhikamendiratta19944 days ago"
},
{
"code": null,
"e": 1129,
"s": 1113,
"text": "python solution"
},
{
"code": null,
"e": 1548,
"s": 1131,
"text": "def remAnagram(str1,str2):\n count=0\n t1=str1[:]\n for i in range(len(str1)):\n \n if t1[i] not in str2:\n #str1=str1[:i]+str1[i+1:]\n #added above statement for debugging\n count+=1\n\n if t1[i] in str2:\n if str2:\n pos = str2.index(t1[i])\n str2=str2[:pos]+str2[pos+1:]\n\n if str2:\n count+=len(str2)\n return count"
},
{
"code": null,
"e": 1550,
"s": 1548,
"text": "0"
},
{
"code": null,
"e": 1575,
"s": 1550,
"text": "danish_nitdgp2 weeks ago"
},
{
"code": null,
"e": 1985,
"s": 1575,
"text": "Basic Solution with constant space.int remAnagram(string str1, string str2){// Your code goes here int n1 = str1.length(); int n2 = str2.length(); vector<int> v1(26,0); vector<int> v2(26,0); for(int i =0;i<n1;i++){ v1[str1[i]-'a']++; } for(int i =0;i<n2;i++){ v2[str2[i]-'a']++; } int count = 0; for(int i =0;i<26;i++){ count+=abs(v1[i]-v2[i]); } return count; }"
},
{
"code": null,
"e": 1987,
"s": 1985,
"text": "0"
},
{
"code": null,
"e": 2001,
"s": 1987,
"text": "srikavyasri09"
},
{
"code": null,
"e": 2027,
"s": 2001,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2030,
"s": 2027,
"text": "+1"
},
{
"code": null,
"e": 2059,
"s": 2030,
"text": "itachinamikaze2211 month ago"
},
{
"code": null,
"e": 2064,
"s": 2059,
"text": "JAVA"
},
{
"code": null,
"e": 2703,
"s": 2064,
"text": "public int remAnagrams(String s,String s1) { HashMap<Character, Integer> map= new HashMap<>(); for(int i=0; i<s.length();i++) { char ch= s.charAt(i); map.put(ch, map.getOrDefault(ch, 0)+1); } for(int i=0; i<s1.length();i++) { char ch= s1.charAt(i); if(map.containsKey(ch)==false) map.put(ch,-1); else map.put(ch, map.get(ch)-1); } int count =0; for(int i: map.values()) { if(i<0) count= count-i; else count=count+i; } return count; }"
},
{
"code": null,
"e": 2706,
"s": 2703,
"text": "+2"
},
{
"code": null,
"e": 2727,
"s": 2706,
"text": "19bcs21821 month ago"
},
{
"code": null,
"e": 2773,
"s": 2727,
"text": "SIMPLE JAVA APPROACH: TIME COMPLEXITY: (0.2)-"
},
{
"code": null,
"e": 3306,
"s": 2773,
"text": "class GfG{public int remAnagrams(String s,String s1) { int al []= new int[256]; // int bl []= new int[256]; int index=0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); index = (int) c; al[index]++; } for(int j=0; j<s1.length(); j++) { char c = s1.charAt(j); index = (int) c; al[index]--; } int ans =0; for(int i=0;i<256;i++){ if(al[i] !=0){ ans = ans+ Math.abs(al[i]); } } return ans; }}"
},
{
"code": null,
"e": 3309,
"s": 3306,
"text": "+2"
},
{
"code": null,
"e": 3333,
"s": 3309,
"text": "atulp2001np2 months ago"
},
{
"code": null,
"e": 3537,
"s": 3333,
"text": " int a[26]={0};\n int count=0;\n int b[26]={0};\n for(auto i: str1)\n {\n a[i-'a']++;\n }\n for(auto i: str2)\n {\n b[i-'a']++;\n }\n for(int i=0;i<26;i++)\n {\n count+=abs(b[i]-a[i]);\n }\n return count;\n "
},
{
"code": null,
"e": 3539,
"s": 3537,
"text": "0"
},
{
"code": null,
"e": 3549,
"s": 3539,
"text": "codeman99"
},
{
"code": null,
"e": 3575,
"s": 3549,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3577,
"s": 3575,
"text": "0"
},
{
"code": null,
"e": 3602,
"s": 3577,
"text": "robingangil52 months ago"
},
{
"code": null,
"e": 3670,
"s": 3602,
"text": "int remAnagram(string str1, string str2){// Your code goes here()){"
},
{
"code": null,
"e": 3875,
"s": 3670,
"text": "int H1[26]={0};int H2[26]={0};for(int i=0;str1[i]!='\\0';i++){ H1[str1[i]-97]++;}for(int i=0;str2[i]!='\\0';i++){ H2[str2[i]-97]++;}int sum=0;for(int i=0;i<26;i++){ sum+=abs(H1[i]-H2[i]);}return sum;}"
},
{
"code": null,
"e": 3877,
"s": 3875,
"text": "0"
},
{
"code": null,
"e": 3900,
"s": 3877,
"text": "vikasingle2 months ago"
},
{
"code": null,
"e": 3907,
"s": 3900,
"text": "Python"
},
{
"code": null,
"e": 4331,
"s": 3907,
"text": "def remAnagram(str1,str2):\n\n #add code here\n\n m = len(str1)\n n = len(str2)\n\n i = 0\n j = 0\n\n ans = 0\n\n str1 = sorted(str1)\n str2 = sorted(str2)\n\n while(i<m and j<n):\n\n if str1[i]==str2[j]:\n i+=1\n j+=1\n\n elif str1[i] < str2[j]:\n i+=1\n ans+=1\n\n else:\n j+=1\n ans+=1\n\n ans += m-i\n ans +=n-j\n\n return ans\n"
},
{
"code": null,
"e": 4333,
"s": 4331,
"text": "0"
},
{
"code": null,
"e": 4363,
"s": 4333,
"text": "bhushan91682730332 months ago"
},
{
"code": null,
"e": 4408,
"s": 4363,
"text": "Simple apporach using two store arrays (C++)"
},
{
"code": null,
"e": 4793,
"s": 4408,
"text": "int remAnagram(string str1, string str2) {\n // Your code goes here\n int count = 0;\n\n\tvector<int>store1(26, 0);\n\tvector<int>store2(26, 0);\n\n\tfor (int i = 0; i < str1.length(); i++)\t{\n\t\tstore1[str1[i] - 'a']++;\n\t}\n\n\tfor (int i = 0; i < str2.length(); i++)\t{\n\t\tstore2[str2[i] - 'a']++;\n\t}\n\n\tfor (int i = 0; i < 26; i++)\t{\n\t\tcount += abs(store1[i] - store2[i]);\n\t}\n\n\treturn count;\n}"
},
{
"code": null,
"e": 4939,
"s": 4793,
"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": 4975,
"s": 4939,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4985,
"s": 4975,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4995,
"s": 4985,
"text": "\nContest\n"
},
{
"code": null,
"e": 5058,
"s": 4995,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5206,
"s": 5058,
"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": 5414,
"s": 5206,
"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": 5520,
"s": 5414,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to change the position of the legend in a PieChart in JavaFX? | In the pie chart, we represent the data values as slices of a circle. Each slice is differentiated from other (typically by color). In JavaFX, you can create a pie chart by instantiating the javafx.scene.chart.PieChart class.
By default, a JavaFX pie chart contains labels of the slices and a legend − a bar with colors specifying the category represented by each color.
The PieChart class has a property named legendSide (inherited from the Chart class). This specifies the position of the legend in the chart (left, right, top-bottom). You can set the value to this property using the setLegendSide() method. This method accepts one of the following values as a parameter −
Side.BOTTOM
Side.BOTTOM
Side.TOP
Side.TOP
Side.LEFT
Side.LEFT
Side.RIGHT
Side.RIGHT
You can change the position of the legend in a chart, by invoking the setLegendSide() method by passing the appropriate value as a parameter.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.StackPane;
public class PieChart_LegendPosition extends Application {
@Override
public void start(Stage stage) {
//Creating a Pie chart
PieChart pieChart = new PieChart();
//Setting data
ObservableList data = FXCollections.observableArrayList(
new PieChart.Data("Work", 10),
new PieChart.Data("Chores", 2),
new PieChart.Data("Sleep", 8),
new PieChart.Data("Others", 4));
pieChart.setData(data);
//Setting the legend on the left side of the chart
pieChart.setLegendSide(Side.LEFT);
//Creating a stack pane to hold the pie chart
StackPane pane = new StackPane(pieChart);
pane.setStyle("-fx-background-color: BEIGE");
//Setting the Scene
Scene scene = new Scene(pane, 595, 300);
stage.setTitle("Pie Chart");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1288,
"s": 1062,
"text": "In the pie chart, we represent the data values as slices of a circle. Each slice is differentiated from other (typically by color). In JavaFX, you can create a pie chart by instantiating the javafx.scene.chart.PieChart class."
},
{
"code": null,
"e": 1433,
"s": 1288,
"text": "By default, a JavaFX pie chart contains labels of the slices and a legend − a bar with colors specifying the category represented by each color."
},
{
"code": null,
"e": 1738,
"s": 1433,
"text": "The PieChart class has a property named legendSide (inherited from the Chart class). This specifies the position of the legend in the chart (left, right, top-bottom). You can set the value to this property using the setLegendSide() method. This method accepts one of the following values as a parameter −"
},
{
"code": null,
"e": 1750,
"s": 1738,
"text": "Side.BOTTOM"
},
{
"code": null,
"e": 1762,
"s": 1750,
"text": "Side.BOTTOM"
},
{
"code": null,
"e": 1771,
"s": 1762,
"text": "Side.TOP"
},
{
"code": null,
"e": 1780,
"s": 1771,
"text": "Side.TOP"
},
{
"code": null,
"e": 1790,
"s": 1780,
"text": "Side.LEFT"
},
{
"code": null,
"e": 1800,
"s": 1790,
"text": "Side.LEFT"
},
{
"code": null,
"e": 1811,
"s": 1800,
"text": "Side.RIGHT"
},
{
"code": null,
"e": 1822,
"s": 1811,
"text": "Side.RIGHT"
},
{
"code": null,
"e": 1964,
"s": 1822,
"text": "You can change the position of the legend in a chart, by invoking the setLegendSide() method by passing the appropriate value as a parameter."
},
{
"code": null,
"e": 3169,
"s": 1964,
"text": "import javafx.application.Application;\nimport javafx.collections.FXCollections;\nimport javafx.collections.ObservableList;\nimport javafx.geometry.Side;\nimport javafx.scene.Scene;\nimport javafx.stage.Stage;\nimport javafx.scene.chart.PieChart;\nimport javafx.scene.layout.StackPane;\npublic class PieChart_LegendPosition extends Application {\n @Override\n public void start(Stage stage) {\n //Creating a Pie chart\n PieChart pieChart = new PieChart();\n //Setting data\n ObservableList data = FXCollections.observableArrayList(\n new PieChart.Data(\"Work\", 10),\n new PieChart.Data(\"Chores\", 2),\n new PieChart.Data(\"Sleep\", 8),\n new PieChart.Data(\"Others\", 4));\n pieChart.setData(data);\n //Setting the legend on the left side of the chart\n pieChart.setLegendSide(Side.LEFT);\n //Creating a stack pane to hold the pie chart\n StackPane pane = new StackPane(pieChart);\n pane.setStyle(\"-fx-background-color: BEIGE\");\n //Setting the Scene\n Scene scene = new Scene(pane, 595, 300);\n stage.setTitle(\"Pie Chart\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
PyQt5 – How to add padding to a Label ? - GeeksforGeeks | 26 Mar, 2020
In this article, we will see how to add padding to our Label. Padding is just the space between the border and the content. Below is image of label this will helps in better understanding of the padding.
In order to add padding to our label, we will use setStyleSheet() method, below is how without padding label vs padded label looks like.
Syntax : label.setStyleSheet(“padding :15px”)
Argument : It takes string as argument.
Action performed : It adds padding to the label.
Code :
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # creating a label widget self.label_1 = QLabel("===============", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet("border :3px solid blue;") # resizing label self.label_1.resize(100, 100) # creating a label widget self.label_2 = QLabel("==================", self) # setting up the border and adding padding self.label_2.setStyleSheet("border :3px solid blue;padding :15px") # moving position self.label_2.move(230, 200) # resizing the label self.label_2.resize(100, 100) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python | [
{
"code": null,
"e": 24563,
"s": 24535,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24767,
"s": 24563,
"text": "In this article, we will see how to add padding to our Label. Padding is just the space between the border and the content. Below is image of label this will helps in better understanding of the padding."
},
{
"code": null,
"e": 24904,
"s": 24767,
"text": "In order to add padding to our label, we will use setStyleSheet() method, below is how without padding label vs padded label looks like."
},
{
"code": null,
"e": 24950,
"s": 24904,
"text": "Syntax : label.setStyleSheet(“padding :15px”)"
},
{
"code": null,
"e": 24990,
"s": 24950,
"text": "Argument : It takes string as argument."
},
{
"code": null,
"e": 25039,
"s": 24990,
"text": "Action performed : It adds padding to the label."
},
{
"code": null,
"e": 25046,
"s": 25039,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # creating a label widget self.label_1 = QLabel(\"===============\", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet(\"border :3px solid blue;\") # resizing label self.label_1.resize(100, 100) # creating a label widget self.label_2 = QLabel(\"==================\", self) # setting up the border and adding padding self.label_2.setStyleSheet(\"border :3px solid blue;padding :15px\") # moving position self.label_2.move(230, 200) # resizing the label self.label_2.resize(100, 100) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())",
"e": 26249,
"s": 25046,
"text": null
},
{
"code": null,
"e": 26258,
"s": 26249,
"text": "Output :"
},
{
"code": null,
"e": 26269,
"s": 26258,
"text": "Python-gui"
},
{
"code": null,
"e": 26281,
"s": 26269,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26288,
"s": 26281,
"text": "Python"
},
{
"code": null,
"e": 26386,
"s": 26288,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26395,
"s": 26386,
"text": "Comments"
},
{
"code": null,
"e": 26408,
"s": 26395,
"text": "Old Comments"
},
{
"code": null,
"e": 26426,
"s": 26408,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26448,
"s": 26426,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26483,
"s": 26448,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26505,
"s": 26483,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26547,
"s": 26505,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26572,
"s": 26547,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26604,
"s": 26572,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26620,
"s": 26604,
"text": "Deque in Python"
},
{
"code": null,
"e": 26646,
"s": 26620,
"text": "Python String | replace()"
}
] |
PHP - hash() Function | The hash() function returns a hash value for the given data based on the algorithm like (md5, sha256). The return value is a string with hexits (hexadecimal values).
hash ( string $algo , string $data [, bool $raw_output = FALSE ] ) : string
algo
Name of the hashing algorithm. There is a big list of algorithm available with hash, some important ones are md5, sha256, etc. To get the full list of algorithms supported use the hashing function hash_algos()
data
The data you want the hash to be generated. Please note once the hash is generated it cannot be reversed.
raw_output
By default, the value is false and hence it returns lowercase hexits values. If the value is true, it will return raw binary data.
PHP hash() function returns a string with lowercase hexits. If the raw_output is set to true, it will return raw binary data.
This function will work from PHP Version greater than 5.1.2.
To generate hash value using md5 Algorithm −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint');
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - 8ab923b97822bd258bf882e41de6ebff
To generate hash value using sha256 Algorithm −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('sha256', 'Welcome to Tutorialspoint');
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e
To generate hash using crc32b Algorithm −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('crc32b', 'Welcome to Tutorialspoint');
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - cd12151c
To generate hash with raw_output as true −
<?php
echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint', true);
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - ��#�x"�%����u001d���
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2923,
"s": 2757,
"text": "The hash() function returns a hash value for the given data based on the algorithm like (md5, sha256). The return value is a string with hexits (hexadecimal values)."
},
{
"code": null,
"e": 3000,
"s": 2923,
"text": "hash ( string $algo , string $data [, bool $raw_output = FALSE ] ) : string\n"
},
{
"code": null,
"e": 3005,
"s": 3000,
"text": "algo"
},
{
"code": null,
"e": 3215,
"s": 3005,
"text": "Name of the hashing algorithm. There is a big list of algorithm available with hash, some important ones are md5, sha256, etc. To get the full list of algorithms supported use the hashing function hash_algos()"
},
{
"code": null,
"e": 3220,
"s": 3215,
"text": "data"
},
{
"code": null,
"e": 3326,
"s": 3220,
"text": "The data you want the hash to be generated. Please note once the hash is generated it cannot be reversed."
},
{
"code": null,
"e": 3337,
"s": 3326,
"text": "raw_output"
},
{
"code": null,
"e": 3468,
"s": 3337,
"text": "By default, the value is false and hence it returns lowercase hexits values. If the value is true, it will return raw binary data."
},
{
"code": null,
"e": 3594,
"s": 3468,
"text": "PHP hash() function returns a string with lowercase hexits. If the raw_output is set to true, it will return raw binary data."
},
{
"code": null,
"e": 3655,
"s": 3594,
"text": "This function will work from PHP Version greater than 5.1.2."
},
{
"code": null,
"e": 3700,
"s": 3655,
"text": "To generate hash value using md5 Algorithm −"
},
{
"code": null,
"e": 3806,
"s": 3700,
"text": "<?php\n echo \"The hash of Welcome to Tutorialspoint is - \". hash('md5', 'Welcome to Tutorialspoint');\n?>"
},
{
"code": null,
"e": 3847,
"s": 3806,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3924,
"s": 3847,
"text": "The hash of Welcome to Tutorialspoint is - 8ab923b97822bd258bf882e41de6ebff\n"
},
{
"code": null,
"e": 3972,
"s": 3924,
"text": "To generate hash value using sha256 Algorithm −"
},
{
"code": null,
"e": 4081,
"s": 3972,
"text": "<?php\n echo \"The hash of Welcome to Tutorialspoint is - \". hash('sha256', 'Welcome to Tutorialspoint');\n?>"
},
{
"code": null,
"e": 4122,
"s": 4081,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4231,
"s": 4122,
"text": "The hash of Welcome to Tutorialspoint is - a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e\n"
},
{
"code": null,
"e": 4273,
"s": 4231,
"text": "To generate hash using crc32b Algorithm −"
},
{
"code": null,
"e": 4382,
"s": 4273,
"text": "<?php\n echo \"The hash of Welcome to Tutorialspoint is - \". hash('crc32b', 'Welcome to Tutorialspoint');\n?>"
},
{
"code": null,
"e": 4423,
"s": 4382,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4476,
"s": 4423,
"text": "The hash of Welcome to Tutorialspoint is - cd12151c\n"
},
{
"code": null,
"e": 4519,
"s": 4476,
"text": "To generate hash with raw_output as true −"
},
{
"code": null,
"e": 4631,
"s": 4519,
"text": "<?php\n echo \"The hash of Welcome to Tutorialspoint is - \". hash('md5', 'Welcome to Tutorialspoint', true);\n?>"
},
{
"code": null,
"e": 4672,
"s": 4631,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4737,
"s": 4672,
"text": "The hash of Welcome to Tutorialspoint is - ��#�x\"�%����u001d���\n"
},
{
"code": null,
"e": 4770,
"s": 4737,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4786,
"s": 4770,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4819,
"s": 4786,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4830,
"s": 4819,
"text": " Syed Raza"
},
{
"code": null,
"e": 4865,
"s": 4830,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4882,
"s": 4865,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4915,
"s": 4882,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4930,
"s": 4915,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 4965,
"s": 4930,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 4977,
"s": 4965,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5012,
"s": 4977,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5040,
"s": 5012,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5047,
"s": 5040,
"text": " Print"
},
{
"code": null,
"e": 5058,
"s": 5047,
"text": " Add Notes"
}
] |
HTML | <th> width Attribute - GeeksforGeeks | 26 Jun, 2019
The HTML <th> width Attribute is used to specify the width of a table header cell. If width attribute is not set then it takes default width according to content. It is not supported by HTML 5.
Syntax:
<th width="pixels | %">
Attribute Values:
pixels: It sets the width of table header cell in terms of pixels.
%: It sets the width of table header cell in terms of percentage (%).
Example:
<!DOCTYPE html><html> <head> <title> HTML th width Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th width Attribute</h2> <table border="1" width="500"> <tr> <th width="50%">NAME</th> <th width="20%">AGE</th> <th width="30%">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>
Output:
Supported Browsers: The browser supported by HTML <th> width attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
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 ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25889,
"s": 25861,
"text": "\n26 Jun, 2019"
},
{
"code": null,
"e": 26083,
"s": 25889,
"text": "The HTML <th> width Attribute is used to specify the width of a table header cell. If width attribute is not set then it takes default width according to content. It is not supported by HTML 5."
},
{
"code": null,
"e": 26091,
"s": 26083,
"text": "Syntax:"
},
{
"code": null,
"e": 26115,
"s": 26091,
"text": "<th width=\"pixels | %\">"
},
{
"code": null,
"e": 26133,
"s": 26115,
"text": "Attribute Values:"
},
{
"code": null,
"e": 26200,
"s": 26133,
"text": "pixels: It sets the width of table header cell in terms of pixels."
},
{
"code": null,
"e": 26270,
"s": 26200,
"text": "%: It sets the width of table header cell in terms of percentage (%)."
},
{
"code": null,
"e": 26279,
"s": 26270,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML th width Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th width Attribute</h2> <table border=\"1\" width=\"500\"> <tr> <th width=\"50%\">NAME</th> <th width=\"20%\">AGE</th> <th width=\"30%\">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>",
"e": 26843,
"s": 26279,
"text": null
},
{
"code": null,
"e": 26851,
"s": 26843,
"text": "Output:"
},
{
"code": null,
"e": 26940,
"s": 26851,
"text": "Supported Browsers: The browser supported by HTML <th> width attribute are listed below:"
},
{
"code": null,
"e": 26954,
"s": 26940,
"text": "Google Chrome"
},
{
"code": null,
"e": 26972,
"s": 26954,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26980,
"s": 26972,
"text": "Firefox"
},
{
"code": null,
"e": 26987,
"s": 26980,
"text": "Safari"
},
{
"code": null,
"e": 26993,
"s": 26987,
"text": "Opera"
},
{
"code": null,
"e": 27130,
"s": 26993,
"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": 27146,
"s": 27130,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 27151,
"s": 27146,
"text": "HTML"
},
{
"code": null,
"e": 27168,
"s": 27151,
"text": "Web Technologies"
},
{
"code": null,
"e": 27173,
"s": 27168,
"text": "HTML"
},
{
"code": null,
"e": 27271,
"s": 27173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27319,
"s": 27271,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27343,
"s": 27319,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27384,
"s": 27343,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 27434,
"s": 27384,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27484,
"s": 27434,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27524,
"s": 27484,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27557,
"s": 27524,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27602,
"s": 27557,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27645,
"s": 27602,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Image Matching with OpenCV’s Template Matching | by Aviad Atlas | Towards Data Science | As a data scientist at VATBox, I’ve mainly worked on projects which at their core involve building Machine Learning models. What’s nice about this project is that it purely includes building an algorithm to solve the given task. A real-world problem with a custom-made solution.
The problem in hand is essentially matching between two images which are close to being identical (changes can be due to image size, for example). The goal here is to do so in real-time, therefore we need the algorithm to be relatively fast.
At VATBox our world is a world of invoices. Users upload reports, which contain images of invoices, to our platform. A single report contains two groups of images, one is a collection of separate invoices, and the other is all the collection together in one single file. For reasons which we will not go into, there may be images in one group that won’t appear in the other. The goal is to detect the images which don’t appear in the other group (if there are any). If we match between all the images which are essentially the same image, we can also identify the spare ones.
So to find the spare images, we need to perform a comparison between every two images (or do we..? we’ll get to that..), one image being from the first group and the other from the second group. Once that is done, we can match between images, and then see which images are left without any match. We can build a Comparison Matrix which holds these comparisons.
During my research, I mostly encountered solutions that are based on features extracted from images to match between images, but that’s computationally expensive for our case, as we’re interested in doing this for every pair of images. Therefore we are in need of a different approach.
As described, the images that actually match, are close to being identical. So we can expect their pixel values to be relatively similar. So can we perhaps calculate the correlation between the two given signals? But how can this be done efficiently with images?
OpenCV has a Template Matching module. The purpose of this module is to find a given template within a (larger) image. The module enables us to “swipe” a template (T) across an image (I) and perform calculations efficiently (similarly to how a convolutional kernel is swiped on an image in a CNN).
This can be great for our needs! We can use this to swipe an image from the first group on an image of the other group efficently, as OpenCV’s implementation is optimal. Of course, since we’re looking for two images that match (and not a template in another image) the swiping is just done a single time.
The Template Matching module includes different methods of calculating correlations, one of them being a normalized calculation, returning values between 0 (no similarity) to 1 (completely identical images):
corr = cv2.matchTemplate(group1_image, group2_image, cv2.TM_CCOEFF_NORMED)[0][0]
The indexing shows that we’re accessing a matrix. As mentioned, we’re essentially performing a single swipe, therefore we’re just grabbing the single value from a matrix with a single element.
A word about the calculation. Prior to the actual correlation calculation, the images are normalized, resulting in a matrix (or tensor) with negative values as well as positive values. When performing the correlation calculation, similar regions will get positive values within the correlation calculation, whereas dissimilar regions will get negative values (resulting in lower correlation).
Since we’re comparing every pair of images, the complexity of the algorithm is O(n*m), n being the number of images in group one, and m being the number of images in group two. Can we make the algorithm more efficient?
As the above function returns values close to 1 for similar images, we can set a threshold (e.g. 0.9) for which there’s no need to keep on searching for a match if one is found. In addition, if a match is found, we’ll remove the matched images from our search. For example, if in the first iteration we are comparing an image from group one with 4 images from group two, on the second iteration we’ll do a comparison with only 3 images, and so on.
In this article, we reviewed a somewhat out of the ordinary real-world data science problem which required a tailor-made solution. We dug into OpenCV’s Template Matching and understood how it can be used to fulfill the requirements of the problem at hand. Hope you enjoyed it! | [
{
"code": null,
"e": 451,
"s": 172,
"text": "As a data scientist at VATBox, I’ve mainly worked on projects which at their core involve building Machine Learning models. What’s nice about this project is that it purely includes building an algorithm to solve the given task. A real-world problem with a custom-made solution."
},
{
"code": null,
"e": 693,
"s": 451,
"text": "The problem in hand is essentially matching between two images which are close to being identical (changes can be due to image size, for example). The goal here is to do so in real-time, therefore we need the algorithm to be relatively fast."
},
{
"code": null,
"e": 1269,
"s": 693,
"text": "At VATBox our world is a world of invoices. Users upload reports, which contain images of invoices, to our platform. A single report contains two groups of images, one is a collection of separate invoices, and the other is all the collection together in one single file. For reasons which we will not go into, there may be images in one group that won’t appear in the other. The goal is to detect the images which don’t appear in the other group (if there are any). If we match between all the images which are essentially the same image, we can also identify the spare ones."
},
{
"code": null,
"e": 1630,
"s": 1269,
"text": "So to find the spare images, we need to perform a comparison between every two images (or do we..? we’ll get to that..), one image being from the first group and the other from the second group. Once that is done, we can match between images, and then see which images are left without any match. We can build a Comparison Matrix which holds these comparisons."
},
{
"code": null,
"e": 1916,
"s": 1630,
"text": "During my research, I mostly encountered solutions that are based on features extracted from images to match between images, but that’s computationally expensive for our case, as we’re interested in doing this for every pair of images. Therefore we are in need of a different approach."
},
{
"code": null,
"e": 2179,
"s": 1916,
"text": "As described, the images that actually match, are close to being identical. So we can expect their pixel values to be relatively similar. So can we perhaps calculate the correlation between the two given signals? But how can this be done efficiently with images?"
},
{
"code": null,
"e": 2477,
"s": 2179,
"text": "OpenCV has a Template Matching module. The purpose of this module is to find a given template within a (larger) image. The module enables us to “swipe” a template (T) across an image (I) and perform calculations efficiently (similarly to how a convolutional kernel is swiped on an image in a CNN)."
},
{
"code": null,
"e": 2782,
"s": 2477,
"text": "This can be great for our needs! We can use this to swipe an image from the first group on an image of the other group efficently, as OpenCV’s implementation is optimal. Of course, since we’re looking for two images that match (and not a template in another image) the swiping is just done a single time."
},
{
"code": null,
"e": 2990,
"s": 2782,
"text": "The Template Matching module includes different methods of calculating correlations, one of them being a normalized calculation, returning values between 0 (no similarity) to 1 (completely identical images):"
},
{
"code": null,
"e": 3095,
"s": 2990,
"text": "corr = cv2.matchTemplate(group1_image, group2_image, cv2.TM_CCOEFF_NORMED)[0][0]"
},
{
"code": null,
"e": 3288,
"s": 3095,
"text": "The indexing shows that we’re accessing a matrix. As mentioned, we’re essentially performing a single swipe, therefore we’re just grabbing the single value from a matrix with a single element."
},
{
"code": null,
"e": 3681,
"s": 3288,
"text": "A word about the calculation. Prior to the actual correlation calculation, the images are normalized, resulting in a matrix (or tensor) with negative values as well as positive values. When performing the correlation calculation, similar regions will get positive values within the correlation calculation, whereas dissimilar regions will get negative values (resulting in lower correlation)."
},
{
"code": null,
"e": 3900,
"s": 3681,
"text": "Since we’re comparing every pair of images, the complexity of the algorithm is O(n*m), n being the number of images in group one, and m being the number of images in group two. Can we make the algorithm more efficient?"
},
{
"code": null,
"e": 4348,
"s": 3900,
"text": "As the above function returns values close to 1 for similar images, we can set a threshold (e.g. 0.9) for which there’s no need to keep on searching for a match if one is found. In addition, if a match is found, we’ll remove the matched images from our search. For example, if in the first iteration we are comparing an image from group one with 4 images from group two, on the second iteration we’ll do a comparison with only 3 images, and so on."
}
] |
JavaScript Error Handling: Unexpected Token - GeeksforGeeks | 20 Jul, 2021
Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + – var if-else var etc}. Unexpected token is similar to syntax error but more specific.Semicolon(;) in JavaScript plays a vital role while writing a programme.Usage: To understand this we should know JavaScript also has a particular syntax like in JavaScript are concluded by a semi-colon(;) and there are many rules like all spaces/tabs/newlines are considered whitespace. JavaScript code are parsed from left to right, it is a process in which the parser converts the statements and whitespace into unique elements.
Tokens: All the operator (+, -, if, else...) are reserved by the JavaScript engine.So, it cannot be used incorrectly .It cannot be used as part of variable names.
Line terminators: A JavaScript code should end with semi-colon(;).
Control characters: To control code, it is important to maintain braces({ }) in a code. It is also important to defines the scope of the code.
Comments: A line of code written after // is a comment. JavaScript ignores this line.
Whitespace: It is a tab/space in code.Changing it does not change the functionality of the code.
Therefore JavaScript code is very sensitive to any typo error. These examples given below explain the ways that unexpected token can occur.Example 1: It was either expecting a parameter in myFunc(mycar, ) or not, .So it was enable to execute this code.
javascript
<script>function multiple(number1, number2) { function myFunc(theObject) { theObject.make = 'Toyota'; } var mycar = { make: 'BMW', model: 'Q8-7', year: 2005 }; var x, y; x = mycar.make; myFunc(mycar, ); y = mycar.make;</script>
Output:
Unexpected end of input
Example 2: An unexpected token ‘, ‘occurs after i=0 which javascript cannot recognize.We can remove error here by removing extra.
javascript
<script>for(i=0, ;i<10;i++){ document.writeln(i);}</script>
Output:
expected expression, got ', '
Example 3: An unexpected token ‘)’ occur after i++ which JavaScript cannot recognize.We can remove error here by removing extra ).
javascript
<script>for(i=0;i<10;i++)){ console.log(i);}</script>
Output
expected expression, got ')'
Example 4: At end of if’s body JavaScript was expecting braces “}” but instead it got an unexpected token else.If we put } at the end of the body of if.
javascript
<script>var n = 10;if (n == 10) { console.log("TRUE"); else { console.log("FALSE"); }</script>
Output
expected expression, got keyword 'else'
Similarly, unnecessary use of any token will throw this type of error. We can remove this error by binding by following the programming rules of JavaScript.
sagartomar9927
JavaScript-Misc
Picked
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
How to Open URL in New Tab using JavaScript ? | [
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 25046,
"s": 24318,
"text": "Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + – var if-else var etc}. Unexpected token is similar to syntax error but more specific.Semicolon(;) in JavaScript plays a vital role while writing a programme.Usage: To understand this we should know JavaScript also has a particular syntax like in JavaScript are concluded by a semi-colon(;) and there are many rules like all spaces/tabs/newlines are considered whitespace. JavaScript code are parsed from left to right, it is a process in which the parser converts the statements and whitespace into unique elements. "
},
{
"code": null,
"e": 25209,
"s": 25046,
"text": "Tokens: All the operator (+, -, if, else...) are reserved by the JavaScript engine.So, it cannot be used incorrectly .It cannot be used as part of variable names."
},
{
"code": null,
"e": 25276,
"s": 25209,
"text": "Line terminators: A JavaScript code should end with semi-colon(;)."
},
{
"code": null,
"e": 25419,
"s": 25276,
"text": "Control characters: To control code, it is important to maintain braces({ }) in a code. It is also important to defines the scope of the code."
},
{
"code": null,
"e": 25505,
"s": 25419,
"text": "Comments: A line of code written after // is a comment. JavaScript ignores this line."
},
{
"code": null,
"e": 25602,
"s": 25505,
"text": "Whitespace: It is a tab/space in code.Changing it does not change the functionality of the code."
},
{
"code": null,
"e": 25857,
"s": 25602,
"text": "Therefore JavaScript code is very sensitive to any typo error. These examples given below explain the ways that unexpected token can occur.Example 1: It was either expecting a parameter in myFunc(mycar, ) or not, .So it was enable to execute this code. "
},
{
"code": null,
"e": 25868,
"s": 25857,
"text": "javascript"
},
{
"code": "<script>function multiple(number1, number2) { function myFunc(theObject) { theObject.make = 'Toyota'; } var mycar = { make: 'BMW', model: 'Q8-7', year: 2005 }; var x, y; x = mycar.make; myFunc(mycar, ); y = mycar.make;</script>",
"e": 26148,
"s": 25868,
"text": null
},
{
"code": null,
"e": 26158,
"s": 26148,
"text": "Output: "
},
{
"code": null,
"e": 26182,
"s": 26158,
"text": "Unexpected end of input"
},
{
"code": null,
"e": 26314,
"s": 26182,
"text": "Example 2: An unexpected token ‘, ‘occurs after i=0 which javascript cannot recognize.We can remove error here by removing extra. "
},
{
"code": null,
"e": 26325,
"s": 26314,
"text": "javascript"
},
{
"code": "<script>for(i=0, ;i<10;i++){ document.writeln(i);}</script>",
"e": 26386,
"s": 26325,
"text": null
},
{
"code": null,
"e": 26396,
"s": 26386,
"text": "Output: "
},
{
"code": null,
"e": 26426,
"s": 26396,
"text": "expected expression, got ', '"
},
{
"code": null,
"e": 26559,
"s": 26426,
"text": "Example 3: An unexpected token ‘)’ occur after i++ which JavaScript cannot recognize.We can remove error here by removing extra ). "
},
{
"code": null,
"e": 26570,
"s": 26559,
"text": "javascript"
},
{
"code": "<script>for(i=0;i<10;i++)){ console.log(i);}</script>",
"e": 26625,
"s": 26570,
"text": null
},
{
"code": null,
"e": 26634,
"s": 26625,
"text": "Output "
},
{
"code": null,
"e": 26663,
"s": 26634,
"text": "expected expression, got ')'"
},
{
"code": null,
"e": 26818,
"s": 26663,
"text": "Example 4: At end of if’s body JavaScript was expecting braces “}” but instead it got an unexpected token else.If we put } at the end of the body of if. "
},
{
"code": null,
"e": 26829,
"s": 26818,
"text": "javascript"
},
{
"code": "<script>var n = 10;if (n == 10) { console.log(\"TRUE\"); else { console.log(\"FALSE\"); }</script>",
"e": 26940,
"s": 26829,
"text": null
},
{
"code": null,
"e": 26949,
"s": 26940,
"text": "Output "
},
{
"code": null,
"e": 26989,
"s": 26949,
"text": "expected expression, got keyword 'else'"
},
{
"code": null,
"e": 27147,
"s": 26989,
"text": "Similarly, unnecessary use of any token will throw this type of error. We can remove this error by binding by following the programming rules of JavaScript. "
},
{
"code": null,
"e": 27162,
"s": 27147,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27178,
"s": 27162,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27185,
"s": 27178,
"text": "Picked"
},
{
"code": null,
"e": 27202,
"s": 27185,
"text": "Web Technologies"
},
{
"code": null,
"e": 27229,
"s": 27202,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27245,
"s": 27229,
"text": "Write From Home"
},
{
"code": null,
"e": 27343,
"s": 27245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27352,
"s": 27343,
"text": "Comments"
},
{
"code": null,
"e": 27365,
"s": 27352,
"text": "Old Comments"
},
{
"code": null,
"e": 27407,
"s": 27365,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27450,
"s": 27407,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27495,
"s": 27450,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27539,
"s": 27495,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27597,
"s": 27539,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27657,
"s": 27597,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27684,
"s": 27657,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 27745,
"s": 27684,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27795,
"s": 27745,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
LASTNONBLANK function | Returns the last value in the column filtered by the current context, where the expression is not blank.
LASTNONBLANK (<column>, <expression>)
column
A column expression.
expression
An expression evaluated for blanks for each value of column.
A table containing a single column and single row with the computed last non-blank value.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
= LASTNONBLANK (Sales [Sales Amount], MIN (Sales [Date])>3/31/2015)
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2106,
"s": 2001,
"text": "Returns the last value in the column filtered by the current context, where the expression is not blank."
},
{
"code": null,
"e": 2146,
"s": 2106,
"text": "LASTNONBLANK (<column>, <expression>) \n"
},
{
"code": null,
"e": 2153,
"s": 2146,
"text": "column"
},
{
"code": null,
"e": 2174,
"s": 2153,
"text": "A column expression."
},
{
"code": null,
"e": 2185,
"s": 2174,
"text": "expression"
},
{
"code": null,
"e": 2246,
"s": 2185,
"text": "An expression evaluated for blanks for each value of column."
},
{
"code": null,
"e": 2336,
"s": 2246,
"text": "A table containing a single column and single row with the computed last non-blank value."
},
{
"code": null,
"e": 2386,
"s": 2336,
"text": "The dates parameter can be any of the following −"
},
{
"code": null,
"e": 2421,
"s": 2386,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2456,
"s": 2421,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2525,
"s": 2456,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2594,
"s": 2525,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2671,
"s": 2594,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2748,
"s": 2671,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2785,
"s": 2748,
"text": "Constraints on Boolean expressions −"
},
{
"code": null,
"e": 2837,
"s": 2785,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2889,
"s": 2837,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2935,
"s": 2889,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 2981,
"s": 2935,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 3092,
"s": 2981,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3203,
"s": 3092,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3319,
"s": 3203,
"text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value."
},
{
"code": null,
"e": 3388,
"s": 3319,
"text": "= LASTNONBLANK (Sales [Sales Amount], MIN (Sales [Date])>3/31/2015) "
},
{
"code": null,
"e": 3423,
"s": 3388,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3437,
"s": 3423,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3470,
"s": 3437,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3484,
"s": 3470,
"text": " Randy Minder"
},
{
"code": null,
"e": 3519,
"s": 3484,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3533,
"s": 3519,
"text": " Randy Minder"
},
{
"code": null,
"e": 3540,
"s": 3533,
"text": " Print"
},
{
"code": null,
"e": 3551,
"s": 3540,
"text": " Add Notes"
}
] |
Production-Grade R Shiny with Golem: Prototyping | by Liz Nelson | Towards Data Science | It’s an exciting time to be an R Shiny developer — R Shiny is being increasingly adopted to let data scientists make fast, beautiful web applications to share data and even provide public-facing access to data products and dashboards. R Shiny lets non-web developers get applications up and running quickly, but also puts data scientists and data analysts in the position of becoming web developers or software engineers in terms of dependency management, reproducibility, testing, and deployment responsibilities. As R Shiny has been adopted in various spheres, a new world of production Shiny tools have been developed to help meet the challenges of developing robust, sustainable, and reproducible R Shiny applications created and maintained by data scientists and non-web developers. In fact, I would argue that even if you don’t think of your application as truly production or software, you too can benefit from using production Shiny tools in your development workflow.
In this tutorial I will cover the basics of getting an R Shiny application up and running in development with a new package called Golem, which is particularly designed as an opinionated framework for developing production-ready R Shiny applications. For the purpose of this tutorial, our client is me, and we’ll be focused on prototyping a weightlifting application.
In this tutorial, you will learn:
Basic ideas of user interviewing and prototyping
Basic wireframe drawing
How to make a working prototype in R Shiny with filler text and demo graphics using the shinipsum package
You may be wondering why this section is here — come on, get to the code! Well, before we start muddling around in R, we should probably take a moment to figure out what we’re trying to do! This is perhaps the most underrated development step of them all: actually defining what we want to build. Luckily, given that the user of this application is me (or us), this should be a pretty easy user interview!
Core Functionality
Upload updated exports from Fitbod (where I generate and track my workouts)
Track how much weight I have lifted over time to feel accomplished
Track how much total volume per workout I have lifted in different exercises
Track my projected 1 rep max for different exercises
Track how much I have lifted per muscle group
One last step before we get to coding, I promise. We’re going to do a quick (manual) sketch of what we’re going to build so we have an idea of what we’re going for. There are lots of cool tools for interactive mockups, if you are so inclined, but we’re going to keep it simple for now and just draw it out. I drew this one out on a tablet, but pen and paper works just fine as well.
First, let’s draw what we want our main dashboard page and the data upload to look like:
We can also draw two more tabs to include the content on exercise-specific statistics and muscle-group statistics outlined in our user interview.
Starting a project with Golem is deceptively simple. First, make sure you have it installed using your good old friend install.packages('golem').
After you’ve installed golem, you should be able to go to ‘File’ -> ‘New Directory’ -> ‘Package for Shiny App using golem’ in your RStudio menu.
You can also create your project on the command line by typing golem::create_golem("projectName") in your RStudio console.
From here, Golem will open up lots of files to get you going! Let’s start with dev/01_start.R at the comment numbered 1.1. Go ahead and fill out the golem::fill_desc() function with your name, the package name, etc. I prefer to set up my repos ahead of time, so I’m going to create an empty repo on GitHub and input the URL here as well.
Now let’s call golem::set_golem_options() to set all this up. We’re also going to keep everything in comment ‘1.2 — Set common files’ as it is for now.
We’re now going to run golem::use_recommended_tests() to add a folder for unit tests we can add later using testthat. Testing allows you to automate the process you use to ensure your code is working correctly. Why should you use unit testing? Well, this says it pretty well:
I started using automated tests because I discovered I was spending too much time re-fixing bugs that I’d already fixed before. While writing code or fixing bugs, I’d perform interactive tests to make sure the code worked. But I never had a system which could store those tests so I could re-run them as needed. I think that this is a common practice among R programmers. It’s not that you don’t test your code, it’s that you don’t automate your tests.
From R Packages by Hadley Wickham and Jennifer Bryan
Now we run golem::use_recommended_deps() to add Golem’s recommended dependencies. These are packages you are almost certain to need later in your development process.
I’m also going to run golem::use_utils_ui() and golem::use_utils_server() because I'm never one to say no to some nice pre-written functions I'm likely to need later. These aren't strictly necessary, but they add some functions for common R Shiny tasks that might help us out.
With that, we’re ready to get prototyping!
Remember that drawing we made way back when of what we wanted to make? Well, now it’s time to see if it looks any good when we actually try to make it in Shiny!
Prototyping is a great way to be able to pulse-check your user requirements before you get all the way through building something. When people can see what an app looks like and play with it, even if it doesn’t have the final information yet, they tend to clarify what they want as they realize the application is missing something, or perhaps they don’t like or want a feature they thought would be essential.
We’re going to try out a fun new part of the golem-universe to do our prototyping: {shinipsum}
As always, we’ll start with installing it: install.packages('shinipsum') and we'll let golem know we'll be using it with usethis::use_package("shinipsum").
Let’s start prototyping!
If we look back at our diagrams, we see we really had three tabs (I’m not counting our initial pop-up to have our user upload their data).
This means that having three modules, one for each page, is probably a good start.
Let’s create our first module using golem! In your R terminal, you can use golem’s functions to directly add module infrastructure:
golem::add_module(name = 'Home')
Now let’s add our other modules:
golem::add_module(name = 'Exercises')
golem::add_module(name = 'MuscleGroup')
Cool- we’ve got two modules! Let’s do as it says in our newly created modules and add the references to these modules in the main UI and main server, so the application knows to call them. Once you’ve pasted those chunks into the right spot in the R/app_ui.R and the R/app_server.R files, feel free to delete the commented chunk at the bottom of your module files.
Now let’s look back at the drawing of our first page to start working on our modules.
Hey, that navigation bit looks pretty important, so let’s focus on that first. We want this to look pretty, so we’re going to bring out the big guns of gorgeous Shiny UI design:
install.packages("shinydashboard")install.packages("shinydashboardPlus")usethis::use_package("shinydashboard")usethis::use_package("shinydashboardPlus")
We’re going to put our sidebar in our main R/app_ui.R file, because we'll want it visible on all our pages. Now hold with me here, because this is going to be a wild ride of UI code for a minute.
app_ui <- function() { tagList( # Leave this function for adding external resources golem_add_external_resources(), # Define this page as a dashboard page to signal we're using the dashboard page format shinydashboardPlus::dashboardPagePlus( header = shinydashboardPlus::dashboardHeaderPlus( title = "Fitbod Tracking Dashboard", enable_rightsidebar = FALSE ), # Create our navigation menu that links to each of the tabs we defined sidebar = shinydashboard::dashboardSidebar( shinydashboard::sidebarMenu( # Setting id makes input$tabs give the tabName of currently-selected tab id = "tabs", shinydashboard::menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")), shinydashboard::menuItem("Muscle Group View", icon = icon("th"), tabName = "mg"), shinydashboard::menuItem("Exercise View", icon = icon("bar-chart-o"), tabName = "ev" )) ),# Show the appropriate tab's content in the main body of our dashboard when we select it body = shinydashboard::dashboardBody( shinydashboard::tabItems( shinydashboard::tabItem("dashboard", mod_Home_ui("Home_ui_1")), shinydashboard::tabItem("mg", mod_MuscleGroup_ui("MuscleGroup_ui_1")), shinydashboard::tabItem("ev", mod_Exercises_ui("Exercises_ui_1") ) ) ), rightsidebar = NULL, title = "FitBod App Monitoring Dashboard" ) )}
Just for fun, let’s also add something to each of our module pages so we can tell if our navigation is working.
In each of your R/mod_TABNAME_ui.R files, add a little line to signify which tab is showing after the tagList(
For example:
mod_Home_ui <- function(id){ ns <- NS(id) tagList( h1("Welcome HOME!") )}
Now let’s see if this works! If you are a more experienced Shiny developer, you may have noticed we’re not sourcing our modules anywhere, and there’s no ‘Run App’ button on any of our scripts. Those pieces are both integrated into the Golem infrastructure! So how do we run our app? Let’s navigate to the dev/run_dev.Rscript.
Hey, that run_app() command looks familiar! Since we're building our app as a package in golem, we run the run_app() function out of our own package. Let's go ahead and run this script!
Assuming everything worked correctly, we should see something like this pop up:
Excellent! Let’s work on fleshing out these pages now.
So let’s put {shinipsum} to use so we don't have to worry about the data for now. We will need good old {ggplot2} though, so if you don't have it installed, please install it and remember to also use the command usethis::use_package("ggplot2") in your R terminal so golem knows to load the package when it runs our app.
In our R/mod_Home.R file, we can change our placeholder text to look more like what we expect to see and add placeholder graphs and tables as well.
A few notes:
When you call functions in a golem app, you need to make sure you attach the package using the :: notation. This is a good practice anyway as it makes sure you're using the right function from the right package when functions have clashing names.
We’re using the shinydashboard::box() function to give us nice formatted boxes with minimal work-- that's one of the great advantages of these packages!
Shinipsum gives us automatic fake data to make our plots with so we don’t have to worry about our data yet.
We’re using modules, so we need the ns() around our output tags so our namespacing will work right.
mod_Home_ui <- function(id){ ns <- NS(id) tagList( fluidPage( fluidRow( column(width = 5, h2("Welcome!")), br(),br(),br() ), fluidRow( column(width = 10, shinydashboard::box( background = "blue", h2("You lifted XYZ xx times!"), title = "Congrats!"), br(), br(), br(), br() )), fluidRow( shinydashboard::box( title = "Top Exercises", width = 6, DT::dataTableOutput(ns('data_table'))), shinydashboard::box( title = "Total Weight Lifted", width = 6, plotOutput(ns("plot")) ) ) ) )}mod_Home_server <- function(input, output, session){ ns <- session$ns output$data_table <- DT::renderDT({ shinipsum::random_DT(5, 3, "numeric") }) output$plot <- renderPlot({ shinipsum::random_ggplot(type = "line") })}
Now if you run your app again (remember, we do this from the dev/run_dev.Rscript now) it should look like this:
That’s looking much better! Time to finish up the prototypes of our other two tabs. Remember, our exercise and muscle group tabs should look like this (according to our wireframes):
Luckily, we can reuse a fair amount of our code from our dashboard page. So in R/mod_Exercises.R we will flesh out this demo UI!
A few notes:
We have hard-coded the choices in our input box for now, but we’ll fill this with our data later!
You’ll notice we’re using boxes again, as well as a Shiny function to create a spot for our users to filter based on what exercise they want to look at.
mod_Exercises_ui <- function(id){ ns <- NS(id) tagList( fluidPage( fluidRow( h2("Exercise Progress for "), selectizeInput( inputId = ns("exercises"), label = "", # Hard coded for now, but we'll deal with this later! choices = c("Dumbell Bicep Curl", "Deadlift"), selected = "Dumbell Bicep Curl", width = '50%', multiple = FALSE) ), fluidRow( column(width = 10, shinydashboard::box( background = "blue", h2("Your current projected 1 rep max is x!"), title = "Congrats!") )), fluidRow( shinydashboard::box( title = "Total Weight Per Workout", width = 6, plotOutput(ns("plot2"))), shinydashboard::box( title = "Max Weight Per Workout", width = 6, plotOutput(ns("plot3")) ) ) ) )}mod_Exercises_server <- function(input, output, session){ ns <- session$ns output$plot2 <- renderPlot({ shinipsum::random_ggplot(type = "line") }) output$plot3 <- renderPlot({ shinipsum::random_ggplot(type = "line") })}
Great! If you run your app, your ‘Exercises’ tab should now look like this:
I bet you can guess what we’re going to do on the muscle groups tab! Try and do that one yourself based on what we’ve already written, but if you need help, my code is below.
In R/mod_MuscleGroup.R:
mod_MuscleGroup_ui <- function(id){ ns <- NS(id) tagList( fluidPage( fluidRow( h2("Muscle Group Progress for "), selectizeInput( inputId = ns("muscles"), label = "", choices = c("Back", "Hamstrings"), selected = "Back", width = '50%', multiple = FALSE) ), fluidRow( shinydashboard::box( title = "Max Weight Over Time", width = 6, plotOutput(ns("plot4"))), shinydashboard::box( title = "Top Exercises", width = 6, DT::dataTableOutput(ns('data_table2')) ) ) ) )}mod_MuscleGroup_server <- function(input, output, session){ ns <- session$ns output$plot4 <- renderPlot({ shinipsum::random_ggplot(type = "line") }) output$data_table2 <- DT::renderDT({ shinipsum::random_DT(5, 3, "numeric") })}
The final result should look like this:
Now we have a fully functioning prototype ready to show our theoretical user (in this case, us)! We can make alterations based on our user’s feedback much more easily using prototyping graphs rather than dealing with all our data wrangling, and we can get a prototype to our user much more quickly when we don’t have to make the whole app work before they see anything. Once our user approves the final wireframe, we’ll be ready to build the rest of our Shiny app the normal way and we’re all set up to use automated testing and Docker-based deployments using the Golem infrastructure.
If you’ve had any trouble following along, all of the code for this tutorial is in my Github repository here. | [
{
"code": null,
"e": 1149,
"s": 172,
"text": "It’s an exciting time to be an R Shiny developer — R Shiny is being increasingly adopted to let data scientists make fast, beautiful web applications to share data and even provide public-facing access to data products and dashboards. R Shiny lets non-web developers get applications up and running quickly, but also puts data scientists and data analysts in the position of becoming web developers or software engineers in terms of dependency management, reproducibility, testing, and deployment responsibilities. As R Shiny has been adopted in various spheres, a new world of production Shiny tools have been developed to help meet the challenges of developing robust, sustainable, and reproducible R Shiny applications created and maintained by data scientists and non-web developers. In fact, I would argue that even if you don’t think of your application as truly production or software, you too can benefit from using production Shiny tools in your development workflow."
},
{
"code": null,
"e": 1517,
"s": 1149,
"text": "In this tutorial I will cover the basics of getting an R Shiny application up and running in development with a new package called Golem, which is particularly designed as an opinionated framework for developing production-ready R Shiny applications. For the purpose of this tutorial, our client is me, and we’ll be focused on prototyping a weightlifting application."
},
{
"code": null,
"e": 1551,
"s": 1517,
"text": "In this tutorial, you will learn:"
},
{
"code": null,
"e": 1600,
"s": 1551,
"text": "Basic ideas of user interviewing and prototyping"
},
{
"code": null,
"e": 1624,
"s": 1600,
"text": "Basic wireframe drawing"
},
{
"code": null,
"e": 1730,
"s": 1624,
"text": "How to make a working prototype in R Shiny with filler text and demo graphics using the shinipsum package"
},
{
"code": null,
"e": 2136,
"s": 1730,
"text": "You may be wondering why this section is here — come on, get to the code! Well, before we start muddling around in R, we should probably take a moment to figure out what we’re trying to do! This is perhaps the most underrated development step of them all: actually defining what we want to build. Luckily, given that the user of this application is me (or us), this should be a pretty easy user interview!"
},
{
"code": null,
"e": 2155,
"s": 2136,
"text": "Core Functionality"
},
{
"code": null,
"e": 2231,
"s": 2155,
"text": "Upload updated exports from Fitbod (where I generate and track my workouts)"
},
{
"code": null,
"e": 2298,
"s": 2231,
"text": "Track how much weight I have lifted over time to feel accomplished"
},
{
"code": null,
"e": 2375,
"s": 2298,
"text": "Track how much total volume per workout I have lifted in different exercises"
},
{
"code": null,
"e": 2428,
"s": 2375,
"text": "Track my projected 1 rep max for different exercises"
},
{
"code": null,
"e": 2474,
"s": 2428,
"text": "Track how much I have lifted per muscle group"
},
{
"code": null,
"e": 2857,
"s": 2474,
"text": "One last step before we get to coding, I promise. We’re going to do a quick (manual) sketch of what we’re going to build so we have an idea of what we’re going for. There are lots of cool tools for interactive mockups, if you are so inclined, but we’re going to keep it simple for now and just draw it out. I drew this one out on a tablet, but pen and paper works just fine as well."
},
{
"code": null,
"e": 2946,
"s": 2857,
"text": "First, let’s draw what we want our main dashboard page and the data upload to look like:"
},
{
"code": null,
"e": 3092,
"s": 2946,
"text": "We can also draw two more tabs to include the content on exercise-specific statistics and muscle-group statistics outlined in our user interview."
},
{
"code": null,
"e": 3238,
"s": 3092,
"text": "Starting a project with Golem is deceptively simple. First, make sure you have it installed using your good old friend install.packages('golem')."
},
{
"code": null,
"e": 3383,
"s": 3238,
"text": "After you’ve installed golem, you should be able to go to ‘File’ -> ‘New Directory’ -> ‘Package for Shiny App using golem’ in your RStudio menu."
},
{
"code": null,
"e": 3506,
"s": 3383,
"text": "You can also create your project on the command line by typing golem::create_golem(\"projectName\") in your RStudio console."
},
{
"code": null,
"e": 3844,
"s": 3506,
"text": "From here, Golem will open up lots of files to get you going! Let’s start with dev/01_start.R at the comment numbered 1.1. Go ahead and fill out the golem::fill_desc() function with your name, the package name, etc. I prefer to set up my repos ahead of time, so I’m going to create an empty repo on GitHub and input the URL here as well."
},
{
"code": null,
"e": 3996,
"s": 3844,
"text": "Now let’s call golem::set_golem_options() to set all this up. We’re also going to keep everything in comment ‘1.2 — Set common files’ as it is for now."
},
{
"code": null,
"e": 4272,
"s": 3996,
"text": "We’re now going to run golem::use_recommended_tests() to add a folder for unit tests we can add later using testthat. Testing allows you to automate the process you use to ensure your code is working correctly. Why should you use unit testing? Well, this says it pretty well:"
},
{
"code": null,
"e": 4725,
"s": 4272,
"text": "I started using automated tests because I discovered I was spending too much time re-fixing bugs that I’d already fixed before. While writing code or fixing bugs, I’d perform interactive tests to make sure the code worked. But I never had a system which could store those tests so I could re-run them as needed. I think that this is a common practice among R programmers. It’s not that you don’t test your code, it’s that you don’t automate your tests."
},
{
"code": null,
"e": 4778,
"s": 4725,
"text": "From R Packages by Hadley Wickham and Jennifer Bryan"
},
{
"code": null,
"e": 4945,
"s": 4778,
"text": "Now we run golem::use_recommended_deps() to add Golem’s recommended dependencies. These are packages you are almost certain to need later in your development process."
},
{
"code": null,
"e": 5222,
"s": 4945,
"text": "I’m also going to run golem::use_utils_ui() and golem::use_utils_server() because I'm never one to say no to some nice pre-written functions I'm likely to need later. These aren't strictly necessary, but they add some functions for common R Shiny tasks that might help us out."
},
{
"code": null,
"e": 5265,
"s": 5222,
"text": "With that, we’re ready to get prototyping!"
},
{
"code": null,
"e": 5426,
"s": 5265,
"text": "Remember that drawing we made way back when of what we wanted to make? Well, now it’s time to see if it looks any good when we actually try to make it in Shiny!"
},
{
"code": null,
"e": 5837,
"s": 5426,
"text": "Prototyping is a great way to be able to pulse-check your user requirements before you get all the way through building something. When people can see what an app looks like and play with it, even if it doesn’t have the final information yet, they tend to clarify what they want as they realize the application is missing something, or perhaps they don’t like or want a feature they thought would be essential."
},
{
"code": null,
"e": 5932,
"s": 5837,
"text": "We’re going to try out a fun new part of the golem-universe to do our prototyping: {shinipsum}"
},
{
"code": null,
"e": 6088,
"s": 5932,
"text": "As always, we’ll start with installing it: install.packages('shinipsum') and we'll let golem know we'll be using it with usethis::use_package(\"shinipsum\")."
},
{
"code": null,
"e": 6113,
"s": 6088,
"text": "Let’s start prototyping!"
},
{
"code": null,
"e": 6252,
"s": 6113,
"text": "If we look back at our diagrams, we see we really had three tabs (I’m not counting our initial pop-up to have our user upload their data)."
},
{
"code": null,
"e": 6335,
"s": 6252,
"text": "This means that having three modules, one for each page, is probably a good start."
},
{
"code": null,
"e": 6467,
"s": 6335,
"text": "Let’s create our first module using golem! In your R terminal, you can use golem’s functions to directly add module infrastructure:"
},
{
"code": null,
"e": 6500,
"s": 6467,
"text": "golem::add_module(name = 'Home')"
},
{
"code": null,
"e": 6533,
"s": 6500,
"text": "Now let’s add our other modules:"
},
{
"code": null,
"e": 6571,
"s": 6533,
"text": "golem::add_module(name = 'Exercises')"
},
{
"code": null,
"e": 6611,
"s": 6571,
"text": "golem::add_module(name = 'MuscleGroup')"
},
{
"code": null,
"e": 6976,
"s": 6611,
"text": "Cool- we’ve got two modules! Let’s do as it says in our newly created modules and add the references to these modules in the main UI and main server, so the application knows to call them. Once you’ve pasted those chunks into the right spot in the R/app_ui.R and the R/app_server.R files, feel free to delete the commented chunk at the bottom of your module files."
},
{
"code": null,
"e": 7062,
"s": 6976,
"text": "Now let’s look back at the drawing of our first page to start working on our modules."
},
{
"code": null,
"e": 7240,
"s": 7062,
"text": "Hey, that navigation bit looks pretty important, so let’s focus on that first. We want this to look pretty, so we’re going to bring out the big guns of gorgeous Shiny UI design:"
},
{
"code": null,
"e": 7393,
"s": 7240,
"text": "install.packages(\"shinydashboard\")install.packages(\"shinydashboardPlus\")usethis::use_package(\"shinydashboard\")usethis::use_package(\"shinydashboardPlus\")"
},
{
"code": null,
"e": 7589,
"s": 7393,
"text": "We’re going to put our sidebar in our main R/app_ui.R file, because we'll want it visible on all our pages. Now hold with me here, because this is going to be a wild ride of UI code for a minute."
},
{
"code": null,
"e": 9065,
"s": 7589,
"text": "app_ui <- function() { tagList( # Leave this function for adding external resources golem_add_external_resources(), # Define this page as a dashboard page to signal we're using the dashboard page format shinydashboardPlus::dashboardPagePlus( header = shinydashboardPlus::dashboardHeaderPlus( title = \"Fitbod Tracking Dashboard\", enable_rightsidebar = FALSE ), # Create our navigation menu that links to each of the tabs we defined sidebar = shinydashboard::dashboardSidebar( shinydashboard::sidebarMenu( # Setting id makes input$tabs give the tabName of currently-selected tab id = \"tabs\", shinydashboard::menuItem(\"Dashboard\", tabName = \"dashboard\", icon = icon(\"dashboard\")), shinydashboard::menuItem(\"Muscle Group View\", icon = icon(\"th\"), tabName = \"mg\"), shinydashboard::menuItem(\"Exercise View\", icon = icon(\"bar-chart-o\"), tabName = \"ev\" )) ),# Show the appropriate tab's content in the main body of our dashboard when we select it body = shinydashboard::dashboardBody( shinydashboard::tabItems( shinydashboard::tabItem(\"dashboard\", mod_Home_ui(\"Home_ui_1\")), shinydashboard::tabItem(\"mg\", mod_MuscleGroup_ui(\"MuscleGroup_ui_1\")), shinydashboard::tabItem(\"ev\", mod_Exercises_ui(\"Exercises_ui_1\") ) ) ), rightsidebar = NULL, title = \"FitBod App Monitoring Dashboard\" ) )}"
},
{
"code": null,
"e": 9177,
"s": 9065,
"text": "Just for fun, let’s also add something to each of our module pages so we can tell if our navigation is working."
},
{
"code": null,
"e": 9288,
"s": 9177,
"text": "In each of your R/mod_TABNAME_ui.R files, add a little line to signify which tab is showing after the tagList("
},
{
"code": null,
"e": 9301,
"s": 9288,
"text": "For example:"
},
{
"code": null,
"e": 9379,
"s": 9301,
"text": "mod_Home_ui <- function(id){ ns <- NS(id) tagList( h1(\"Welcome HOME!\") )}"
},
{
"code": null,
"e": 9705,
"s": 9379,
"text": "Now let’s see if this works! If you are a more experienced Shiny developer, you may have noticed we’re not sourcing our modules anywhere, and there’s no ‘Run App’ button on any of our scripts. Those pieces are both integrated into the Golem infrastructure! So how do we run our app? Let’s navigate to the dev/run_dev.Rscript."
},
{
"code": null,
"e": 9891,
"s": 9705,
"text": "Hey, that run_app() command looks familiar! Since we're building our app as a package in golem, we run the run_app() function out of our own package. Let's go ahead and run this script!"
},
{
"code": null,
"e": 9971,
"s": 9891,
"text": "Assuming everything worked correctly, we should see something like this pop up:"
},
{
"code": null,
"e": 10026,
"s": 9971,
"text": "Excellent! Let’s work on fleshing out these pages now."
},
{
"code": null,
"e": 10346,
"s": 10026,
"text": "So let’s put {shinipsum} to use so we don't have to worry about the data for now. We will need good old {ggplot2} though, so if you don't have it installed, please install it and remember to also use the command usethis::use_package(\"ggplot2\") in your R terminal so golem knows to load the package when it runs our app."
},
{
"code": null,
"e": 10494,
"s": 10346,
"text": "In our R/mod_Home.R file, we can change our placeholder text to look more like what we expect to see and add placeholder graphs and tables as well."
},
{
"code": null,
"e": 10507,
"s": 10494,
"text": "A few notes:"
},
{
"code": null,
"e": 10754,
"s": 10507,
"text": "When you call functions in a golem app, you need to make sure you attach the package using the :: notation. This is a good practice anyway as it makes sure you're using the right function from the right package when functions have clashing names."
},
{
"code": null,
"e": 10907,
"s": 10754,
"text": "We’re using the shinydashboard::box() function to give us nice formatted boxes with minimal work-- that's one of the great advantages of these packages!"
},
{
"code": null,
"e": 11015,
"s": 10907,
"text": "Shinipsum gives us automatic fake data to make our plots with so we don’t have to worry about our data yet."
},
{
"code": null,
"e": 11115,
"s": 11015,
"text": "We’re using modules, so we need the ns() around our output tags so our namespacing will work right."
},
{
"code": null,
"e": 12050,
"s": 11115,
"text": "mod_Home_ui <- function(id){ ns <- NS(id) tagList( fluidPage( fluidRow( column(width = 5, h2(\"Welcome!\")), br(),br(),br() ), fluidRow( column(width = 10, shinydashboard::box( background = \"blue\", h2(\"You lifted XYZ xx times!\"), title = \"Congrats!\"), br(), br(), br(), br() )), fluidRow( shinydashboard::box( title = \"Top Exercises\", width = 6, DT::dataTableOutput(ns('data_table'))), shinydashboard::box( title = \"Total Weight Lifted\", width = 6, plotOutput(ns(\"plot\")) ) ) ) )}mod_Home_server <- function(input, output, session){ ns <- session$ns output$data_table <- DT::renderDT({ shinipsum::random_DT(5, 3, \"numeric\") }) output$plot <- renderPlot({ shinipsum::random_ggplot(type = \"line\") })}"
},
{
"code": null,
"e": 12162,
"s": 12050,
"text": "Now if you run your app again (remember, we do this from the dev/run_dev.Rscript now) it should look like this:"
},
{
"code": null,
"e": 12344,
"s": 12162,
"text": "That’s looking much better! Time to finish up the prototypes of our other two tabs. Remember, our exercise and muscle group tabs should look like this (according to our wireframes):"
},
{
"code": null,
"e": 12473,
"s": 12344,
"text": "Luckily, we can reuse a fair amount of our code from our dashboard page. So in R/mod_Exercises.R we will flesh out this demo UI!"
},
{
"code": null,
"e": 12486,
"s": 12473,
"text": "A few notes:"
},
{
"code": null,
"e": 12584,
"s": 12486,
"text": "We have hard-coded the choices in our input box for now, but we’ll fill this with our data later!"
},
{
"code": null,
"e": 12737,
"s": 12584,
"text": "You’ll notice we’re using boxes again, as well as a Shiny function to create a spot for our users to filter based on what exercise they want to look at."
},
{
"code": null,
"e": 13935,
"s": 12737,
"text": "mod_Exercises_ui <- function(id){ ns <- NS(id) tagList( fluidPage( fluidRow( h2(\"Exercise Progress for \"), selectizeInput( inputId = ns(\"exercises\"), label = \"\", # Hard coded for now, but we'll deal with this later! choices = c(\"Dumbell Bicep Curl\", \"Deadlift\"), selected = \"Dumbell Bicep Curl\", width = '50%', multiple = FALSE) ), fluidRow( column(width = 10, shinydashboard::box( background = \"blue\", h2(\"Your current projected 1 rep max is x!\"), title = \"Congrats!\") )), fluidRow( shinydashboard::box( title = \"Total Weight Per Workout\", width = 6, plotOutput(ns(\"plot2\"))), shinydashboard::box( title = \"Max Weight Per Workout\", width = 6, plotOutput(ns(\"plot3\")) ) ) ) )}mod_Exercises_server <- function(input, output, session){ ns <- session$ns output$plot2 <- renderPlot({ shinipsum::random_ggplot(type = \"line\") }) output$plot3 <- renderPlot({ shinipsum::random_ggplot(type = \"line\") })}"
},
{
"code": null,
"e": 14011,
"s": 13935,
"text": "Great! If you run your app, your ‘Exercises’ tab should now look like this:"
},
{
"code": null,
"e": 14186,
"s": 14011,
"text": "I bet you can guess what we’re going to do on the muscle groups tab! Try and do that one yourself based on what we’ve already written, but if you need help, my code is below."
},
{
"code": null,
"e": 14210,
"s": 14186,
"text": "In R/mod_MuscleGroup.R:"
},
{
"code": null,
"e": 15091,
"s": 14210,
"text": "mod_MuscleGroup_ui <- function(id){ ns <- NS(id) tagList( fluidPage( fluidRow( h2(\"Muscle Group Progress for \"), selectizeInput( inputId = ns(\"muscles\"), label = \"\", choices = c(\"Back\", \"Hamstrings\"), selected = \"Back\", width = '50%', multiple = FALSE) ), fluidRow( shinydashboard::box( title = \"Max Weight Over Time\", width = 6, plotOutput(ns(\"plot4\"))), shinydashboard::box( title = \"Top Exercises\", width = 6, DT::dataTableOutput(ns('data_table2')) ) ) ) )}mod_MuscleGroup_server <- function(input, output, session){ ns <- session$ns output$plot4 <- renderPlot({ shinipsum::random_ggplot(type = \"line\") }) output$data_table2 <- DT::renderDT({ shinipsum::random_DT(5, 3, \"numeric\") })}"
},
{
"code": null,
"e": 15131,
"s": 15091,
"text": "The final result should look like this:"
},
{
"code": null,
"e": 15717,
"s": 15131,
"text": "Now we have a fully functioning prototype ready to show our theoretical user (in this case, us)! We can make alterations based on our user’s feedback much more easily using prototyping graphs rather than dealing with all our data wrangling, and we can get a prototype to our user much more quickly when we don’t have to make the whole app work before they see anything. Once our user approves the final wireframe, we’ll be ready to build the rest of our Shiny app the normal way and we’re all set up to use automated testing and Docker-based deployments using the Golem infrastructure."
}
] |
Entity Framework - Asynchronous Query | Asynchronous programming involves executing operations in the background so that the main thread can continue its own operations. This way the main thread can keep the user interface responsive while the background thread is processing the task at hand.
Entity Framework 6.0 supports asynchronous operations for querying and saving of data.
Entity Framework 6.0 supports asynchronous operations for querying and saving of data.
Asynchronous operations can help your application in the following ways −
Make your application more responsive to user interactions
Improve the overall performance of your application
Asynchronous operations can help your application in the following ways −
Make your application more responsive to user interactions
Improve the overall performance of your application
You can execute asynchronous operations in various ways. But async/await keywords were introduced in .NET Framework 4.5 which makes your job simple.
You can execute asynchronous operations in various ways. But async/await keywords were introduced in .NET Framework 4.5 which makes your job simple.
The only thing you need to follow is the async/await pattern as illustrated by the following code fragment.
The only thing you need to follow is the async/await pattern as illustrated by the following code fragment.
Let’s take a look at the following example (without using async/await) in which DatabaseOperations method saves a new student to the database and then retrieves all students from the database and at the end some additional message is printed on the console.
class Program {
static void Main(string[] args) {
Console.WriteLine("Database Operations Started");
DatabaseOperations();
Console.WriteLine();
Console.WriteLine("Database Operations Completed");
Console.WriteLine();
Console.WriteLine("Entity Framework Tutorials");
Console.ReadKey();
}
public static void DatabaseOperations() {
using (var context = new UniContextEntities()) {
// Create a new student and save it
context.Students.Add(new Student {
FirstMidName = "Akram",
LastName = "Khan",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())});
Console.WriteLine("Calling SaveChanges.");
context.SaveChanges();
Console.WriteLine("SaveChanges completed.");
// Query for all Students ordered by first name
var students = (from s in context.Students
orderby s.FirstMidName select s).ToList();
// Write all students out to Console
Console.WriteLine();
Console.WriteLine("All Student:");
foreach (var student in students) {
string name = student.FirstMidName + " " + student.LastName;
Console.WriteLine(" " + name);
}
}
}
}
When the above code is executed, you will receive the following output −
Calling SaveChanges.
SaveChanges completed.
All Student:
Akram Khan
Ali Khan
Ali Alexander
Arturo Anand
Bill Gates
Gytis Barzdukas
Laura Nornan
Meredith fllonso
Nino Olioetto
Peggy Justice
Yan Li
Entity Framework Tutorials
Let’s use the new async and await keywords and make the following changes to Program.cs
Add System.Data.Entity namespace which will give EF async extension methods.
Add System.Data.Entity namespace which will give EF async extension methods.
Add System.Threading.Tasks namespace which will allow us to use the Task type.
Add System.Threading.Tasks namespace which will allow us to use the Task type.
Update DatabaseOperations to be marked as async and return a Task.
Update DatabaseOperations to be marked as async and return a Task.
Call the Async version of SaveChanges and await its completion.
Call the Async version of SaveChanges and await its completion.
Call the Async version of ToList and await the result.
Call the Async version of ToList and await the result.
class Program {
static void Main(string[] args) {
var task = DatabaseOperations();
Console.WriteLine();
Console.WriteLine("Entity Framework Tutorials");
task.Wait();
Console.ReadKey();
}
public static async Task DatabaseOperations() {
using (var context = new UniContextEntities()) {
// Create a new blog and save it
context.Students.Add(new Student {
FirstMidName = "Salman",
LastName = "Khan",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())});
Console.WriteLine("Calling SaveChanges.");
await context.SaveChangesAsync();
Console.WriteLine("SaveChanges completed.");
// Query for all Students ordered by first name
var students = await (from s in context.Students
orderby s.FirstMidName select s).ToListAsync();
// Write all students out to Console
Console.WriteLine();
Console.WriteLine("All Student:");
foreach (var student in students) {
string name = student.FirstMidName + " " + student.LastName;
Console.WriteLine(" " + name);
}
}
}
}
On execution, it will produce the following output.
Calling SaveChanges.
Entity Framework Tutorials
SaveChanges completed.
All Student:
Akram Khan
Ali Khan
Ali Alexander
Arturo Anand
Bill Gates
Gytis Barzdukas
Laura Nornan
Meredith fllonso
Nino Olioetto
Peggy Justice
Salman Khan
Yan Li
Now that the code is asynchronous, you can observe a different execution flow of your program.
SaveChanges begins to push the new Student to the database and then the DatabaseOperations method returns (even though it hasn't finished executing) and program flow in the Main method continues.
SaveChanges begins to push the new Student to the database and then the DatabaseOperations method returns (even though it hasn't finished executing) and program flow in the Main method continues.
Message is then written to the console.
Message is then written to the console.
The managed thread is blocked on the Wait call until the database operation completes. Once it completes, the remainder of our DatabaseOperations will be executed.
The managed thread is blocked on the Wait call until the database operation completes. Once it completes, the remainder of our DatabaseOperations will be executed.
SaveChanges completes.
SaveChanges completes.
Retrieved all the student from the database and is written to the Console.
Retrieved all the student from the database and is written to the Console.
We recommend that you execute the above example in a step-by-step manner for better understanding.
19 Lectures
5 hours
Trevoir Williams
33 Lectures
3.5 hours
Nilay Mehta
21 Lectures
2.5 hours
TELCOMA Global
89 Lectures
7.5 hours
Mustafa Radaideh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3286,
"s": 3032,
"text": "Asynchronous programming involves executing operations in the background so that the main thread can continue its own operations. This way the main thread can keep the user interface responsive while the background thread is processing the task at hand."
},
{
"code": null,
"e": 3373,
"s": 3286,
"text": "Entity Framework 6.0 supports asynchronous operations for querying and saving of data."
},
{
"code": null,
"e": 3460,
"s": 3373,
"text": "Entity Framework 6.0 supports asynchronous operations for querying and saving of data."
},
{
"code": null,
"e": 3648,
"s": 3460,
"text": "Asynchronous operations can help your application in the following ways −\n\nMake your application more responsive to user interactions\nImprove the overall performance of your application\n\n"
},
{
"code": null,
"e": 3722,
"s": 3648,
"text": "Asynchronous operations can help your application in the following ways −"
},
{
"code": null,
"e": 3781,
"s": 3722,
"text": "Make your application more responsive to user interactions"
},
{
"code": null,
"e": 3833,
"s": 3781,
"text": "Improve the overall performance of your application"
},
{
"code": null,
"e": 3982,
"s": 3833,
"text": "You can execute asynchronous operations in various ways. But async/await keywords were introduced in .NET Framework 4.5 which makes your job simple."
},
{
"code": null,
"e": 4131,
"s": 3982,
"text": "You can execute asynchronous operations in various ways. But async/await keywords were introduced in .NET Framework 4.5 which makes your job simple."
},
{
"code": null,
"e": 4239,
"s": 4131,
"text": "The only thing you need to follow is the async/await pattern as illustrated by the following code fragment."
},
{
"code": null,
"e": 4347,
"s": 4239,
"text": "The only thing you need to follow is the async/await pattern as illustrated by the following code fragment."
},
{
"code": null,
"e": 4605,
"s": 4347,
"text": "Let’s take a look at the following example (without using async/await) in which DatabaseOperations method saves a new student to the database and then retrieves all students from the database and at the end some additional message is printed on the console."
},
{
"code": null,
"e": 5897,
"s": 4605,
"text": "class Program {\n\n static void Main(string[] args) {\n Console.WriteLine(\"Database Operations Started\");\n DatabaseOperations();\n\t\t\n Console.WriteLine();\n Console.WriteLine(\"Database Operations Completed\");\n Console.WriteLine();\n Console.WriteLine(\"Entity Framework Tutorials\");\n\t\t\n Console.ReadKey();\n }\n\n public static void DatabaseOperations() {\n\n using (var context = new UniContextEntities()) {\n\n // Create a new student and save it\n\n context.Students.Add(new Student {\n FirstMidName = \"Akram\", \n LastName = \"Khan\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())});\n\n Console.WriteLine(\"Calling SaveChanges.\");\n context.SaveChanges();\n Console.WriteLine(\"SaveChanges completed.\");\n\n // Query for all Students ordered by first name\n\n var students = (from s in context.Students\n orderby s.FirstMidName select s).ToList();\n\n // Write all students out to Console\n\n Console.WriteLine();\n Console.WriteLine(\"All Student:\");\n\n foreach (var student in students) {\n string name = student.FirstMidName + \" \" + student.LastName;\n Console.WriteLine(\" \" + name);\n }\n }\n }\n}"
},
{
"code": null,
"e": 5970,
"s": 5897,
"text": "When the above code is executed, you will receive the following output −"
},
{
"code": null,
"e": 6196,
"s": 5970,
"text": "Calling SaveChanges.\nSaveChanges completed.\nAll Student:\nAkram Khan\nAli Khan\nAli Alexander\nArturo Anand\nBill Gates\nGytis Barzdukas\nLaura Nornan\nMeredith fllonso\nNino Olioetto\nPeggy Justice\nYan Li\n\nEntity Framework Tutorials\n"
},
{
"code": null,
"e": 6284,
"s": 6196,
"text": "Let’s use the new async and await keywords and make the following changes to Program.cs"
},
{
"code": null,
"e": 6361,
"s": 6284,
"text": "Add System.Data.Entity namespace which will give EF async extension methods."
},
{
"code": null,
"e": 6438,
"s": 6361,
"text": "Add System.Data.Entity namespace which will give EF async extension methods."
},
{
"code": null,
"e": 6517,
"s": 6438,
"text": "Add System.Threading.Tasks namespace which will allow us to use the Task type."
},
{
"code": null,
"e": 6596,
"s": 6517,
"text": "Add System.Threading.Tasks namespace which will allow us to use the Task type."
},
{
"code": null,
"e": 6663,
"s": 6596,
"text": "Update DatabaseOperations to be marked as async and return a Task."
},
{
"code": null,
"e": 6730,
"s": 6663,
"text": "Update DatabaseOperations to be marked as async and return a Task."
},
{
"code": null,
"e": 6794,
"s": 6730,
"text": "Call the Async version of SaveChanges and await its completion."
},
{
"code": null,
"e": 6858,
"s": 6794,
"text": "Call the Async version of SaveChanges and await its completion."
},
{
"code": null,
"e": 6913,
"s": 6858,
"text": "Call the Async version of ToList and await the result."
},
{
"code": null,
"e": 6968,
"s": 6913,
"text": "Call the Async version of ToList and await the result."
},
{
"code": null,
"e": 8171,
"s": 6968,
"text": "class Program {\n\n static void Main(string[] args) {\n var task = DatabaseOperations();\n Console.WriteLine();\n Console.WriteLine(\"Entity Framework Tutorials\");\n task.Wait();\n Console.ReadKey();\n }\n\n public static async Task DatabaseOperations() {\n\n using (var context = new UniContextEntities()) {\n\n // Create a new blog and save it\n\n context.Students.Add(new Student {\n FirstMidName = \"Salman\", \n LastName = \"Khan\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())});\n\n Console.WriteLine(\"Calling SaveChanges.\");\n await context.SaveChangesAsync();\n Console.WriteLine(\"SaveChanges completed.\");\n\n // Query for all Students ordered by first name\n\n var students = await (from s in context.Students \n orderby s.FirstMidName select s).ToListAsync();\n\n // Write all students out to Console\n\n Console.WriteLine();\n Console.WriteLine(\"All Student:\");\n\n foreach (var student in students) {\n string name = student.FirstMidName + \" \" + student.LastName; \n Console.WriteLine(\" \" + name);\n }\n }\n }\n}"
},
{
"code": null,
"e": 8223,
"s": 8171,
"text": "On execution, it will produce the following output."
},
{
"code": null,
"e": 8460,
"s": 8223,
"text": "Calling SaveChanges.\nEntity Framework Tutorials\nSaveChanges completed.\nAll Student:\nAkram Khan\nAli Khan\nAli Alexander\nArturo Anand\nBill Gates\nGytis Barzdukas\nLaura Nornan\nMeredith fllonso\nNino Olioetto\nPeggy Justice\nSalman Khan\nYan Li\n"
},
{
"code": null,
"e": 8555,
"s": 8460,
"text": "Now that the code is asynchronous, you can observe a different execution flow of your program."
},
{
"code": null,
"e": 8751,
"s": 8555,
"text": "SaveChanges begins to push the new Student to the database and then the DatabaseOperations method returns (even though it hasn't finished executing) and program flow in the Main method continues."
},
{
"code": null,
"e": 8947,
"s": 8751,
"text": "SaveChanges begins to push the new Student to the database and then the DatabaseOperations method returns (even though it hasn't finished executing) and program flow in the Main method continues."
},
{
"code": null,
"e": 8987,
"s": 8947,
"text": "Message is then written to the console."
},
{
"code": null,
"e": 9027,
"s": 8987,
"text": "Message is then written to the console."
},
{
"code": null,
"e": 9191,
"s": 9027,
"text": "The managed thread is blocked on the Wait call until the database operation completes. Once it completes, the remainder of our DatabaseOperations will be executed."
},
{
"code": null,
"e": 9355,
"s": 9191,
"text": "The managed thread is blocked on the Wait call until the database operation completes. Once it completes, the remainder of our DatabaseOperations will be executed."
},
{
"code": null,
"e": 9378,
"s": 9355,
"text": "SaveChanges completes."
},
{
"code": null,
"e": 9401,
"s": 9378,
"text": "SaveChanges completes."
},
{
"code": null,
"e": 9476,
"s": 9401,
"text": "Retrieved all the student from the database and is written to the Console."
},
{
"code": null,
"e": 9551,
"s": 9476,
"text": "Retrieved all the student from the database and is written to the Console."
},
{
"code": null,
"e": 9650,
"s": 9551,
"text": "We recommend that you execute the above example in a step-by-step manner for better understanding."
},
{
"code": null,
"e": 9683,
"s": 9650,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9701,
"s": 9683,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 9736,
"s": 9701,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9749,
"s": 9736,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 9784,
"s": 9749,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9800,
"s": 9784,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 9835,
"s": 9800,
"text": "\n 89 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9853,
"s": 9835,
"text": " Mustafa Radaideh"
},
{
"code": null,
"e": 9860,
"s": 9853,
"text": " Print"
},
{
"code": null,
"e": 9871,
"s": 9860,
"text": " Add Notes"
}
] |
MariaDB - Select Database | After connecting to MariaDB, you must select a database to work with because many databases may exist. There are two ways to perform this task: from the command prompt or through a PHP script.
In choosing a database at the command prompt, simply utilize the SQL command ‘use’ −
[root@host]# mysql -u root -p
Enter password:******
mysql> use PRODUCTS;
Database changed
mysql> SELECT database();
+-------------------------+
| Database |
+-------------------------+
| PRODUCTS |
+-------------------------+
Once you select a database, all subsequent commands will operate on the chosen database.
Note − All names (e.g., database, table, fields) are case sensitive. Ensure commands conform to the proper case.
PHP provides the mysql_select_db function for database selection. The function uses two parameters, one optional, and returns a value of “true” on successful selection, or false on failure.
Review the following select database script syntax.
bool mysql_select_db( db_name, connection );
The description of the parameters is given below −
db_name
This required parameter specifies the name of the database to use.
connection
When not specified, this optional parameter uses the most recent connection used.
Try the following example code for selecting a database −
<html>
<head>
<title>Select a MariaDB Database</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest1';
$dbpass = 'guest1a';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'PRODUCTS' );
mysql_close($conn);
?>
</body>
</html>
On successful selection, you will see the following output −
mysql> Connected successfully
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2555,
"s": 2362,
"text": "After connecting to MariaDB, you must select a database to work with because many databases may exist. There are two ways to perform this task: from the command prompt or through a PHP script."
},
{
"code": null,
"e": 2640,
"s": 2555,
"text": "In choosing a database at the command prompt, simply utilize the SQL command ‘use’ −"
},
{
"code": null,
"e": 2908,
"s": 2640,
"text": "[root@host]# mysql -u root -p\n\nEnter password:******\n\nmysql> use PRODUCTS;\n\nDatabase changed\n\nmysql> SELECT database(); \n+-------------------------+ \n| Database | \n+-------------------------+ \n| PRODUCTS | \n+-------------------------+ \n"
},
{
"code": null,
"e": 2997,
"s": 2908,
"text": "Once you select a database, all subsequent commands will operate on the chosen database."
},
{
"code": null,
"e": 3110,
"s": 2997,
"text": "Note − All names (e.g., database, table, fields) are case sensitive. Ensure commands conform to the proper case."
},
{
"code": null,
"e": 3300,
"s": 3110,
"text": "PHP provides the mysql_select_db function for database selection. The function uses two parameters, one optional, and returns a value of “true” on successful selection, or false on failure."
},
{
"code": null,
"e": 3352,
"s": 3300,
"text": "Review the following select database script syntax."
},
{
"code": null,
"e": 3398,
"s": 3352,
"text": "bool mysql_select_db( db_name, connection );\n"
},
{
"code": null,
"e": 3449,
"s": 3398,
"text": "The description of the parameters is given below −"
},
{
"code": null,
"e": 3457,
"s": 3449,
"text": "db_name"
},
{
"code": null,
"e": 3524,
"s": 3457,
"text": "This required parameter specifies the name of the database to use."
},
{
"code": null,
"e": 3535,
"s": 3524,
"text": "connection"
},
{
"code": null,
"e": 3617,
"s": 3535,
"text": "When not specified, this optional parameter uses the most recent connection used."
},
{
"code": null,
"e": 3675,
"s": 3617,
"text": "Try the following example code for selecting a database −"
},
{
"code": null,
"e": 4173,
"s": 3675,
"text": "<html>\n <head>\n <title>Select a MariaDB Database</title>\n </head>\n\n <body>\n <?php\n $dbhost = 'localhost:3036';\n $dbuser = 'guest1';\n $dbpass = 'guest1a';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n echo 'Connected successfully';\n \n mysql_select_db( 'PRODUCTS' );\n mysql_close($conn);\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 4234,
"s": 4173,
"text": "On successful selection, you will see the following output −"
},
{
"code": null,
"e": 4266,
"s": 4234,
"text": "mysql> Connected successfully \n"
},
{
"code": null,
"e": 4273,
"s": 4266,
"text": " Print"
},
{
"code": null,
"e": 4284,
"s": 4273,
"text": " Add Notes"
}
] |
Nth Digit in C++ | Suppose we have one infinite integer sequence, we have to find the nth digit of this sequence. So if the input is 11, then the output will be 0 as if we place the numbers like 123456789101112, so the 11th digit is 0.
To solve this, we will follow these steps −
len := 0 and cnt := 9 and start := 1
len := 0 and cnt := 9 and start := 1
while n > len * cntn := n – (len * cnt)cnt := cnt * 10, start := start * 10increase len by 1
while n > len * cnt
n := n – (len * cnt)
n := n – (len * cnt)
cnt := cnt * 10, start := start * 10
cnt := cnt * 10, start := start * 10
increase len by 1
increase len by 1
start := start +(n - 1) / len
start := start +(n - 1) / len
s := start as string
s := start as string
return s[(n – 1) mod len]
return s[(n – 1) mod len]
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
int findNthDigit(int n) {
lli len = 1;
lli cnt = 9;
lli start = 1;
while(n > len * cnt){
n -= len * cnt;
cnt *= 10;
start *= 10;
len++;
}
start += (n - 1) / len;
string s = to_string(start);
return s[(n - 1) % len] - '0';
}
};
main(){
Solution ob;
cout << (ob.findNthDigit(11));
}
11
0 | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "Suppose we have one infinite integer sequence, we have to find the nth digit of this sequence. So if the input is 11, then the output will be 0 as if we place the numbers like 123456789101112, so the 11th digit is 0."
},
{
"code": null,
"e": 1323,
"s": 1279,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1360,
"s": 1323,
"text": "len := 0 and cnt := 9 and start := 1"
},
{
"code": null,
"e": 1397,
"s": 1360,
"text": "len := 0 and cnt := 9 and start := 1"
},
{
"code": null,
"e": 1490,
"s": 1397,
"text": "while n > len * cntn := n – (len * cnt)cnt := cnt * 10, start := start * 10increase len by 1"
},
{
"code": null,
"e": 1510,
"s": 1490,
"text": "while n > len * cnt"
},
{
"code": null,
"e": 1531,
"s": 1510,
"text": "n := n – (len * cnt)"
},
{
"code": null,
"e": 1552,
"s": 1531,
"text": "n := n – (len * cnt)"
},
{
"code": null,
"e": 1589,
"s": 1552,
"text": "cnt := cnt * 10, start := start * 10"
},
{
"code": null,
"e": 1626,
"s": 1589,
"text": "cnt := cnt * 10, start := start * 10"
},
{
"code": null,
"e": 1644,
"s": 1626,
"text": "increase len by 1"
},
{
"code": null,
"e": 1662,
"s": 1644,
"text": "increase len by 1"
},
{
"code": null,
"e": 1692,
"s": 1662,
"text": "start := start +(n - 1) / len"
},
{
"code": null,
"e": 1722,
"s": 1692,
"text": "start := start +(n - 1) / len"
},
{
"code": null,
"e": 1743,
"s": 1722,
"text": "s := start as string"
},
{
"code": null,
"e": 1764,
"s": 1743,
"text": "s := start as string"
},
{
"code": null,
"e": 1790,
"s": 1764,
"text": "return s[(n – 1) mod len]"
},
{
"code": null,
"e": 1816,
"s": 1790,
"text": "return s[(n – 1) mod len]"
},
{
"code": null,
"e": 1888,
"s": 1816,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1899,
"s": 1888,
"text": " Live Demo"
},
{
"code": null,
"e": 2374,
"s": 1899,
"text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\npublic:\n int findNthDigit(int n) {\n lli len = 1;\n lli cnt = 9;\n lli start = 1;\n while(n > len * cnt){\n n -= len * cnt;\n cnt *= 10;\n start *= 10;\n len++;\n }\n start += (n - 1) / len;\n string s = to_string(start);\n return s[(n - 1) % len] - '0';\n }\n};\nmain(){\n Solution ob;\n cout << (ob.findNthDigit(11));\n}"
},
{
"code": null,
"e": 2377,
"s": 2374,
"text": "11"
},
{
"code": null,
"e": 2379,
"s": 2377,
"text": "0"
}
] |
Notebook widget in Tkinter | Notebook widget is an inbuilt widget of ttk library in tkinter. It enables the user to create Tabs in the window application. Tabs are generally used to separate the workspace and specialize the group of operations in applications at the same time.
In this example, we will create two tabs using Notebook widget and then will add some context to it.
#Import the required library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
win.geometry("750x250")
#Create a Notebook widget
my_notebook= ttk.Notebook(win)
my_notebook.pack(expand=1,fill=BOTH)
#Create Tabs
tab1= ttk.Frame(my_notebook)
my_notebook.add(tab1, text= "Tab 1")
tab2= ttk.Frame(my_notebook)
my_notebook.add(tab2, text= "Tab2")
#Create a Label in Tabs
Label(tab1, text= "Hello, Howdy?", font= ('Helvetica 20 bold')).pack()
Label(tab2, text= "This is a New Tab Context", font=('Helvetica
20 bold')).pack()
win.mainloop()
Running the above code will display a window containing two tabs, tab1 and tab2 respectively. Tabs contain some Text Labels in it.
Now, switch to "tab1" and then "tab2" to see the changes between the two tabs. | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "Notebook widget is an inbuilt widget of ttk library in tkinter. It enables the user to create Tabs in the window application. Tabs are generally used to separate the workspace and specialize the group of operations in applications at the same time."
},
{
"code": null,
"e": 1412,
"s": 1311,
"text": "In this example, we will create two tabs using Notebook widget and then will add some context to it."
},
{
"code": null,
"e": 1989,
"s": 1412,
"text": "#Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame\nwin = Tk()\nwin.geometry(\"750x250\")\n#Create a Notebook widget\nmy_notebook= ttk.Notebook(win)\nmy_notebook.pack(expand=1,fill=BOTH)\n#Create Tabs\ntab1= ttk.Frame(my_notebook)\nmy_notebook.add(tab1, text= \"Tab 1\")\ntab2= ttk.Frame(my_notebook)\nmy_notebook.add(tab2, text= \"Tab2\")\n#Create a Label in Tabs\nLabel(tab1, text= \"Hello, Howdy?\", font= ('Helvetica 20 bold')).pack()\nLabel(tab2, text= \"This is a New Tab Context\", font=('Helvetica\n20 bold')).pack()\nwin.mainloop()"
},
{
"code": null,
"e": 2120,
"s": 1989,
"text": "Running the above code will display a window containing two tabs, tab1 and tab2 respectively. Tabs contain some Text Labels in it."
},
{
"code": null,
"e": 2199,
"s": 2120,
"text": "Now, switch to \"tab1\" and then \"tab2\" to see the changes between the two tabs."
}
] |
String compareTo() Method | Returns a new string by removing all leading and trailing spaces. However, this method doesn’t discard spaces between two strings.
compareTo(String other)
Returns an integer representing the relationship between two strings.
0 − when the strings are equal.
0 − when the strings are equal.
1 − when the first string is greater than the second
1 − when the first string is greater than the second
-1 − when the first string is smaller than the second
-1 − when the first string is smaller than the second
void main() {
String str1 = "A";
String str2 = "A";
String str3 = "B";
print("str1.compareTo(str2): ${str1.compareTo(str2)}");
print("str1.compareTo(str3): ${str1.compareTo(str3)}");
print("str3.compareTo(str2): ${str3.compareTo(str2)}");
}
It will produce the following output −.
str1.compareTo(str2): 0
str1.compareTo(str3): -1
str3.compareTo(str2): 1
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2656,
"s": 2525,
"text": "Returns a new string by removing all leading and trailing spaces. However, this method doesn’t discard spaces between two strings."
},
{
"code": null,
"e": 2681,
"s": 2656,
"text": "compareTo(String other)\n"
},
{
"code": null,
"e": 2751,
"s": 2681,
"text": "Returns an integer representing the relationship between two strings."
},
{
"code": null,
"e": 2783,
"s": 2751,
"text": "0 − when the strings are equal."
},
{
"code": null,
"e": 2815,
"s": 2783,
"text": "0 − when the strings are equal."
},
{
"code": null,
"e": 2868,
"s": 2815,
"text": "1 − when the first string is greater than the second"
},
{
"code": null,
"e": 2921,
"s": 2868,
"text": "1 − when the first string is greater than the second"
},
{
"code": null,
"e": 2975,
"s": 2921,
"text": "-1 − when the first string is smaller than the second"
},
{
"code": null,
"e": 3029,
"s": 2975,
"text": "-1 − when the first string is smaller than the second"
},
{
"code": null,
"e": 3300,
"s": 3029,
"text": "void main() { \n String str1 = \"A\"; \n String str2 = \"A\"; \n String str3 = \"B\"; \n \n print(\"str1.compareTo(str2): ${str1.compareTo(str2)}\"); \n print(\"str1.compareTo(str3): ${str1.compareTo(str3)}\"); \n print(\"str3.compareTo(str2): ${str3.compareTo(str2)}\"); \n} "
},
{
"code": null,
"e": 3340,
"s": 3300,
"text": "It will produce the following output −."
},
{
"code": null,
"e": 3417,
"s": 3340,
"text": "str1.compareTo(str2): 0 \nstr1.compareTo(str3): -1 \nstr3.compareTo(str2): 1 \n"
},
{
"code": null,
"e": 3452,
"s": 3417,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3472,
"s": 3452,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3505,
"s": 3472,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3525,
"s": 3505,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3558,
"s": 3525,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3575,
"s": 3558,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3610,
"s": 3575,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3627,
"s": 3610,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3662,
"s": 3627,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3682,
"s": 3662,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3715,
"s": 3682,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3735,
"s": 3715,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3742,
"s": 3735,
"text": " Print"
},
{
"code": null,
"e": 3753,
"s": 3742,
"text": " Add Notes"
}
] |
C - if statement | An if statement consists of a Boolean expression followed by one or more statements.
The syntax of an 'if' statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is either zero or null, then it is assumed as false value.
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result −
a is less than 20;
value of a is : 10
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2169,
"s": 2084,
"text": "An if statement consists of a Boolean expression followed by one or more statements."
},
{
"code": null,
"e": 2232,
"s": 2169,
"text": "The syntax of an 'if' statement in C programming language is −"
},
{
"code": null,
"e": 2329,
"s": 2232,
"text": "if(boolean_expression) {\n /* statement(s) will execute if the boolean expression is true */\n}\n"
},
{
"code": null,
"e": 2601,
"s": 2329,
"text": "If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed."
},
{
"code": null,
"e": 2742,
"s": 2601,
"text": "C programming language assumes any non-zero and non-null values as true and if it is either zero or null, then it is assumed as false value."
},
{
"code": null,
"e": 3066,
"s": 2742,
"text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 10;\n \n /* check the boolean condition using if statement */\n\t\n if( a < 20 ) {\n /* if condition is true then print the following */\n printf(\"a is less than 20\\n\" );\n }\n \n printf(\"value of a is : %d\\n\", a);\n \n return 0;\n}"
},
{
"code": null,
"e": 3147,
"s": 3066,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3186,
"s": 3147,
"text": "a is less than 20;\nvalue of a is : 10\n"
},
{
"code": null,
"e": 3193,
"s": 3186,
"text": " Print"
},
{
"code": null,
"e": 3204,
"s": 3193,
"text": " Add Notes"
}
] |
Like Operator in SAS Programming - GeeksforGeeks | 23 Jul, 2019
LIKE Operator: Pattern Matching
The LIKE operator used to select data by comparing the values of a character variable to a specified pattern. It is case sensitive.
Task 1: To select all students with a name that starts with the letter S.
There are two special characters patterns available for specifying a pattern:
percent sign (%) – Wildcard Character
percent sign (%) – Wildcard Character
underscore ( _ ) – Fill in the blanks
underscore ( _ ) – Fill in the blanks
data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya . 45Sandy A 67David B 39Rahul . 95Sahil C 84Savitri B 65;run; data readin1;set readin;where name like 'S%';run;
Output:
In a given dataset, the above statements would produce the same result in both cases.
Examples:
where name like '%ul';Output:It contains all the data where the name ends with ‘ul’.where name like '_ah%';Output:It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place.where name like '_a___';Output:It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place.
where name like '%ul';Output:It contains all the data where the name ends with ‘ul’.
where name like '%ul';
Output:
It contains all the data where the name ends with ‘ul’.
where name like '_ah%';Output:It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place.
where name like '_ah%';
Output:
It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place.
where name like '_a___';Output:It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place.
where name like '_a___';
Output:
It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place.
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
All forms of formatted scanf() in C
Difference Between Imperative and Declarative Programming
Difference between while and do-while loop in C, C++, Java
Top 10 Programming Languages to Learn in 2022
Prolog | An Introduction
Header Guard in C++
Lists in Prolog
Scope of Variable in R
DataFrame Operations in R
Top 10 Fastest Programming Languages | [
{
"code": null,
"e": 23717,
"s": 23689,
"text": "\n23 Jul, 2019"
},
{
"code": null,
"e": 23749,
"s": 23717,
"text": "LIKE Operator: Pattern Matching"
},
{
"code": null,
"e": 23881,
"s": 23749,
"text": "The LIKE operator used to select data by comparing the values of a character variable to a specified pattern. It is case sensitive."
},
{
"code": null,
"e": 23955,
"s": 23881,
"text": "Task 1: To select all students with a name that starts with the letter S."
},
{
"code": null,
"e": 24033,
"s": 23955,
"text": "There are two special characters patterns available for specifying a pattern:"
},
{
"code": null,
"e": 24071,
"s": 24033,
"text": "percent sign (%) – Wildcard Character"
},
{
"code": null,
"e": 24109,
"s": 24071,
"text": "percent sign (%) – Wildcard Character"
},
{
"code": null,
"e": 24147,
"s": 24109,
"text": "underscore ( _ ) – Fill in the blanks"
},
{
"code": null,
"e": 24185,
"s": 24147,
"text": "underscore ( _ ) – Fill in the blanks"
},
{
"code": "data readin;input name $ Section $ Score;cards;Raj A 80Atul . 77Priya . 45Sandy A 67David B 39Rahul . 95Sahil C 84Savitri B 65;run; data readin1;set readin;where name like 'S%';run;",
"e": 24369,
"s": 24185,
"text": null
},
{
"code": null,
"e": 24377,
"s": 24369,
"text": "Output:"
},
{
"code": null,
"e": 24463,
"s": 24377,
"text": "In a given dataset, the above statements would produce the same result in both cases."
},
{
"code": null,
"e": 24473,
"s": 24463,
"text": "Examples:"
},
{
"code": null,
"e": 24840,
"s": 24473,
"text": "where name like '%ul';Output:It contains all the data where the name ends with ‘ul’.where name like '_ah%';Output:It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place.where name like '_a___';Output:It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place."
},
{
"code": null,
"e": 24925,
"s": 24840,
"text": "where name like '%ul';Output:It contains all the data where the name ends with ‘ul’."
},
{
"code": null,
"e": 24948,
"s": 24925,
"text": "where name like '%ul';"
},
{
"code": null,
"e": 24956,
"s": 24948,
"text": "Output:"
},
{
"code": null,
"e": 25012,
"s": 24956,
"text": "It contains all the data where the name ends with ‘ul’."
},
{
"code": null,
"e": 25154,
"s": 25012,
"text": "where name like '_ah%';Output:It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place."
},
{
"code": null,
"e": 25178,
"s": 25154,
"text": "where name like '_ah%';"
},
{
"code": null,
"e": 25186,
"s": 25178,
"text": "Output:"
},
{
"code": null,
"e": 25298,
"s": 25186,
"text": "It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place."
},
{
"code": null,
"e": 25440,
"s": 25298,
"text": "where name like '_a___';Output:It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place."
},
{
"code": null,
"e": 25465,
"s": 25440,
"text": "where name like '_a___';"
},
{
"code": null,
"e": 25473,
"s": 25465,
"text": "Output:"
},
{
"code": null,
"e": 25584,
"s": 25473,
"text": "It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place."
},
{
"code": null,
"e": 25600,
"s": 25584,
"text": "SAS Programming"
},
{
"code": null,
"e": 25621,
"s": 25600,
"text": "Programming Language"
},
{
"code": null,
"e": 25719,
"s": 25621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25728,
"s": 25719,
"text": "Comments"
},
{
"code": null,
"e": 25741,
"s": 25728,
"text": "Old Comments"
},
{
"code": null,
"e": 25777,
"s": 25741,
"text": "All forms of formatted scanf() in C"
},
{
"code": null,
"e": 25835,
"s": 25777,
"text": "Difference Between Imperative and Declarative Programming"
},
{
"code": null,
"e": 25894,
"s": 25835,
"text": "Difference between while and do-while loop in C, C++, Java"
},
{
"code": null,
"e": 25940,
"s": 25894,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 25965,
"s": 25940,
"text": "Prolog | An Introduction"
},
{
"code": null,
"e": 25985,
"s": 25965,
"text": "Header Guard in C++"
},
{
"code": null,
"e": 26001,
"s": 25985,
"text": "Lists in Prolog"
},
{
"code": null,
"e": 26024,
"s": 26001,
"text": "Scope of Variable in R"
},
{
"code": null,
"e": 26050,
"s": 26024,
"text": "DataFrame Operations in R"
}
] |
Check if left and right shift of any string results into given string - GeeksforGeeks | 01 Sep, 2021
Given string S consisting of only lowercase English letters. The task is to find if there exists any string which has left shift and right shift both equal to string S. If there exists any string then print Yes, otherwise print No.
Examples:
Input: S = “abcd” Output: No Explanation: There is no string which have left shift and right shift both equal to string “abcd”.
Input: papa Output: Yes Explanation: The left shift and right shift both of string “apap” equals to string “papa”.
Approach:
The main target is to check the left shift and right shift both of any string equals to given string or not.For that we just have to check every character of given string is equal to its next to next character or not (i.e. character at (i)th position must be equal to character at (i+2)th position ).If it’s true for every position on the given stringm then we can say there exist any string whose left shift and right shift equal to given string otherwise not.
The main target is to check the left shift and right shift both of any string equals to given string or not.
For that we just have to check every character of given string is equal to its next to next character or not (i.e. character at (i)th position must be equal to character at (i+2)th position ).
If it’s true for every position on the given stringm then we can say there exist any string whose left shift and right shift equal to given string otherwise not.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if left// and right shift of any string// results into the given string #include <bits/stdc++.h>using namespace std; // Function to check string exist// or not as per above approachvoid check_string_exist(string S){ int size = S.length(); bool check = true; for (int i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S[i] != S[(i + 2) % size]) { check = false; break; } } if (check) cout << "Yes" << endl; else cout << "No" << endl;} // Driver codeint main(){ string S = "papa"; check_string_exist(S); return 0;}
// Java program to check if left// and right shift of any string// results into the given stringclass GFG{ // Function to check string exist// or not as per above approachpublic static void check_string_exist(String S){ int size = S.length(); boolean check = true; for(int i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S.charAt(i) != S.charAt((i + 2) % size)) { check = false; break; } } if (check) System.out.println("Yes"); else System.out.println("No");} // Driver Codepublic static void main(String[] args){ String S = "papa"; check_string_exist(S);}} // This code is contributed by divyeshrabadiya07
# Python3 program to check if left# and right shift of any string# results into the given string # Function to check string exist# or not as per above approachdef check_string_exist(S): size = len(S) check = True for i in range(size): # Check if any character # at position i and i+2 # are not equal, then # string doesnot exist if S[i] != S[(i + 2) % size]: check = False break if check : print("Yes") else: print("No") # Driver CodeS = "papa" check_string_exist(S) # This code is contributed by divyeshrabadiya07
// C# program to check if left// and right shift of any string// results into the given stringusing System; class GFG{ // Function to check string exist// or not as per above approachpublic static void check_string_exist(String S){ int size = S.Length; bool check = true; for(int i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S[i] != S[(i + 2) % size]) { check = false; break; } } if (check) Console.WriteLine("Yes"); else Console.WriteLine("No");} // Driver Codepublic static void Main(String[] args){ String S = "papa"; check_string_exist(S);}} // This code is contributed by sapnasingh4991
<script> // Javascript program to check if left// and right shift of any string// results into the given string // Function to check string exist// or not as per above approachfunction check_string_exist(S){ var size = S.length; var check = true; for (var i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S[i] != S[(i + 2) % size]) { check = false; break; } } if (check) document.write( "Yes" ); else document.write( "No" );} // Driver codevar S = "papa";check_string_exist(S); // This code is contributed by noob2000.</script>
Yes
Time Complexity: O(N) where N is the size of the string S.Auxiliary Space Complexity: O(1)
divyeshrabadiya07
sapnasingh4991
noob2000
anikakapoor
Bit Magic
Competitive Programming
Pattern Searching
Strings
Strings
Bit Magic
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Bits manipulation (Important tactics)
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Bits manipulation (Important tactics)
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 25438,
"s": 25410,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 25670,
"s": 25438,
"text": "Given string S consisting of only lowercase English letters. The task is to find if there exists any string which has left shift and right shift both equal to string S. If there exists any string then print Yes, otherwise print No."
},
{
"code": null,
"e": 25681,
"s": 25670,
"text": "Examples: "
},
{
"code": null,
"e": 25809,
"s": 25681,
"text": "Input: S = “abcd” Output: No Explanation: There is no string which have left shift and right shift both equal to string “abcd”."
},
{
"code": null,
"e": 25926,
"s": 25809,
"text": "Input: papa Output: Yes Explanation: The left shift and right shift both of string “apap” equals to string “papa”. "
},
{
"code": null,
"e": 25937,
"s": 25926,
"text": "Approach: "
},
{
"code": null,
"e": 26399,
"s": 25937,
"text": "The main target is to check the left shift and right shift both of any string equals to given string or not.For that we just have to check every character of given string is equal to its next to next character or not (i.e. character at (i)th position must be equal to character at (i+2)th position ).If it’s true for every position on the given stringm then we can say there exist any string whose left shift and right shift equal to given string otherwise not."
},
{
"code": null,
"e": 26508,
"s": 26399,
"text": "The main target is to check the left shift and right shift both of any string equals to given string or not."
},
{
"code": null,
"e": 26701,
"s": 26508,
"text": "For that we just have to check every character of given string is equal to its next to next character or not (i.e. character at (i)th position must be equal to character at (i+2)th position )."
},
{
"code": null,
"e": 26863,
"s": 26701,
"text": "If it’s true for every position on the given stringm then we can say there exist any string whose left shift and right shift equal to given string otherwise not."
},
{
"code": null,
"e": 26915,
"s": 26863,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26919,
"s": 26915,
"text": "C++"
},
{
"code": null,
"e": 26924,
"s": 26919,
"text": "Java"
},
{
"code": null,
"e": 26932,
"s": 26924,
"text": "Python3"
},
{
"code": null,
"e": 26935,
"s": 26932,
"text": "C#"
},
{
"code": null,
"e": 26946,
"s": 26935,
"text": "Javascript"
},
{
"code": "// C++ program to check if left// and right shift of any string// results into the given string #include <bits/stdc++.h>using namespace std; // Function to check string exist// or not as per above approachvoid check_string_exist(string S){ int size = S.length(); bool check = true; for (int i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S[i] != S[(i + 2) % size]) { check = false; break; } } if (check) cout << \"Yes\" << endl; else cout << \"No\" << endl;} // Driver codeint main(){ string S = \"papa\"; check_string_exist(S); return 0;}",
"e": 27669,
"s": 26946,
"text": null
},
{
"code": "// Java program to check if left// and right shift of any string// results into the given stringclass GFG{ // Function to check string exist// or not as per above approachpublic static void check_string_exist(String S){ int size = S.length(); boolean check = true; for(int i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S.charAt(i) != S.charAt((i + 2) % size)) { check = false; break; } } if (check) System.out.println(\"Yes\"); else System.out.println(\"No\");} // Driver Codepublic static void main(String[] args){ String S = \"papa\"; check_string_exist(S);}} // This code is contributed by divyeshrabadiya07",
"e": 28483,
"s": 27669,
"text": null
},
{
"code": "# Python3 program to check if left# and right shift of any string# results into the given string # Function to check string exist# or not as per above approachdef check_string_exist(S): size = len(S) check = True for i in range(size): # Check if any character # at position i and i+2 # are not equal, then # string doesnot exist if S[i] != S[(i + 2) % size]: check = False break if check : print(\"Yes\") else: print(\"No\") # Driver CodeS = \"papa\" check_string_exist(S) # This code is contributed by divyeshrabadiya07",
"e": 29113,
"s": 28483,
"text": null
},
{
"code": "// C# program to check if left// and right shift of any string// results into the given stringusing System; class GFG{ // Function to check string exist// or not as per above approachpublic static void check_string_exist(String S){ int size = S.Length; bool check = true; for(int i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S[i] != S[(i + 2) % size]) { check = false; break; } } if (check) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");} // Driver Codepublic static void Main(String[] args){ String S = \"papa\"; check_string_exist(S);}} // This code is contributed by sapnasingh4991",
"e": 29911,
"s": 29113,
"text": null
},
{
"code": "<script> // Javascript program to check if left// and right shift of any string// results into the given string // Function to check string exist// or not as per above approachfunction check_string_exist(S){ var size = S.length; var check = true; for (var i = 0; i < size; i++) { // Check if any character // at position i and i+2 // are not equal // then string doesnot exist if (S[i] != S[(i + 2) % size]) { check = false; break; } } if (check) document.write( \"Yes\" ); else document.write( \"No\" );} // Driver codevar S = \"papa\";check_string_exist(S); // This code is contributed by noob2000.</script>",
"e": 30615,
"s": 29911,
"text": null
},
{
"code": null,
"e": 30619,
"s": 30615,
"text": "Yes"
},
{
"code": null,
"e": 30713,
"s": 30621,
"text": "Time Complexity: O(N) where N is the size of the string S.Auxiliary Space Complexity: O(1) "
},
{
"code": null,
"e": 30731,
"s": 30713,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 30746,
"s": 30731,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 30755,
"s": 30746,
"text": "noob2000"
},
{
"code": null,
"e": 30767,
"s": 30755,
"text": "anikakapoor"
},
{
"code": null,
"e": 30777,
"s": 30767,
"text": "Bit Magic"
},
{
"code": null,
"e": 30801,
"s": 30777,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30819,
"s": 30801,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30827,
"s": 30819,
"text": "Strings"
},
{
"code": null,
"e": 30835,
"s": 30827,
"text": "Strings"
},
{
"code": null,
"e": 30845,
"s": 30835,
"text": "Bit Magic"
},
{
"code": null,
"e": 30863,
"s": 30845,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30961,
"s": 30863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31007,
"s": 30961,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 31037,
"s": 31007,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 31090,
"s": 31037,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 31130,
"s": 31090,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 31168,
"s": 31130,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 31211,
"s": 31168,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 31254,
"s": 31211,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 31295,
"s": 31254,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 31333,
"s": 31295,
"text": "Bits manipulation (Important tactics)"
}
] |
Machine Learning with R: Churn Prediction | by Soner Yıldırım | Towards Data Science | R is one of the predominant languages in data science ecosystem. It is primarily designed for statistical computing and graphics. R makes it simple to efficiently implement statistical techniques and thus it is excellent choice for machine learning tasks.
In this article, we will create a random forest model to solve a typical machine learning problem: churn prediction.
Note: If you’d like to read this article in Spanish, it is published on Planeta Chatbot.
Customer churn is an important issue for every business. While looking for ways to expand customer portfolio, businesses also focuses on keeping the existing customers. Thus, it is crucial to learn the reasons why existing customers churn (i.e. leaves).
The dataset is available on Kaggle. We will use the randomForest library for R. The first step is to install and import the library.
install.package("randomForest")library(randomForest)
I use R-studio IDE but there are other alternatives too. The next step is to read the dataset into a table.
> churn <- read.table("/home/soner/Downloads/datasets/BankChurners.csv", sep = ",", header = TRUE)
Some of the columns are redundant or highly correlated with another column. Thus, we will drop 7 columns.
> churn2 <- churn[-c(1,3,10,16,19,22,23)]
The code above filters the table based on the given index list of the columns. We add a minus sign before the list to indicate these columns will be dropped.
I wrote a separate article as exploratory data analysis of this dataset. I suggest to read it if you’d like to know why we drop some of the columns.
Here is a list of the remaining columns:
The attrition flag column is our target variable and indicates whether a customer churned (i.e. left the company). Remaining columns carry information about the customers and their activities with the bank.
The next step is to split the dataset into train and test subsets. We first create a partition and use it to split the data. Before splitting the dataset, we need to factor the target variable (Attrition_Flag) so that the model knows this is a classification task.
> churn2$Attrition_Flag = as.factor(churn2$Attrition_Flag)> set.seed(42)> train <- sample(nrow(churn2), 0.8*nrow(churn2), replace = FALSE)> train_set <- churn2[train,]> test_set <- churn2[-train,]
We randomly select 80% of the observations (i.e. rows) for training. The remaining ones are stored in the test set.
The next step is to create a random forest model and train it.
> model_rf <- randomForest(Attrition_Flag ~ ., data = train_set, importance = TRUE)
We create random forest model and indicate the target variable. The dot after the tilde (~) operator tells the model that all other columns are used in training as independent variables.
Here is a summary of the random forest model:
The number of trees used in the forest is 500 by default. We can change it using the ntree parameter.
The critical metric for evaluation is the OOB (Out of bag) estimate of the error rate. I would like to briefly explain how random forest algorithm works before going in detail about the OOB estimate of the error.
Random forest uses bootstrap sampling which means randomly selecting samples from training data with replacement. Each bootstrap sample contains a random sample from the entire dataset. The observations that are not in a bootstrap sample are referred to as out of bag data. In order to get an unbiased and more accurate evaluation of the model, out of bag error is used.
The OOB error rate is 5.33% which means the accuracy of the model is approximately 95%.
The confusion matrix is also an important tool to evaluate a classification model. It shows the number of correct and incorrect predictions for each class.
In order to evaluate the model on the test set, we first make predictions.
> predTest <- predict(model_rf, test_set, type = "class")> mean(predTest == test_set$Attrition_Flag) [1] 0.9343534
We compare the predictions and the target variable of the test set (Attrition_Flag) and take the mean. The classification accuracy of the model on the test set is 93.4% which is a little lower than the accuracy on the train set.
We can also generate the confusion matrix of the predictions on the test set.
It seems like the model performs worse at predicting the churned customers (i.e. attrited) than the existing customers. The main reason of this issue is the unbalanced class distribution. The number of churned customers is much less than the number of existing customers. One way to overcome this issue is to use upsampling to increase the number of observations in attrited customer class.
Hyperparameter tuning is an important part of model building, especially for complex model. For instance, changing the number of trees in random forest or the maximum depth of an individual tree are considered as hyperparameter tuning.
Hyperparameter tuning requires to have a comprehensive understanding of the hyperparameters of an algorithm. It would not be efficient just to try out random values.
We have covered the randomForest library in R programming language. The syntax is fairly simple and the model evaluation tools are highly intuitive.
Python and R are the two most commonly used programming language in data science and machine learning. Both of them have a rich selection of libraries and frameworks that makes the life easier for data scientists and machine learning engineers.
I don’t think one is superior to other with regards to data science related tasks. I suggest to learn both in order to benefit some special features of both.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 302,
"s": 46,
"text": "R is one of the predominant languages in data science ecosystem. It is primarily designed for statistical computing and graphics. R makes it simple to efficiently implement statistical techniques and thus it is excellent choice for machine learning tasks."
},
{
"code": null,
"e": 419,
"s": 302,
"text": "In this article, we will create a random forest model to solve a typical machine learning problem: churn prediction."
},
{
"code": null,
"e": 508,
"s": 419,
"text": "Note: If you’d like to read this article in Spanish, it is published on Planeta Chatbot."
},
{
"code": null,
"e": 762,
"s": 508,
"text": "Customer churn is an important issue for every business. While looking for ways to expand customer portfolio, businesses also focuses on keeping the existing customers. Thus, it is crucial to learn the reasons why existing customers churn (i.e. leaves)."
},
{
"code": null,
"e": 895,
"s": 762,
"text": "The dataset is available on Kaggle. We will use the randomForest library for R. The first step is to install and import the library."
},
{
"code": null,
"e": 948,
"s": 895,
"text": "install.package(\"randomForest\")library(randomForest)"
},
{
"code": null,
"e": 1056,
"s": 948,
"text": "I use R-studio IDE but there are other alternatives too. The next step is to read the dataset into a table."
},
{
"code": null,
"e": 1155,
"s": 1056,
"text": "> churn <- read.table(\"/home/soner/Downloads/datasets/BankChurners.csv\", sep = \",\", header = TRUE)"
},
{
"code": null,
"e": 1261,
"s": 1155,
"text": "Some of the columns are redundant or highly correlated with another column. Thus, we will drop 7 columns."
},
{
"code": null,
"e": 1303,
"s": 1261,
"text": "> churn2 <- churn[-c(1,3,10,16,19,22,23)]"
},
{
"code": null,
"e": 1461,
"s": 1303,
"text": "The code above filters the table based on the given index list of the columns. We add a minus sign before the list to indicate these columns will be dropped."
},
{
"code": null,
"e": 1610,
"s": 1461,
"text": "I wrote a separate article as exploratory data analysis of this dataset. I suggest to read it if you’d like to know why we drop some of the columns."
},
{
"code": null,
"e": 1651,
"s": 1610,
"text": "Here is a list of the remaining columns:"
},
{
"code": null,
"e": 1858,
"s": 1651,
"text": "The attrition flag column is our target variable and indicates whether a customer churned (i.e. left the company). Remaining columns carry information about the customers and their activities with the bank."
},
{
"code": null,
"e": 2123,
"s": 1858,
"text": "The next step is to split the dataset into train and test subsets. We first create a partition and use it to split the data. Before splitting the dataset, we need to factor the target variable (Attrition_Flag) so that the model knows this is a classification task."
},
{
"code": null,
"e": 2320,
"s": 2123,
"text": "> churn2$Attrition_Flag = as.factor(churn2$Attrition_Flag)> set.seed(42)> train <- sample(nrow(churn2), 0.8*nrow(churn2), replace = FALSE)> train_set <- churn2[train,]> test_set <- churn2[-train,]"
},
{
"code": null,
"e": 2436,
"s": 2320,
"text": "We randomly select 80% of the observations (i.e. rows) for training. The remaining ones are stored in the test set."
},
{
"code": null,
"e": 2499,
"s": 2436,
"text": "The next step is to create a random forest model and train it."
},
{
"code": null,
"e": 2583,
"s": 2499,
"text": "> model_rf <- randomForest(Attrition_Flag ~ ., data = train_set, importance = TRUE)"
},
{
"code": null,
"e": 2770,
"s": 2583,
"text": "We create random forest model and indicate the target variable. The dot after the tilde (~) operator tells the model that all other columns are used in training as independent variables."
},
{
"code": null,
"e": 2816,
"s": 2770,
"text": "Here is a summary of the random forest model:"
},
{
"code": null,
"e": 2918,
"s": 2816,
"text": "The number of trees used in the forest is 500 by default. We can change it using the ntree parameter."
},
{
"code": null,
"e": 3131,
"s": 2918,
"text": "The critical metric for evaluation is the OOB (Out of bag) estimate of the error rate. I would like to briefly explain how random forest algorithm works before going in detail about the OOB estimate of the error."
},
{
"code": null,
"e": 3502,
"s": 3131,
"text": "Random forest uses bootstrap sampling which means randomly selecting samples from training data with replacement. Each bootstrap sample contains a random sample from the entire dataset. The observations that are not in a bootstrap sample are referred to as out of bag data. In order to get an unbiased and more accurate evaluation of the model, out of bag error is used."
},
{
"code": null,
"e": 3590,
"s": 3502,
"text": "The OOB error rate is 5.33% which means the accuracy of the model is approximately 95%."
},
{
"code": null,
"e": 3746,
"s": 3590,
"text": "The confusion matrix is also an important tool to evaluate a classification model. It shows the number of correct and incorrect predictions for each class."
},
{
"code": null,
"e": 3821,
"s": 3746,
"text": "In order to evaluate the model on the test set, we first make predictions."
},
{
"code": null,
"e": 3955,
"s": 3821,
"text": "> predTest <- predict(model_rf, test_set, type = \"class\")> mean(predTest == test_set$Attrition_Flag) [1] 0.9343534"
},
{
"code": null,
"e": 4184,
"s": 3955,
"text": "We compare the predictions and the target variable of the test set (Attrition_Flag) and take the mean. The classification accuracy of the model on the test set is 93.4% which is a little lower than the accuracy on the train set."
},
{
"code": null,
"e": 4262,
"s": 4184,
"text": "We can also generate the confusion matrix of the predictions on the test set."
},
{
"code": null,
"e": 4653,
"s": 4262,
"text": "It seems like the model performs worse at predicting the churned customers (i.e. attrited) than the existing customers. The main reason of this issue is the unbalanced class distribution. The number of churned customers is much less than the number of existing customers. One way to overcome this issue is to use upsampling to increase the number of observations in attrited customer class."
},
{
"code": null,
"e": 4889,
"s": 4653,
"text": "Hyperparameter tuning is an important part of model building, especially for complex model. For instance, changing the number of trees in random forest or the maximum depth of an individual tree are considered as hyperparameter tuning."
},
{
"code": null,
"e": 5055,
"s": 4889,
"text": "Hyperparameter tuning requires to have a comprehensive understanding of the hyperparameters of an algorithm. It would not be efficient just to try out random values."
},
{
"code": null,
"e": 5204,
"s": 5055,
"text": "We have covered the randomForest library in R programming language. The syntax is fairly simple and the model evaluation tools are highly intuitive."
},
{
"code": null,
"e": 5449,
"s": 5204,
"text": "Python and R are the two most commonly used programming language in data science and machine learning. Both of them have a rich selection of libraries and frameworks that makes the life easier for data scientists and machine learning engineers."
},
{
"code": null,
"e": 5607,
"s": 5449,
"text": "I don’t think one is superior to other with regards to data science related tasks. I suggest to learn both in order to benefit some special features of both."
}
] |
Check for subsequence | Practice | GeeksforGeeks | Given two strings A and B, find if A is a subsequence of B.
Example 1:
Input:
A = AXY
B = YADXCP
Output: 0
Explanation: A is not a subsequence of B
as 'Y' appears before 'A'.
Example 2:
Input:
A = gksrek
B = geeksforgeeks
Output: 1
Explanation: A is a subsequence of B.
Your Task:
You dont need to read input or print anything. Complete the function isSubSequence() which takes A and B as input parameters and returns a boolean value denoting if A is a subsequence of B or not.
Expected Time Complexity: O(N) where N is length of string B.
Expected Auxiliary Space: O(1)
Constraints:
1<= |A|,|B| <=104
0
rjpatil20011 week ago
bool isSubSequence(string A, string B) { // code here int j=0; for(int i =0;i<B.length();i++){ if(B[i] == A[j]){ j++; } } if(j == A.length()) return true; else false; }
0
jayesh293 weeks ago
Very Easy Java Solution:-
boolean isSubSequence(String A, String B){
int j=0,m=A.length(),n=B.length();
for(int i=0; i<n && j<m; i++){
if(A.charAt(j)==B.charAt(i)) j++;
}
return (j==m);
}
0
dineshvishnukanth1 month ago
Python Solution:
class Solution: def isSubSequence(self, A, B): c=0 B=[i for i in B] for i in range(len(A)): for j in range(len(B)): if A[i]==B[j]: B[:j+1]=' ' c+=1 break if c==len(A): return(True) else: return(False)
0
geeky_kuldeep1 month ago
JS Solution using queueclass Solution { isSubSequence(A,B){ let AQ = A.split(''); for (let b of B) { if (b === AQ[0]) AQ.shift(); if (AQ.length === 0) return 1; } return 0; }}
+1
mayank20212 months ago
C++ 0.3/1.7bool isSubSequence(string A, string B) { if(A.length() > B.length()) return 0; if(A == B) return 1; int j=0; for(int i=0; i<B.length(); i++) { if(A[j]==B[i]) { if(j==A.length()-1) return 1; j++; } } return 0; }
+1
tarun2002ts0212 months ago
my dp approch
int m=B.size(),n=A.size(); vector<vector<bool>>dp(m+1,vector<bool>(n+1,-1)); for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { if(j==0) dp[i][j]= true; else if(i==0 && j!=0) dp[i][j]=false; else if(A[j-1]==B[i-1]) dp[i][j]=dp[i-1][j-1]&&true; else dp[i][j]=dp[i-1][j]; } } return dp[m][n];
0
anindiangeek2 months ago
int first{0},second{0};
while(second<B.length())
if(B[second++]==A[first]) first++;
return (second==A.length());
0
prasadkandekar5552 months ago
C++ O(N) Solution :)
class Solution{
public:
bool isSubSequence(string a, string b) {
int n = a.length(), m = b.length();
int i = 0, j = 0;
while(i < n && j < m) {
if(a[i] == b[j]) i++;
j++;
}
return i == n;
}
};
0
ervishnu19942 months ago
class Solution{ boolean isSubSequence(String A, String B){ int i=0; int n=A.length(),m=B.length(); for(int j=0;j<m&&n>i;j++){ if(A.charAt(i)==B.charAt(j)){ i++; } } if(i>=n)return true; return false; }}
0
akkeshri140420013 months ago
bool isSubSequence(string A, string B) { // code here int m=A.length(); int n=B.length(); int i=0,j=0; while(i<n and j<m){ if(A[j]!=B[i]){ i++; } else if(A[j]==B[i]){ i++; j++; } } if(j==m){ return true; } return false; }
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": 298,
"s": 238,
"text": "Given two strings A and B, find if A is a subsequence of B."
},
{
"code": null,
"e": 309,
"s": 298,
"text": "Example 1:"
},
{
"code": null,
"e": 416,
"s": 309,
"text": "Input:\nA = AXY \nB = YADXCP\nOutput: 0 \nExplanation: A is not a subsequence of B\nas 'Y' appears before 'A'.\n"
},
{
"code": null,
"e": 429,
"s": 418,
"text": "Example 2:"
},
{
"code": null,
"e": 513,
"s": 429,
"text": "Input:\nA = gksrek\nB = geeksforgeeks\nOutput: 1\nExplanation: A is a subsequence of B."
},
{
"code": null,
"e": 726,
"s": 515,
"text": "Your Task: \nYou dont need to read input or print anything. Complete the function isSubSequence() which takes A and B as input parameters and returns a boolean value denoting if A is a subsequence of B or not. "
},
{
"code": null,
"e": 821,
"s": 728,
"text": "Expected Time Complexity: O(N) where N is length of string B.\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 853,
"s": 821,
"text": "\nConstraints:\n1<= |A|,|B| <=104"
},
{
"code": null,
"e": 857,
"s": 855,
"text": "0"
},
{
"code": null,
"e": 879,
"s": 857,
"text": "rjpatil20011 week ago"
},
{
"code": null,
"e": 1118,
"s": 879,
"text": "bool isSubSequence(string A, string B) { // code here int j=0; for(int i =0;i<B.length();i++){ if(B[i] == A[j]){ j++; } } if(j == A.length()) return true; else false; }"
},
{
"code": null,
"e": 1120,
"s": 1118,
"text": "0"
},
{
"code": null,
"e": 1140,
"s": 1120,
"text": "jayesh293 weeks ago"
},
{
"code": null,
"e": 1166,
"s": 1140,
"text": "Very Easy Java Solution:-"
},
{
"code": null,
"e": 1380,
"s": 1166,
"text": " boolean isSubSequence(String A, String B){\n int j=0,m=A.length(),n=B.length();\n for(int i=0; i<n && j<m; i++){\n if(A.charAt(j)==B.charAt(i)) j++;\n }\n return (j==m);\n }"
},
{
"code": null,
"e": 1382,
"s": 1380,
"text": "0"
},
{
"code": null,
"e": 1411,
"s": 1382,
"text": "dineshvishnukanth1 month ago"
},
{
"code": null,
"e": 1428,
"s": 1411,
"text": "Python Solution:"
},
{
"code": null,
"e": 1810,
"s": 1430,
"text": "class Solution: def isSubSequence(self, A, B): c=0 B=[i for i in B] for i in range(len(A)): for j in range(len(B)): if A[i]==B[j]: B[:j+1]=' ' c+=1 break if c==len(A): return(True) else: return(False)"
},
{
"code": null,
"e": 1812,
"s": 1810,
"text": "0"
},
{
"code": null,
"e": 1837,
"s": 1812,
"text": "geeky_kuldeep1 month ago"
},
{
"code": null,
"e": 2056,
"s": 1837,
"text": "JS Solution using queueclass Solution { isSubSequence(A,B){ let AQ = A.split(''); for (let b of B) { if (b === AQ[0]) AQ.shift(); if (AQ.length === 0) return 1; } return 0; }}"
},
{
"code": null,
"e": 2059,
"s": 2056,
"text": "+1"
},
{
"code": null,
"e": 2082,
"s": 2059,
"text": "mayank20212 months ago"
},
{
"code": null,
"e": 2448,
"s": 2082,
"text": "C++ 0.3/1.7bool isSubSequence(string A, string B) { if(A.length() > B.length()) return 0; if(A == B) return 1; int j=0; for(int i=0; i<B.length(); i++) { if(A[j]==B[i]) { if(j==A.length()-1) return 1; j++; } } return 0; }"
},
{
"code": null,
"e": 2451,
"s": 2448,
"text": "+1"
},
{
"code": null,
"e": 2478,
"s": 2451,
"text": "tarun2002ts0212 months ago"
},
{
"code": null,
"e": 2493,
"s": 2478,
"text": "my dp approch "
},
{
"code": null,
"e": 2957,
"s": 2493,
"text": " int m=B.size(),n=A.size(); vector<vector<bool>>dp(m+1,vector<bool>(n+1,-1)); for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { if(j==0) dp[i][j]= true; else if(i==0 && j!=0) dp[i][j]=false; else if(A[j-1]==B[i-1]) dp[i][j]=dp[i-1][j-1]&&true; else dp[i][j]=dp[i-1][j]; } } return dp[m][n];"
},
{
"code": null,
"e": 2959,
"s": 2957,
"text": "0"
},
{
"code": null,
"e": 2984,
"s": 2959,
"text": "anindiangeek2 months ago"
},
{
"code": null,
"e": 3133,
"s": 2984,
"text": " int first{0},second{0};\n while(second<B.length())\n if(B[second++]==A[first]) first++;\n return (second==A.length());"
},
{
"code": null,
"e": 3135,
"s": 3133,
"text": "0"
},
{
"code": null,
"e": 3165,
"s": 3135,
"text": "prasadkandekar5552 months ago"
},
{
"code": null,
"e": 3186,
"s": 3165,
"text": "C++ O(N) Solution :)"
},
{
"code": null,
"e": 3454,
"s": 3186,
"text": "class Solution{\n public:\n bool isSubSequence(string a, string b) {\n int n = a.length(), m = b.length();\n int i = 0, j = 0;\n while(i < n && j < m) {\n if(a[i] == b[j]) i++;\n j++;\n }\n return i == n;\n }\n};"
},
{
"code": null,
"e": 3456,
"s": 3454,
"text": "0"
},
{
"code": null,
"e": 3481,
"s": 3456,
"text": "ervishnu19942 months ago"
},
{
"code": null,
"e": 3757,
"s": 3481,
"text": "class Solution{ boolean isSubSequence(String A, String B){ int i=0; int n=A.length(),m=B.length(); for(int j=0;j<m&&n>i;j++){ if(A.charAt(i)==B.charAt(j)){ i++; } } if(i>=n)return true; return false; }}"
},
{
"code": null,
"e": 3759,
"s": 3757,
"text": "0"
},
{
"code": null,
"e": 3788,
"s": 3759,
"text": "akkeshri140420013 months ago"
},
{
"code": null,
"e": 4186,
"s": 3788,
"text": "bool isSubSequence(string A, string B) { // code here int m=A.length(); int n=B.length(); int i=0,j=0; while(i<n and j<m){ if(A[j]!=B[i]){ i++; } else if(A[j]==B[i]){ i++; j++; } } if(j==m){ return true; } return false; }"
},
{
"code": null,
"e": 4332,
"s": 4186,
"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": 4368,
"s": 4332,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4378,
"s": 4368,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4388,
"s": 4378,
"text": "\nContest\n"
},
{
"code": null,
"e": 4451,
"s": 4388,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4599,
"s": 4451,
"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": 4807,
"s": 4599,
"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": 4913,
"s": 4807,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Group by in Pandas, SQL, and NoSQL | by Soner Yıldırım | Towards Data Science | The group by operations are commonly used in exploratory data analysis. Almost every data analysis tool and framework provides an implementation of group by operation.
The group by operation involves grouping numerical values based on the values of a discrete or categorical variable and then apply some form of transformation or aggregation.
For instance, finding the average house prices in different neighborhoods of a city is a group by operation. The prices are grouped based on neighborhoods and the mean function is applied.
The following figure illustrates how a typical group by operation is executed.
In this article, we will see how group by operations are done in Pandas, SQL, and MongoDB (NoSQL database). There will be a separate section for each tool and we will do the same examples in each section.
Pandas is a highly popular data analysis and manipulation library for Python. The group by operations are done using the “groupby” function.
The dataset is stores in a dataframe called marketing.
Let’s first calculate the average amount spent per age group. We select both the column to be aggregates and the column to be used for grouping. The grouping column is passed to the groupby function. Then, we apply the desired aggregate function which is the mean function in this case.
marketing[['Age','AmountSpent']].groupby('Age').mean() AmountSpent Age --------------------- Middle 1501.690945 Old 1432.126829 Young 558.623693
The middle aged customers tend to spend most on average.
We can group by multiple columns. The group by function accepts multiple columns in a list. Let’s also add the gender column in the groups to make the previous example more detailed.
marketing[['Age','Gender','AmountSpent']]\.groupby(['Age','Gender']).mean() AmountSpent Age Gender------------------------------------- Middle Female 1301.339806 Male 1638.354305 Old Female 1279.310078 Male 1691.513158 Young Female 501.257310 Male 643.189655
It seems like males tend to spend more than females in all age groups.
We have seen multiple columns to be used grouping. Another common case is to aggregate multiple columns. For instance, we can calculate the average salary and total spent amount for categories in the own home column.
There are multiple ways of doing this task. The simplest one is as follows:
marketing[['OwnHome','Salary','AmountSpent']]\.groupby('OwnHome').agg({'Salary':'mean', 'AmountSpent':'sum'}) Salary AmountSpent OwnHome --------------------------------------- Own 69758.720930 796258 Rent 41546.280992 420512
We pass a dictionary to the agg function that indicates the aggregations applied to each column. However, we can’t really tell from the results which aggregation function is applied the columns because it only shows the column names.
One solution overcome this issue is to use the NamedAgg method.
marketing[['OwnHome','Salary','AmountSpent']]\.groupby('OwnHome').agg( avgSalary = pd.NamedAgg('Salary','mean'), totalSpent = pd.NamedAgg('AmountSpent','sum')) avgSalary totalSpent OwnHome --------------------------------------- Own 69758.720930 796258 Rent 41546.280992 420512
SQL is a programming language used for managing data in a relational database. It allows for efficient and versatile ways to filter, transform, and analyze data stored in databases.
There are many relational database managements systems that use SQL. Although most of the SQL syntax is the same among them, there might be small differences. I will be using MySQL.
The dataset is stored in a table called marketing.
The first example includes finding the average spent amount for categories in the age column. We use the select statement with the group by clause. The columns are selected first. The aggregate function is specified while selecting the column. Then, we use the group by with the age column.
mysql> select Age, avg(AmountSpent) -> from marketing -> group by Age;+--------+------------------+| Age | avg(AmountSpent) |+--------+------------------+| Middle | 1501.6909 || Old | 1432.1268 || Young | 558.6237 |+--------+------------------+
In the second example, we add another column to be used for grouping. For SQL, we add multiple columns to the group by clause separated by comma.
mysql> select Age, Gender, avg(AmountSpent) -> from marketing -> group by Age, Gender;+--------+--------+------------------+| Age | Gender | avg(AmountSpent) |+--------+--------+------------------+| Middle | Female | 1301.3398 || Middle | Male | 1638.3543 || Old | Female | 1279.3101 || Old | Male | 1691.5132 || Young | Female | 501.2573 || Young | Male | 643.1897 |+--------+--------+------------------+
The third example includes multiple aggregations. We calculate the average salary and total spent amount for categories in the own home column.
mysql> select OwnHome, avg(Salary) as avgSalary, -> sum(AmountSpent) as totalSpent -> from marketing -> group by OwnHome;+---------+------------+------------+| OwnHome | avgSalary | totalSpent |+---------+------------+------------+| Own | 69758.7209 | 796258 || Rent | 41546.2810 | 420512 |+---------+------------+------------+
For Pandas, we have used the NamedAgg method to rename the aggregated columns. For SQL, we can change the names using the “as” keyword.
NoSQL refers to non-SQL or non-relational database design. NoSQL also provides an organized way of storing data but not in tabular form.
There are several NoSQL databases used in the data science ecosystem. In this article, we will be using MongoDB which stores data as documents. A document in MongoDB consists of field-value pairs. Documents are organized in a structure called “collection”. As an analogy, we can think of documents as rows in a table and collections as tables.
The dataset is stored in a collection called marketing. Here is a document in the marketing collection that represents an observation (i.e. a row in a table).
> db.marketing.find().limit(1).pretty(){ "_id" : ObjectId("6014dc988c628fa57a508088"), "Age" : "Middle", "Gender" : "Male", "OwnHome" : "Rent", "Married" : "Single", "Location" : "Close", "Salary" : 63600, "Children" : 0, "History" : "High", "Catalogs" : 6, "AmountSpent" : 1318}
The db refers to the current database. We need to specify the collection name after the dot.
MongoDB provides the aggregate pipeline for data analysis operations such as filtering, transforming, filtering, and so on. For group by operations, we use the “$group” stage in the aggregate pipeline.
The first example is to calculate average spent amount for each age group.
> db.marketing.aggregate([... { $group: { _id: "$Age", avgSpent: { $avg: "$AmountSpent" }}}... ]){ "_id" : "Old", "avgSpent" : 1432.1268292682928 }{ "_id" : "Middle", "avgSpent" : 1501.6909448818897 }{ "_id" : "Young", "avgSpent" : 558.6236933797909 }
The fields (i.e. column in table) used for grouping are passed to the group stage with the “_id” keyword. We assign a name for each aggregation that contains the field to be aggregated and the aggregation function.
The next example contains two fields used for grouping. We specify both fields with the “_id” keyword as follows:
> db.marketing.aggregate([... {... $group:... {... _id: {OwnHome: "$OwnHome", Gender: "$Gender"},... avgSpent: { $avg: "$AmountSpent" }... }... }... ]).pretty(){ "_id" : { "ownhome" : "Rent", "gender" : "Male" }, "avg_spent" : 996.1238532110092}{ "_id" : { "ownhome" : "Own", "gender" : "Male" }, "avg_spent" : 1742.0036231884058}{ "_id" : { "ownhome" : "Own", "gender" : "Female" }, "avg_spent" : 1314.4375}{ "_id" : { "ownhome" : "Rent", "gender" : "Female" }, "avg_spent" : 764.5}
The final example contains two fields to be aggregated. We specify them separately in the group stage as follows.
> db.marketing.aggregate([... { ... $group:... {... _id: "$OwnHome",... avgSalary: { $avg: "$Salary" },... totalSpent: { $sum: "$AmountSpent" }... }... }... ]){ "_id" : "Own", "avgSalary" : 69758.72093023256, "totalSpent" : 796258 }{ "_id" : "Rent", "avgSalary" : 41546.28099173554, "totalSpent" : 420512 }
We have done three examples that demonstrate how grouping is done in Pandas, SQL, and MongoDB. The goal of this article is to introduce the idea behind the group by operation and cover the basic syntax for each tool.
For each tool, we can performed more complicated group by operations. For instance, the results can be sorted based on an aggregated column. All of the tools provide a decent way to sort the results of the group by operations.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 340,
"s": 172,
"text": "The group by operations are commonly used in exploratory data analysis. Almost every data analysis tool and framework provides an implementation of group by operation."
},
{
"code": null,
"e": 515,
"s": 340,
"text": "The group by operation involves grouping numerical values based on the values of a discrete or categorical variable and then apply some form of transformation or aggregation."
},
{
"code": null,
"e": 704,
"s": 515,
"text": "For instance, finding the average house prices in different neighborhoods of a city is a group by operation. The prices are grouped based on neighborhoods and the mean function is applied."
},
{
"code": null,
"e": 783,
"s": 704,
"text": "The following figure illustrates how a typical group by operation is executed."
},
{
"code": null,
"e": 988,
"s": 783,
"text": "In this article, we will see how group by operations are done in Pandas, SQL, and MongoDB (NoSQL database). There will be a separate section for each tool and we will do the same examples in each section."
},
{
"code": null,
"e": 1129,
"s": 988,
"text": "Pandas is a highly popular data analysis and manipulation library for Python. The group by operations are done using the “groupby” function."
},
{
"code": null,
"e": 1184,
"s": 1129,
"text": "The dataset is stores in a dataframe called marketing."
},
{
"code": null,
"e": 1471,
"s": 1184,
"text": "Let’s first calculate the average amount spent per age group. We select both the column to be aggregates and the column to be used for grouping. The grouping column is passed to the groupby function. Then, we apply the desired aggregate function which is the mean function in this case."
},
{
"code": null,
"e": 1715,
"s": 1471,
"text": "marketing[['Age','AmountSpent']].groupby('Age').mean() AmountSpent Age --------------------- Middle 1501.690945 Old 1432.126829 Young 558.623693"
},
{
"code": null,
"e": 1772,
"s": 1715,
"text": "The middle aged customers tend to spend most on average."
},
{
"code": null,
"e": 1955,
"s": 1772,
"text": "We can group by multiple columns. The group by function accepts multiple columns in a list. Let’s also add the gender column in the groups to make the previous example more detailed."
},
{
"code": null,
"e": 2477,
"s": 1955,
"text": "marketing[['Age','Gender','AmountSpent']]\\.groupby(['Age','Gender']).mean() AmountSpent Age Gender------------------------------------- Middle Female 1301.339806 Male 1638.354305 Old Female 1279.310078 Male 1691.513158 Young Female 501.257310 Male 643.189655"
},
{
"code": null,
"e": 2548,
"s": 2477,
"text": "It seems like males tend to spend more than females in all age groups."
},
{
"code": null,
"e": 2765,
"s": 2548,
"text": "We have seen multiple columns to be used grouping. Another common case is to aggregate multiple columns. For instance, we can calculate the average salary and total spent amount for categories in the own home column."
},
{
"code": null,
"e": 2841,
"s": 2765,
"text": "There are multiple ways of doing this task. The simplest one is as follows:"
},
{
"code": null,
"e": 3184,
"s": 2841,
"text": "marketing[['OwnHome','Salary','AmountSpent']]\\.groupby('OwnHome').agg({'Salary':'mean', 'AmountSpent':'sum'}) Salary AmountSpent OwnHome --------------------------------------- Own 69758.720930 796258 Rent 41546.280992 420512"
},
{
"code": null,
"e": 3418,
"s": 3184,
"text": "We pass a dictionary to the agg function that indicates the aggregations applied to each column. However, we can’t really tell from the results which aggregation function is applied the columns because it only shows the column names."
},
{
"code": null,
"e": 3482,
"s": 3418,
"text": "One solution overcome this issue is to use the NamedAgg method."
},
{
"code": null,
"e": 3883,
"s": 3482,
"text": "marketing[['OwnHome','Salary','AmountSpent']]\\.groupby('OwnHome').agg( avgSalary = pd.NamedAgg('Salary','mean'), totalSpent = pd.NamedAgg('AmountSpent','sum')) avgSalary totalSpent OwnHome --------------------------------------- Own 69758.720930 796258 Rent 41546.280992 420512"
},
{
"code": null,
"e": 4065,
"s": 3883,
"text": "SQL is a programming language used for managing data in a relational database. It allows for efficient and versatile ways to filter, transform, and analyze data stored in databases."
},
{
"code": null,
"e": 4247,
"s": 4065,
"text": "There are many relational database managements systems that use SQL. Although most of the SQL syntax is the same among them, there might be small differences. I will be using MySQL."
},
{
"code": null,
"e": 4298,
"s": 4247,
"text": "The dataset is stored in a table called marketing."
},
{
"code": null,
"e": 4589,
"s": 4298,
"text": "The first example includes finding the average spent amount for categories in the age column. We use the select statement with the group by clause. The columns are selected first. The aggregate function is specified while selecting the column. Then, we use the group by with the age column."
},
{
"code": null,
"e": 4869,
"s": 4589,
"text": "mysql> select Age, avg(AmountSpent) -> from marketing -> group by Age;+--------+------------------+| Age | avg(AmountSpent) |+--------+------------------+| Middle | 1501.6909 || Old | 1432.1268 || Young | 558.6237 |+--------+------------------+"
},
{
"code": null,
"e": 5015,
"s": 4869,
"text": "In the second example, we add another column to be used for grouping. For SQL, we add multiple columns to the group by clause separated by comma."
},
{
"code": null,
"e": 5488,
"s": 5015,
"text": "mysql> select Age, Gender, avg(AmountSpent) -> from marketing -> group by Age, Gender;+--------+--------+------------------+| Age | Gender | avg(AmountSpent) |+--------+--------+------------------+| Middle | Female | 1301.3398 || Middle | Male | 1638.3543 || Old | Female | 1279.3101 || Old | Male | 1691.5132 || Young | Female | 501.2573 || Young | Male | 643.1897 |+--------+--------+------------------+"
},
{
"code": null,
"e": 5632,
"s": 5488,
"text": "The third example includes multiple aggregations. We calculate the average salary and total spent amount for categories in the own home column."
},
{
"code": null,
"e": 5985,
"s": 5632,
"text": "mysql> select OwnHome, avg(Salary) as avgSalary, -> sum(AmountSpent) as totalSpent -> from marketing -> group by OwnHome;+---------+------------+------------+| OwnHome | avgSalary | totalSpent |+---------+------------+------------+| Own | 69758.7209 | 796258 || Rent | 41546.2810 | 420512 |+---------+------------+------------+"
},
{
"code": null,
"e": 6121,
"s": 5985,
"text": "For Pandas, we have used the NamedAgg method to rename the aggregated columns. For SQL, we can change the names using the “as” keyword."
},
{
"code": null,
"e": 6258,
"s": 6121,
"text": "NoSQL refers to non-SQL or non-relational database design. NoSQL also provides an organized way of storing data but not in tabular form."
},
{
"code": null,
"e": 6602,
"s": 6258,
"text": "There are several NoSQL databases used in the data science ecosystem. In this article, we will be using MongoDB which stores data as documents. A document in MongoDB consists of field-value pairs. Documents are organized in a structure called “collection”. As an analogy, we can think of documents as rows in a table and collections as tables."
},
{
"code": null,
"e": 6761,
"s": 6602,
"text": "The dataset is stored in a collection called marketing. Here is a document in the marketing collection that represents an observation (i.e. a row in a table)."
},
{
"code": null,
"e": 7041,
"s": 6761,
"text": "> db.marketing.find().limit(1).pretty(){ \"_id\" : ObjectId(\"6014dc988c628fa57a508088\"), \"Age\" : \"Middle\", \"Gender\" : \"Male\", \"OwnHome\" : \"Rent\", \"Married\" : \"Single\", \"Location\" : \"Close\", \"Salary\" : 63600, \"Children\" : 0, \"History\" : \"High\", \"Catalogs\" : 6, \"AmountSpent\" : 1318}"
},
{
"code": null,
"e": 7134,
"s": 7041,
"text": "The db refers to the current database. We need to specify the collection name after the dot."
},
{
"code": null,
"e": 7336,
"s": 7134,
"text": "MongoDB provides the aggregate pipeline for data analysis operations such as filtering, transforming, filtering, and so on. For group by operations, we use the “$group” stage in the aggregate pipeline."
},
{
"code": null,
"e": 7411,
"s": 7336,
"text": "The first example is to calculate average spent amount for each age group."
},
{
"code": null,
"e": 7663,
"s": 7411,
"text": "> db.marketing.aggregate([... { $group: { _id: \"$Age\", avgSpent: { $avg: \"$AmountSpent\" }}}... ]){ \"_id\" : \"Old\", \"avgSpent\" : 1432.1268292682928 }{ \"_id\" : \"Middle\", \"avgSpent\" : 1501.6909448818897 }{ \"_id\" : \"Young\", \"avgSpent\" : 558.6236933797909 }"
},
{
"code": null,
"e": 7878,
"s": 7663,
"text": "The fields (i.e. column in table) used for grouping are passed to the group stage with the “_id” keyword. We assign a name for each aggregation that contains the field to be aggregated and the aggregation function."
},
{
"code": null,
"e": 7992,
"s": 7878,
"text": "The next example contains two fields used for grouping. We specify both fields with the “_id” keyword as follows:"
},
{
"code": null,
"e": 8502,
"s": 7992,
"text": "> db.marketing.aggregate([... {... $group:... {... _id: {OwnHome: \"$OwnHome\", Gender: \"$Gender\"},... avgSpent: { $avg: \"$AmountSpent\" }... }... }... ]).pretty(){ \"_id\" : { \"ownhome\" : \"Rent\", \"gender\" : \"Male\" }, \"avg_spent\" : 996.1238532110092}{ \"_id\" : { \"ownhome\" : \"Own\", \"gender\" : \"Male\" }, \"avg_spent\" : 1742.0036231884058}{ \"_id\" : { \"ownhome\" : \"Own\", \"gender\" : \"Female\" }, \"avg_spent\" : 1314.4375}{ \"_id\" : { \"ownhome\" : \"Rent\", \"gender\" : \"Female\" }, \"avg_spent\" : 764.5}"
},
{
"code": null,
"e": 8616,
"s": 8502,
"text": "The final example contains two fields to be aggregated. We specify them separately in the group stage as follows."
},
{
"code": null,
"e": 8951,
"s": 8616,
"text": "> db.marketing.aggregate([... { ... $group:... {... _id: \"$OwnHome\",... avgSalary: { $avg: \"$Salary\" },... totalSpent: { $sum: \"$AmountSpent\" }... }... }... ]){ \"_id\" : \"Own\", \"avgSalary\" : 69758.72093023256, \"totalSpent\" : 796258 }{ \"_id\" : \"Rent\", \"avgSalary\" : 41546.28099173554, \"totalSpent\" : 420512 }"
},
{
"code": null,
"e": 9168,
"s": 8951,
"text": "We have done three examples that demonstrate how grouping is done in Pandas, SQL, and MongoDB. The goal of this article is to introduce the idea behind the group by operation and cover the basic syntax for each tool."
},
{
"code": null,
"e": 9395,
"s": 9168,
"text": "For each tool, we can performed more complicated group by operations. For instance, the results can be sorted based on an aggregated column. All of the tools provide a decent way to sort the results of the group by operations."
}
] |
How to Observe Event Only Once Using SingleLiveEvent in Android? - GeeksforGeeks | 08 Sep, 2021
Have you ever had to deal with a Dialog or a SnackBar that, after being triggered/shown or dismissed, gets triggered/shown again after a device rotation? This is most likely connected to the use of LiveData observables to communicate between the ViewModel and the Activity/Fragment.
Using LiveData objects for events might be viewed as a poor design choice, especially when the event is only required once. We can use some boolean flags to assist the view in determining if the Dialog/SnackBar should be triggered/shown or not. However, this might result in a solution that is difficult to comprehend and maintain, as well as being unattractive. As you can see it has the type of live data, the data is consumed continuously, but we only want to get it once.
There are no memory leaks:
Observers are tied to Lifecycle objects and clean up after themselves when the lifecycle with which they are connected is destroyed.
There have been no accidents as a result of activity being halted:
If the observer’s lifetime is idle, like in the case of a back stack activity, it does not receive any LiveData events. LiveData just follows the observer design, and I don’t believe the above-mentioned use case warrants its own variant of the observable class. So, how can we resolve the dialogue issue? Rather than altering the behavior of LiveData, we should keep to the basics of the MVVM paradigm and, if necessary, have the ViewModel tell the ViewModel about the dismissed dialogue. Following that, the VM might reset or alter the status of the event. I realize it’s easy to forget to alert ViewModel, and we’re increasing View’s responsibilities. But, after all, it is the View’s job: to inform the VM of any user action.
Create an ‘Event’ class that is general (maybe call it LiveEvent). Give it observe(owner, observer) and observeForever functions (observer). Give it the same contract and functionality as LiveData. Except that, instead of a persistent value, the LiveEvent just notifies active observers while sending along with the data.
Kotlin
class LiveEvent<C> {... fun sendingValue(data: C) { observers.forEach { gfg -> if (gfg.isActive()) gfg.onChanged(data) } }}
Put the LiveEvent in your basic ViewModel class if you want to utilize it for publishing notifications, SnackBars, or anything on many screens. Then, after initializing the ViewModel in your basic Fragment class, watch for that LiveEvent.
Kotlin
abstract class GeeksforGeeksViewModel : ViewModel() { protected val fireAlertedEvent = LiveEvent<FireAlert>()}abstract class BaseFragment : Fragment() { fun onViewModelInitialized() { viewModel.fireAlertedEvent.observe(this, { fireAlert -> fireAlert.show() } }}class GeeksforGeeksSample : GeeksforGeeksViewModel() { fun onSaveSuccess() { fireAlertedEvent.postValue(FireAlert("yay! we got your stuff!")) }}
The optimum solution would be an event source with automatic unsubscription on destruct that enqueues events as long as no watchers are present and then sends all events to the first observer that subscribes. That can handle the events in whatever way it deems fit. When you need to manage flow, using a callback with distinct success/failure methods is a terrible idea. Make use of an ADT (sealed class).
Blogathon-2021
Picked
Android
Blogathon
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Call or Consume External API in Spring Boot?
Re-rendering Components in ReactJS
SQL Query to Insert Multiple Rows
Python NOT EQUAL operator
Difference Between Local Storage, Session Storage And Cookies | [
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 25008,
"s": 24725,
"text": "Have you ever had to deal with a Dialog or a SnackBar that, after being triggered/shown or dismissed, gets triggered/shown again after a device rotation? This is most likely connected to the use of LiveData observables to communicate between the ViewModel and the Activity/Fragment."
},
{
"code": null,
"e": 25484,
"s": 25008,
"text": "Using LiveData objects for events might be viewed as a poor design choice, especially when the event is only required once. We can use some boolean flags to assist the view in determining if the Dialog/SnackBar should be triggered/shown or not. However, this might result in a solution that is difficult to comprehend and maintain, as well as being unattractive. As you can see it has the type of live data, the data is consumed continuously, but we only want to get it once."
},
{
"code": null,
"e": 25511,
"s": 25484,
"text": "There are no memory leaks:"
},
{
"code": null,
"e": 25644,
"s": 25511,
"text": "Observers are tied to Lifecycle objects and clean up after themselves when the lifecycle with which they are connected is destroyed."
},
{
"code": null,
"e": 25711,
"s": 25644,
"text": "There have been no accidents as a result of activity being halted:"
},
{
"code": null,
"e": 26440,
"s": 25711,
"text": "If the observer’s lifetime is idle, like in the case of a back stack activity, it does not receive any LiveData events. LiveData just follows the observer design, and I don’t believe the above-mentioned use case warrants its own variant of the observable class. So, how can we resolve the dialogue issue? Rather than altering the behavior of LiveData, we should keep to the basics of the MVVM paradigm and, if necessary, have the ViewModel tell the ViewModel about the dismissed dialogue. Following that, the VM might reset or alter the status of the event. I realize it’s easy to forget to alert ViewModel, and we’re increasing View’s responsibilities. But, after all, it is the View’s job: to inform the VM of any user action."
},
{
"code": null,
"e": 26762,
"s": 26440,
"text": "Create an ‘Event’ class that is general (maybe call it LiveEvent). Give it observe(owner, observer) and observeForever functions (observer). Give it the same contract and functionality as LiveData. Except that, instead of a persistent value, the LiveEvent just notifies active observers while sending along with the data."
},
{
"code": null,
"e": 26769,
"s": 26762,
"text": "Kotlin"
},
{
"code": "class LiveEvent<C> {... fun sendingValue(data: C) { observers.forEach { gfg -> if (gfg.isActive()) gfg.onChanged(data) } }}",
"e": 26906,
"s": 26769,
"text": null
},
{
"code": null,
"e": 27145,
"s": 26906,
"text": "Put the LiveEvent in your basic ViewModel class if you want to utilize it for publishing notifications, SnackBars, or anything on many screens. Then, after initializing the ViewModel in your basic Fragment class, watch for that LiveEvent."
},
{
"code": null,
"e": 27152,
"s": 27145,
"text": "Kotlin"
},
{
"code": "abstract class GeeksforGeeksViewModel : ViewModel() { protected val fireAlertedEvent = LiveEvent<FireAlert>()}abstract class BaseFragment : Fragment() { fun onViewModelInitialized() { viewModel.fireAlertedEvent.observe(this, { fireAlert -> fireAlert.show() } }}class GeeksforGeeksSample : GeeksforGeeksViewModel() { fun onSaveSuccess() { fireAlertedEvent.postValue(FireAlert(\"yay! we got your stuff!\")) }}",
"e": 27577,
"s": 27152,
"text": null
},
{
"code": null,
"e": 27983,
"s": 27577,
"text": "The optimum solution would be an event source with automatic unsubscription on destruct that enqueues events as long as no watchers are present and then sends all events to the first observer that subscribes. That can handle the events in whatever way it deems fit. When you need to manage flow, using a callback with distinct success/failure methods is a terrible idea. Make use of an ADT (sealed class)."
},
{
"code": null,
"e": 27998,
"s": 27983,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 28005,
"s": 27998,
"text": "Picked"
},
{
"code": null,
"e": 28013,
"s": 28005,
"text": "Android"
},
{
"code": null,
"e": 28023,
"s": 28013,
"text": "Blogathon"
},
{
"code": null,
"e": 28030,
"s": 28023,
"text": "Kotlin"
},
{
"code": null,
"e": 28038,
"s": 28030,
"text": "Android"
},
{
"code": null,
"e": 28136,
"s": 28038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28145,
"s": 28136,
"text": "Comments"
},
{
"code": null,
"e": 28158,
"s": 28145,
"text": "Old Comments"
},
{
"code": null,
"e": 28197,
"s": 28158,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28247,
"s": 28197,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 28285,
"s": 28247,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 28336,
"s": 28285,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 28378,
"s": 28336,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28430,
"s": 28378,
"text": "How to Call or Consume External API in Spring Boot?"
},
{
"code": null,
"e": 28465,
"s": 28430,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 28499,
"s": 28465,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 28525,
"s": 28499,
"text": "Python NOT EQUAL operator"
}
] |
Aria2 - Multi-Protocol Command-Line Download Tool for Linux - GeeksforGeeks | 30 May, 2021
Aria2 is an open-source lightweight multi-protocol, multi-server & multi-source command-line utility that is used for downloading files in Windows, Linux, and Mac.
Aria2 is used to download a file at a good speed by utilizing your maximum download bandwidth from multiple sources/protocols such as HTTP(S), FTP, SFTP, Bittorrent, and Metalink. You can download a file from HTTP(S)/FTP/SFTP and BitTorrent at the same time, while the data downloaded from HTTP(S)/FTP/SFTP is uploaded to the BitTorrent swarm.
Aria2 can be used as an alternative to wget, curl or torrent clients as aria2 has few more advantages over these tools, because of greater download speed and the facility of pause and resume downloads.
Features:
LightweightBuilt-in JSON-RPC and XML-RPC interfaces can control the aria2 processAuto check of chunks of data s while downloading a file like BitTorrent using Metalink’s chunk checksumsHTTP Proxy authentication supportDownload a file from multiple sources/protocols by giving a better download experience
Lightweight
Built-in JSON-RPC and XML-RPC interfaces can control the aria2 process
Auto check of chunks of data s while downloading a file like BitTorrent using Metalink’s chunk checksums
HTTP Proxy authentication support
Download a file from multiple sources/protocols by giving a better download experience
In this article, we are going to discuss the installation process and usage of Aria2 tool in Debian/Ubuntu-based Linux Distros.
For installing Aria2 in Debian/Ubuntu systems, use the following command to install ‘aria2’:-
$ sudo apt-get install aria2
After you are done with installing the Aria2 tool on your system, now you need to learn how you can use this tool to download files. The following examples will help you understand how you can use this tool.
If you want to download a single file using either HTTP, HTTPS, or FTP protocol, then follow the following syntax:
$ aria2c <url of the file you want to download>
If you stop the download with Ctrl + C, or it gets interrupted, then the download gets paused, and again you can resume it using the same download command.
As you can see, we resumed the download again, and it started from where it had been paused and not from the beginning.
If you want to save the downloaded file with a different name and format then you can use the -o flag using the following syntax:
$ aria2 -o <the name you want to give to the file> <url of the file you want to download >
If you want to limit the download speed of a file while your internet is slow (as by default ‘aria2’ uses the full bandwidth to download a file) you can use the –max-download-limit option using the following syntax:
$ aria2 –max-download-limit=450K <url of the file you want to download>
Here we used 450k as a limit you can use some other limit according to your wish.
If you want to download multiple files at once use the following syntax:-
$ aria2 <” File 1 “> <“File2”> <“File3”>
You can download a file using more than one connection to each host by using the option -x2 (connection 2), although you can also give -x5 (connection 5). The syntax is as follows:
$ aria2 -x2 <URL of the file you want to download>
There are 2 ways you can download files from BitTorrent using aria2. They are as follows:
Method 1: Download a torrent file using aria2 by downloading the.torrent file to your system using the following syntax:
$ aria2c name.torrent
Method 2: By passing the link to the torrent file to aria2 using the following syntax:
$ aria2c https://example.com/filename.torrent
In this case, aria2 will first download the.torrent file to your current directory and then start downloading data, but if you do not want that aria2 to download that torrent file to your system’s current directory, and directly download the file, simply use the –follow-torrent=mem option. The syntax is as follows:
$ aria2c --follow-torrent=mem <torrent file url>
Files that contain all possible sources for data to be downloaded are called Metalinks(although aria2 uses multiple sources to pull the file from metalink). To download a file from Metalink use the following syntax:
$ aria2c http://example.com/filename.metalink
If you want to download a list of URL’s written in a text file where the URL‘s must contain one download per line, then you can use the following command:
$ aria2c -i filename.txt
If you want to know more about the usages and available options of aria2, then have a look over the manual of the aria2 tool.
$ man aria2c
Linux-Tools
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 24570,
"s": 24406,
"text": "Aria2 is an open-source lightweight multi-protocol, multi-server & multi-source command-line utility that is used for downloading files in Windows, Linux, and Mac."
},
{
"code": null,
"e": 24914,
"s": 24570,
"text": "Aria2 is used to download a file at a good speed by utilizing your maximum download bandwidth from multiple sources/protocols such as HTTP(S), FTP, SFTP, Bittorrent, and Metalink. You can download a file from HTTP(S)/FTP/SFTP and BitTorrent at the same time, while the data downloaded from HTTP(S)/FTP/SFTP is uploaded to the BitTorrent swarm."
},
{
"code": null,
"e": 25116,
"s": 24914,
"text": "Aria2 can be used as an alternative to wget, curl or torrent clients as aria2 has few more advantages over these tools, because of greater download speed and the facility of pause and resume downloads."
},
{
"code": null,
"e": 25126,
"s": 25116,
"text": "Features:"
},
{
"code": null,
"e": 25431,
"s": 25126,
"text": "LightweightBuilt-in JSON-RPC and XML-RPC interfaces can control the aria2 processAuto check of chunks of data s while downloading a file like BitTorrent using Metalink’s chunk checksumsHTTP Proxy authentication supportDownload a file from multiple sources/protocols by giving a better download experience"
},
{
"code": null,
"e": 25443,
"s": 25431,
"text": "Lightweight"
},
{
"code": null,
"e": 25514,
"s": 25443,
"text": "Built-in JSON-RPC and XML-RPC interfaces can control the aria2 process"
},
{
"code": null,
"e": 25619,
"s": 25514,
"text": "Auto check of chunks of data s while downloading a file like BitTorrent using Metalink’s chunk checksums"
},
{
"code": null,
"e": 25653,
"s": 25619,
"text": "HTTP Proxy authentication support"
},
{
"code": null,
"e": 25740,
"s": 25653,
"text": "Download a file from multiple sources/protocols by giving a better download experience"
},
{
"code": null,
"e": 25868,
"s": 25740,
"text": "In this article, we are going to discuss the installation process and usage of Aria2 tool in Debian/Ubuntu-based Linux Distros."
},
{
"code": null,
"e": 25962,
"s": 25868,
"text": "For installing Aria2 in Debian/Ubuntu systems, use the following command to install ‘aria2’:-"
},
{
"code": null,
"e": 25991,
"s": 25962,
"text": "$ sudo apt-get install aria2"
},
{
"code": null,
"e": 26199,
"s": 25991,
"text": "After you are done with installing the Aria2 tool on your system, now you need to learn how you can use this tool to download files. The following examples will help you understand how you can use this tool."
},
{
"code": null,
"e": 26314,
"s": 26199,
"text": "If you want to download a single file using either HTTP, HTTPS, or FTP protocol, then follow the following syntax:"
},
{
"code": null,
"e": 26363,
"s": 26314,
"text": "$ aria2c <url of the file you want to download>"
},
{
"code": null,
"e": 26519,
"s": 26363,
"text": "If you stop the download with Ctrl + C, or it gets interrupted, then the download gets paused, and again you can resume it using the same download command."
},
{
"code": null,
"e": 26639,
"s": 26519,
"text": "As you can see, we resumed the download again, and it started from where it had been paused and not from the beginning."
},
{
"code": null,
"e": 26769,
"s": 26639,
"text": "If you want to save the downloaded file with a different name and format then you can use the -o flag using the following syntax:"
},
{
"code": null,
"e": 26860,
"s": 26769,
"text": "$ aria2 -o <the name you want to give to the file> <url of the file you want to download >"
},
{
"code": null,
"e": 27076,
"s": 26860,
"text": "If you want to limit the download speed of a file while your internet is slow (as by default ‘aria2’ uses the full bandwidth to download a file) you can use the –max-download-limit option using the following syntax:"
},
{
"code": null,
"e": 27148,
"s": 27076,
"text": "$ aria2 –max-download-limit=450K <url of the file you want to download>"
},
{
"code": null,
"e": 27230,
"s": 27148,
"text": "Here we used 450k as a limit you can use some other limit according to your wish."
},
{
"code": null,
"e": 27304,
"s": 27230,
"text": "If you want to download multiple files at once use the following syntax:-"
},
{
"code": null,
"e": 27346,
"s": 27304,
"text": "$ aria2 <” File 1 “> <“File2”> <“File3”>"
},
{
"code": null,
"e": 27527,
"s": 27346,
"text": "You can download a file using more than one connection to each host by using the option -x2 (connection 2), although you can also give -x5 (connection 5). The syntax is as follows:"
},
{
"code": null,
"e": 27580,
"s": 27527,
"text": "$ aria2 -x2 <URL of the file you want to download>"
},
{
"code": null,
"e": 27670,
"s": 27580,
"text": "There are 2 ways you can download files from BitTorrent using aria2. They are as follows:"
},
{
"code": null,
"e": 27791,
"s": 27670,
"text": "Method 1: Download a torrent file using aria2 by downloading the.torrent file to your system using the following syntax:"
},
{
"code": null,
"e": 27813,
"s": 27791,
"text": "$ aria2c name.torrent"
},
{
"code": null,
"e": 27900,
"s": 27813,
"text": "Method 2: By passing the link to the torrent file to aria2 using the following syntax:"
},
{
"code": null,
"e": 27946,
"s": 27900,
"text": "$ aria2c https://example.com/filename.torrent"
},
{
"code": null,
"e": 28263,
"s": 27946,
"text": "In this case, aria2 will first download the.torrent file to your current directory and then start downloading data, but if you do not want that aria2 to download that torrent file to your system’s current directory, and directly download the file, simply use the –follow-torrent=mem option. The syntax is as follows:"
},
{
"code": null,
"e": 28312,
"s": 28263,
"text": "$ aria2c --follow-torrent=mem <torrent file url>"
},
{
"code": null,
"e": 28528,
"s": 28312,
"text": "Files that contain all possible sources for data to be downloaded are called Metalinks(although aria2 uses multiple sources to pull the file from metalink). To download a file from Metalink use the following syntax:"
},
{
"code": null,
"e": 28574,
"s": 28528,
"text": "$ aria2c http://example.com/filename.metalink"
},
{
"code": null,
"e": 28729,
"s": 28574,
"text": "If you want to download a list of URL’s written in a text file where the URL‘s must contain one download per line, then you can use the following command:"
},
{
"code": null,
"e": 28754,
"s": 28729,
"text": "$ aria2c -i filename.txt"
},
{
"code": null,
"e": 28880,
"s": 28754,
"text": "If you want to know more about the usages and available options of aria2, then have a look over the manual of the aria2 tool."
},
{
"code": null,
"e": 28893,
"s": 28880,
"text": "$ man aria2c"
},
{
"code": null,
"e": 28905,
"s": 28893,
"text": "Linux-Tools"
},
{
"code": null,
"e": 28912,
"s": 28905,
"text": "Picked"
},
{
"code": null,
"e": 28923,
"s": 28912,
"text": "Linux-Unix"
},
{
"code": null,
"e": 29021,
"s": 28923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29058,
"s": 29021,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 29093,
"s": 29058,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 29119,
"s": 29093,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 29153,
"s": 29119,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 29190,
"s": 29153,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 29219,
"s": 29190,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 29245,
"s": 29219,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 29285,
"s": 29245,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 29320,
"s": 29285,
"text": "Basic Operators in Shell Scripting"
}
] |
Minimize count of divisions by D to obtain at least K equal array elements - GeeksforGeeks | 17 Jul, 2021
Given an array A[ ] of size N and two integers K and D, the task is to calculate the minimum possible number of operations required to obtain at least K equal array elements. Each operation involves replacing an element A[i] by A[i] / D. This operation can be performed any number of times.
Examples:
Input: N = 5, A[ ] = {1, 2, 3, 4, 5}, K = 3, D = 2 Output: 2 Explanation: Step 1: Replace A[3] by A[3] / D, i.e. (4 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 5} Step 2: Replace A[4] by A[4] / D, i.e. (5 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 2} Hence, the modified array has K(= 3) equal elements. Hence, the minimum number of operations required is 2.
Input: N = 4, A[ ] = {1, 2, 3, 6}, K = 2, D = 3 Output: 1 Explanation:Replacing A[3] by A[3] / D, i.e. (6 / 3) = 2. Hence, the array modifies to {1, 2, 3, 2}. Hence, the modified array has K(= 2) equal elements. Hence, the minimum number of operations required is 1.
Naive Approach: The simplest approach to solve the problem is to generate every possible subset of the given array and perform the given operation on all elements of this subset. The number of operations required for each subset will be equal to the size of the subset. For each subset, count the number of equal elements and check if count is equal to K. If so, compare the then count with minimum moves obtained so far and update accordingly. Finally, print the minimum moves.
Time Complexity: O(2N *N) Auxiliary Space: O(N)
Efficient Approach: Follow the steps below to solve the problem:
Initialize a 2D vector V, in which, size of a row V[i] denotes the number of array elements that have been reduced to A[i] and every element of the row denotes a count of divisions by D performed on an array element to obtain the number i.
Traverse the array. For each element A[i], keep dividing it by D until it reduces to 0.
For each intermediate value of A[i] obtained in the above step, insert the number of divisions required into V[A[i]].
Once, the above steps are completed for the entire array, iterate over the array V[ ].
For each V[i], check if the size of V[i] ≥ K (at most K).
If V[i] ≥ K, it denotes that at least K elements in the array have been reduced to i. Sort V[i] and add the first K values, i.e. the smallest K moves required to make K elements equal in the array.
Compare the sum of K moves with the minimum moves required and update accordingly.
Once the traversal of the array V[] is completed, print the minimum count of moves obtained finally.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return minimum// number of moves requiredint getMinimumMoves(int n, int k, int d, vector<int> a){ int MAX = 100000; // Stores the number of moves // required to obtain respective // values from the given array vector<int> v[MAX]; // Traverse the array for (int i = 0; i < n; i++) { int cnt = 0; // Insert 0 into V[a[i]] as // it is the initial state v[a[i]].push_back(0); while (a[i] > 0) { a[i] /= d; cnt++; // Insert the moves required // to obtain current a[i] v[a[i]].push_back(cnt); } } int ans = INT_MAX; // Traverse v[] to obtain // minimum count of moves for (int i = 0; i < MAX; i++) { // Check if there are at least // K equal elements for v[i] if (v[i].size() >= k) { int move = 0; sort(v[i].begin(), v[i].end()); // Add the sum of minimum K moves for (int j = 0; j < k; j++) { move += v[i][j]; } // Update answer ans = min(ans, move); } } // Return the final answer return ans;} // Driver Codeint main(){ int N = 5, K = 3, D = 2; vector<int> A = { 1, 2, 3, 4, 5 }; cout << getMinimumMoves(N, K, D, A); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to return minimum// number of moves required@SuppressWarnings("unchecked")static int getMinimumMoves(int n, int k, int d, int[] a){ int MAX = 100000; // Stores the number of moves // required to obtain respective // values from the given array Vector<Integer> []v = new Vector[MAX]; for(int i = 0; i < v.length; i++) v[i] = new Vector<Integer>(); // Traverse the array for(int i = 0; i < n; i++) { int cnt = 0; // Insert 0 into V[a[i]] as // it is the initial state v[a[i]].add(0); while (a[i] > 0) { a[i] /= d; cnt++; // Insert the moves required // to obtain current a[i] v[a[i]].add(cnt); } } int ans = Integer.MAX_VALUE; // Traverse v[] to obtain // minimum count of moves for(int i = 0; i < MAX; i++) { // Check if there are at least // K equal elements for v[i] if (v[i].size() >= k) { int move = 0; Collections.sort(v[i]); // Add the sum of minimum K moves for(int j = 0; j < k; j++) { move += v[i].get(j); } // Update answer ans = Math.min(ans, move); } } // Return the final answer return ans;} // Driver Codepublic static void main(String[] args){ int N = 5, K = 3, D = 2; int []A = { 1, 2, 3, 4, 5 }; System.out.print(getMinimumMoves(N, K, D, A));}} // This code is contributed by Amit Katiyar
# Python3 program to implement# the above approach # Function to return minimum# number of moves requireddef getMinimumMoves(n, k, d, a): MAX = 100000 # Stores the number of moves # required to obtain respective # values from the given array v = [] for i in range(MAX): v.append([]) # Traverse the array for i in range(n): cnt = 0 # Insert 0 into V[a[i]] as # it is the initial state v[a[i]] += [0] while(a[i] > 0): a[i] //= d cnt += 1 # Insert the moves required # to obtain current a[i] v[a[i]] += [cnt] ans = float('inf') # Traverse v[] to obtain # minimum count of moves for i in range(MAX): # Check if there are at least # K equal elements for v[i] if(len(v[i]) >= k): move = 0 v[i].sort() # Add the sum of minimum K moves for j in range(k): move += v[i][j] # Update answer ans = min(ans, move) # Return the final answer return ans # Driver Codeif __name__ == '__main__': N = 5 K = 3 D = 2 A = [ 1, 2, 3, 4, 5 ] # Function call print(getMinimumMoves(N, K, D, A)) # This code is contributed by Shivam Singh
// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return minimum// number of moves required static int getMinimumMoves(int n, int k, int d, int[] a){ int MAX = 100000; // Stores the number of moves // required to obtain respective // values from the given array List<int> []v = new List<int>[MAX]; for(int i = 0; i < v.Length; i++) v[i] = new List<int>(); // Traverse the array for(int i = 0; i < n; i++) { int cnt = 0; // Insert 0 into V[a[i]] as // it is the initial state v[a[i]].Add(0); while (a[i] > 0) { a[i] /= d; cnt++; // Insert the moves required // to obtain current a[i] v[a[i]].Add(cnt); } } int ans = int.MaxValue; // Traverse v[] to obtain // minimum count of moves for(int i = 0; i < MAX; i++) { // Check if there are at least // K equal elements for v[i] if (v[i].Count >= k) { int move = 0; v[i].Sort(); // Add the sum of minimum K moves for(int j = 0; j < k; j++) { move += v[i][j]; } // Update answer ans = Math.Min(ans, move); } } // Return the final answer return ans;} // Driver Codepublic static void Main(String[] args){ int N = 5, K = 3, D = 2; int []A = { 1, 2, 3, 4, 5 }; Console.Write(getMinimumMoves(N, K, D, A));}} // This code is contributed by 29AjayKumar
2
Time Complexity: O(MlogM), where M is the maximum number taken Auxiliary Space: O(M)
SHIVAMSINGH67
amit143katiyar
29AjayKumar
the_raw_coder
saurabh1990aror
cpp-vector
frequency-counting
subset
Arrays
Mathematical
Matrix
Searching
Sorting
Arrays
Searching
Mathematical
Sorting
Matrix
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Linear Search
Python | Using 2D arrays/lists the right way
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": 24611,
"s": 24583,
"text": "\n17 Jul, 2021"
},
{
"code": null,
"e": 24902,
"s": 24611,
"text": "Given an array A[ ] of size N and two integers K and D, the task is to calculate the minimum possible number of operations required to obtain at least K equal array elements. Each operation involves replacing an element A[i] by A[i] / D. This operation can be performed any number of times."
},
{
"code": null,
"e": 24913,
"s": 24902,
"text": "Examples: "
},
{
"code": null,
"e": 25289,
"s": 24913,
"text": "Input: N = 5, A[ ] = {1, 2, 3, 4, 5}, K = 3, D = 2 Output: 2 Explanation: Step 1: Replace A[3] by A[3] / D, i.e. (4 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 5} Step 2: Replace A[4] by A[4] / D, i.e. (5 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 2} Hence, the modified array has K(= 3) equal elements. Hence, the minimum number of operations required is 2."
},
{
"code": null,
"e": 25557,
"s": 25289,
"text": "Input: N = 4, A[ ] = {1, 2, 3, 6}, K = 2, D = 3 Output: 1 Explanation:Replacing A[3] by A[3] / D, i.e. (6 / 3) = 2. Hence, the array modifies to {1, 2, 3, 2}. Hence, the modified array has K(= 2) equal elements. Hence, the minimum number of operations required is 1. "
},
{
"code": null,
"e": 26036,
"s": 25557,
"text": "Naive Approach: The simplest approach to solve the problem is to generate every possible subset of the given array and perform the given operation on all elements of this subset. The number of operations required for each subset will be equal to the size of the subset. For each subset, count the number of equal elements and check if count is equal to K. If so, compare the then count with minimum moves obtained so far and update accordingly. Finally, print the minimum moves."
},
{
"code": null,
"e": 26084,
"s": 26036,
"text": "Time Complexity: O(2N *N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 26150,
"s": 26084,
"text": "Efficient Approach: Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 26390,
"s": 26150,
"text": "Initialize a 2D vector V, in which, size of a row V[i] denotes the number of array elements that have been reduced to A[i] and every element of the row denotes a count of divisions by D performed on an array element to obtain the number i."
},
{
"code": null,
"e": 26478,
"s": 26390,
"text": "Traverse the array. For each element A[i], keep dividing it by D until it reduces to 0."
},
{
"code": null,
"e": 26596,
"s": 26478,
"text": "For each intermediate value of A[i] obtained in the above step, insert the number of divisions required into V[A[i]]."
},
{
"code": null,
"e": 26683,
"s": 26596,
"text": "Once, the above steps are completed for the entire array, iterate over the array V[ ]."
},
{
"code": null,
"e": 26741,
"s": 26683,
"text": "For each V[i], check if the size of V[i] ≥ K (at most K)."
},
{
"code": null,
"e": 26939,
"s": 26741,
"text": "If V[i] ≥ K, it denotes that at least K elements in the array have been reduced to i. Sort V[i] and add the first K values, i.e. the smallest K moves required to make K elements equal in the array."
},
{
"code": null,
"e": 27022,
"s": 26939,
"text": "Compare the sum of K moves with the minimum moves required and update accordingly."
},
{
"code": null,
"e": 27123,
"s": 27022,
"text": "Once the traversal of the array V[] is completed, print the minimum count of moves obtained finally."
},
{
"code": null,
"e": 27174,
"s": 27123,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27178,
"s": 27174,
"text": "C++"
},
{
"code": null,
"e": 27183,
"s": 27178,
"text": "Java"
},
{
"code": null,
"e": 27191,
"s": 27183,
"text": "Python3"
},
{
"code": null,
"e": 27194,
"s": 27191,
"text": "C#"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return minimum// number of moves requiredint getMinimumMoves(int n, int k, int d, vector<int> a){ int MAX = 100000; // Stores the number of moves // required to obtain respective // values from the given array vector<int> v[MAX]; // Traverse the array for (int i = 0; i < n; i++) { int cnt = 0; // Insert 0 into V[a[i]] as // it is the initial state v[a[i]].push_back(0); while (a[i] > 0) { a[i] /= d; cnt++; // Insert the moves required // to obtain current a[i] v[a[i]].push_back(cnt); } } int ans = INT_MAX; // Traverse v[] to obtain // minimum count of moves for (int i = 0; i < MAX; i++) { // Check if there are at least // K equal elements for v[i] if (v[i].size() >= k) { int move = 0; sort(v[i].begin(), v[i].end()); // Add the sum of minimum K moves for (int j = 0; j < k; j++) { move += v[i][j]; } // Update answer ans = min(ans, move); } } // Return the final answer return ans;} // Driver Codeint main(){ int N = 5, K = 3, D = 2; vector<int> A = { 1, 2, 3, 4, 5 }; cout << getMinimumMoves(N, K, D, A); return 0;}",
"e": 28636,
"s": 27194,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to return minimum// number of moves required@SuppressWarnings(\"unchecked\")static int getMinimumMoves(int n, int k, int d, int[] a){ int MAX = 100000; // Stores the number of moves // required to obtain respective // values from the given array Vector<Integer> []v = new Vector[MAX]; for(int i = 0; i < v.length; i++) v[i] = new Vector<Integer>(); // Traverse the array for(int i = 0; i < n; i++) { int cnt = 0; // Insert 0 into V[a[i]] as // it is the initial state v[a[i]].add(0); while (a[i] > 0) { a[i] /= d; cnt++; // Insert the moves required // to obtain current a[i] v[a[i]].add(cnt); } } int ans = Integer.MAX_VALUE; // Traverse v[] to obtain // minimum count of moves for(int i = 0; i < MAX; i++) { // Check if there are at least // K equal elements for v[i] if (v[i].size() >= k) { int move = 0; Collections.sort(v[i]); // Add the sum of minimum K moves for(int j = 0; j < k; j++) { move += v[i].get(j); } // Update answer ans = Math.min(ans, move); } } // Return the final answer return ans;} // Driver Codepublic static void main(String[] args){ int N = 5, K = 3, D = 2; int []A = { 1, 2, 3, 4, 5 }; System.out.print(getMinimumMoves(N, K, D, A));}} // This code is contributed by Amit Katiyar",
"e": 30300,
"s": 28636,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to return minimum# number of moves requireddef getMinimumMoves(n, k, d, a): MAX = 100000 # Stores the number of moves # required to obtain respective # values from the given array v = [] for i in range(MAX): v.append([]) # Traverse the array for i in range(n): cnt = 0 # Insert 0 into V[a[i]] as # it is the initial state v[a[i]] += [0] while(a[i] > 0): a[i] //= d cnt += 1 # Insert the moves required # to obtain current a[i] v[a[i]] += [cnt] ans = float('inf') # Traverse v[] to obtain # minimum count of moves for i in range(MAX): # Check if there are at least # K equal elements for v[i] if(len(v[i]) >= k): move = 0 v[i].sort() # Add the sum of minimum K moves for j in range(k): move += v[i][j] # Update answer ans = min(ans, move) # Return the final answer return ans # Driver Codeif __name__ == '__main__': N = 5 K = 3 D = 2 A = [ 1, 2, 3, 4, 5 ] # Function call print(getMinimumMoves(N, K, D, A)) # This code is contributed by Shivam Singh",
"e": 31584,
"s": 30300,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return minimum// number of moves required static int getMinimumMoves(int n, int k, int d, int[] a){ int MAX = 100000; // Stores the number of moves // required to obtain respective // values from the given array List<int> []v = new List<int>[MAX]; for(int i = 0; i < v.Length; i++) v[i] = new List<int>(); // Traverse the array for(int i = 0; i < n; i++) { int cnt = 0; // Insert 0 into V[a[i]] as // it is the initial state v[a[i]].Add(0); while (a[i] > 0) { a[i] /= d; cnt++; // Insert the moves required // to obtain current a[i] v[a[i]].Add(cnt); } } int ans = int.MaxValue; // Traverse v[] to obtain // minimum count of moves for(int i = 0; i < MAX; i++) { // Check if there are at least // K equal elements for v[i] if (v[i].Count >= k) { int move = 0; v[i].Sort(); // Add the sum of minimum K moves for(int j = 0; j < k; j++) { move += v[i][j]; } // Update answer ans = Math.Min(ans, move); } } // Return the final answer return ans;} // Driver Codepublic static void Main(String[] args){ int N = 5, K = 3, D = 2; int []A = { 1, 2, 3, 4, 5 }; Console.Write(getMinimumMoves(N, K, D, A));}} // This code is contributed by 29AjayKumar",
"e": 33210,
"s": 31584,
"text": null
},
{
"code": null,
"e": 33212,
"s": 33210,
"text": "2"
},
{
"code": null,
"e": 33298,
"s": 33212,
"text": "Time Complexity: O(MlogM), where M is the maximum number taken Auxiliary Space: O(M) "
},
{
"code": null,
"e": 33312,
"s": 33298,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 33327,
"s": 33312,
"text": "amit143katiyar"
},
{
"code": null,
"e": 33339,
"s": 33327,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33353,
"s": 33339,
"text": "the_raw_coder"
},
{
"code": null,
"e": 33369,
"s": 33353,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 33380,
"s": 33369,
"text": "cpp-vector"
},
{
"code": null,
"e": 33399,
"s": 33380,
"text": "frequency-counting"
},
{
"code": null,
"e": 33406,
"s": 33399,
"text": "subset"
},
{
"code": null,
"e": 33413,
"s": 33406,
"text": "Arrays"
},
{
"code": null,
"e": 33426,
"s": 33413,
"text": "Mathematical"
},
{
"code": null,
"e": 33433,
"s": 33426,
"text": "Matrix"
},
{
"code": null,
"e": 33443,
"s": 33433,
"text": "Searching"
},
{
"code": null,
"e": 33451,
"s": 33443,
"text": "Sorting"
},
{
"code": null,
"e": 33458,
"s": 33451,
"text": "Arrays"
},
{
"code": null,
"e": 33468,
"s": 33458,
"text": "Searching"
},
{
"code": null,
"e": 33481,
"s": 33468,
"text": "Mathematical"
},
{
"code": null,
"e": 33489,
"s": 33481,
"text": "Sorting"
},
{
"code": null,
"e": 33496,
"s": 33489,
"text": "Matrix"
},
{
"code": null,
"e": 33503,
"s": 33496,
"text": "subset"
},
{
"code": null,
"e": 33601,
"s": 33503,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33610,
"s": 33601,
"text": "Comments"
},
{
"code": null,
"e": 33623,
"s": 33610,
"text": "Old Comments"
},
{
"code": null,
"e": 33671,
"s": 33623,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33703,
"s": 33671,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33757,
"s": 33703,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 33771,
"s": 33757,
"text": "Linear Search"
},
{
"code": null,
"e": 33816,
"s": 33771,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 33846,
"s": 33816,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33861,
"s": 33846,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33904,
"s": 33861,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 33923,
"s": 33904,
"text": "Coin Change | DP-7"
}
] |
How to Install JUnit Libraries on Linux? - GeeksforGeeks | 22 Sep, 2021
JUnit is basically a unit testing framework for Java. JAVA provides a JUnit framework for unit testing, unit testing is simply a process by which we ensure that the code works the way it was intended to, i.e. we check individual units of source code, such as functions, methods, and class. And normally we just test everything that could reasonably break. The JUnit helps us to run and write repeatable automated tests. The latest version of JUnit is JUnit 5
Follow the below steps to install JUnit libraries using the apt install command:
Step 1: Open up the terminal and run the following command to update your current system.
sudo apt update
sudo apt upgrade
Step 2: Now we are going to install a package manager called “aptitude”. After that, run the following command to install JUnit.
sudo apt install aptitude
Step 3: After installing aptitude run the following command to install JUnit.
sudo aptitude install junit
To remove JUnit run the following command:
sudo aptitude remove junit
Note: If above method doesn’t work for your system you can try the method 2.
To download the JUnit follow the below steps:
Step 1: Open up the terminal and run the following command to download the JUnit.zip.
wget https://sourceforge.net/projects/junit/files/junit/4.10/junit4.10.zip
downloading junit.zip
Step 2: Move this junit file to another folder called JUnit and unzipping the file.
Making directory for JUnit using the below command:
mkdir JUnit
Move junit4.10.zip to the new folder, JUnit with the below command:
mv junit4.10.zip /home/amninder/Downloads/JUnit/
Unzip the file using the below command:
unzip junit4.10.zip
Now, make sure you are in Download/JUnit folder.
Step 3: Navigate to the junit folder and copy the junit-4.10.jar path to the environment variable by running the following commands:
export JUNIT_HOME=/home/amninder/Downloads/JUnit/junit4.10
Step 4: Set the JUnit class path and export the new JUnit-4.10.jar path to the environment variable by running the following commands:
Command 1:
export CLASSPATH=$JUNIT_HOME/junit-4.10.jar
Here, $JUNIT_HOME indicates that we are accessing the value of JUNIT_HOME from the previous step 3.
Command 2:
export CLASSPATH=/home/amninder/Downloads/JUnit/junit4.10/junit-4.10.jar
Both the above commands from step 3 are serving the same purpose. We can use any of them, but not both.
At this point, the JUnit is successfully installed.
To check if the JUnit is correctly installed run the following command:
java org.junit.runner.JUnitCore junit.tests.AllTests
Note: To uninstall JUnit simply delete the folder where you have pasted the JUnit jar file and it will remove the JUnit from the system.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
SQL Query to Create Table With a Primary Key
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to Align Text in HTML?
How to install Jupyter Notebook on Windows?
How to Install OpenCV for Python on Windows? | [
{
"code": null,
"e": 24812,
"s": 24784,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 25272,
"s": 24812,
"text": "JUnit is basically a unit testing framework for Java. JAVA provides a JUnit framework for unit testing, unit testing is simply a process by which we ensure that the code works the way it was intended to, i.e. we check individual units of source code, such as functions, methods, and class. And normally we just test everything that could reasonably break. The JUnit helps us to run and write repeatable automated tests. The latest version of JUnit is JUnit 5"
},
{
"code": null,
"e": 25353,
"s": 25272,
"text": "Follow the below steps to install JUnit libraries using the apt install command:"
},
{
"code": null,
"e": 25444,
"s": 25353,
"text": " Step 1: Open up the terminal and run the following command to update your current system."
},
{
"code": null,
"e": 25477,
"s": 25444,
"text": "sudo apt update\nsudo apt upgrade"
},
{
"code": null,
"e": 25606,
"s": 25477,
"text": "Step 2: Now we are going to install a package manager called “aptitude”. After that, run the following command to install JUnit."
},
{
"code": null,
"e": 25632,
"s": 25606,
"text": "sudo apt install aptitude"
},
{
"code": null,
"e": 25710,
"s": 25632,
"text": "Step 3: After installing aptitude run the following command to install JUnit."
},
{
"code": null,
"e": 25738,
"s": 25710,
"text": "sudo aptitude install junit"
},
{
"code": null,
"e": 25781,
"s": 25738,
"text": "To remove JUnit run the following command:"
},
{
"code": null,
"e": 25808,
"s": 25781,
"text": "sudo aptitude remove junit"
},
{
"code": null,
"e": 25886,
"s": 25808,
"text": "Note: If above method doesn’t work for your system you can try the method 2."
},
{
"code": null,
"e": 25932,
"s": 25886,
"text": "To download the JUnit follow the below steps:"
},
{
"code": null,
"e": 26018,
"s": 25932,
"text": "Step 1: Open up the terminal and run the following command to download the JUnit.zip."
},
{
"code": null,
"e": 26093,
"s": 26018,
"text": "wget https://sourceforge.net/projects/junit/files/junit/4.10/junit4.10.zip"
},
{
"code": null,
"e": 26115,
"s": 26093,
"text": "downloading junit.zip"
},
{
"code": null,
"e": 26199,
"s": 26115,
"text": "Step 2: Move this junit file to another folder called JUnit and unzipping the file."
},
{
"code": null,
"e": 26252,
"s": 26199,
"text": " Making directory for JUnit using the below command:"
},
{
"code": null,
"e": 26264,
"s": 26252,
"text": "mkdir JUnit"
},
{
"code": null,
"e": 26332,
"s": 26264,
"text": "Move junit4.10.zip to the new folder, JUnit with the below command:"
},
{
"code": null,
"e": 26381,
"s": 26332,
"text": "mv junit4.10.zip /home/amninder/Downloads/JUnit/"
},
{
"code": null,
"e": 26421,
"s": 26381,
"text": "Unzip the file using the below command:"
},
{
"code": null,
"e": 26441,
"s": 26421,
"text": "unzip junit4.10.zip"
},
{
"code": null,
"e": 26490,
"s": 26441,
"text": "Now, make sure you are in Download/JUnit folder."
},
{
"code": null,
"e": 26625,
"s": 26490,
"text": " Step 3: Navigate to the junit folder and copy the junit-4.10.jar path to the environment variable by running the following commands:"
},
{
"code": null,
"e": 26684,
"s": 26625,
"text": "export JUNIT_HOME=/home/amninder/Downloads/JUnit/junit4.10"
},
{
"code": null,
"e": 26819,
"s": 26684,
"text": "Step 4: Set the JUnit class path and export the new JUnit-4.10.jar path to the environment variable by running the following commands:"
},
{
"code": null,
"e": 26830,
"s": 26819,
"text": "Command 1:"
},
{
"code": null,
"e": 26874,
"s": 26830,
"text": "export CLASSPATH=$JUNIT_HOME/junit-4.10.jar"
},
{
"code": null,
"e": 26974,
"s": 26874,
"text": "Here, $JUNIT_HOME indicates that we are accessing the value of JUNIT_HOME from the previous step 3."
},
{
"code": null,
"e": 26985,
"s": 26974,
"text": "Command 2:"
},
{
"code": null,
"e": 27058,
"s": 26985,
"text": "export CLASSPATH=/home/amninder/Downloads/JUnit/junit4.10/junit-4.10.jar"
},
{
"code": null,
"e": 27162,
"s": 27058,
"text": "Both the above commands from step 3 are serving the same purpose. We can use any of them, but not both."
},
{
"code": null,
"e": 27214,
"s": 27162,
"text": "At this point, the JUnit is successfully installed."
},
{
"code": null,
"e": 27287,
"s": 27214,
"text": " To check if the JUnit is correctly installed run the following command:"
},
{
"code": null,
"e": 27340,
"s": 27287,
"text": "java org.junit.runner.JUnitCore junit.tests.AllTests"
},
{
"code": null,
"e": 27477,
"s": 27340,
"text": "Note: To uninstall JUnit simply delete the folder where you have pasted the JUnit jar file and it will remove the JUnit from the system."
},
{
"code": null,
"e": 27492,
"s": 27477,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27507,
"s": 27492,
"text": "how-to-install"
},
{
"code": null,
"e": 27514,
"s": 27507,
"text": "Picked"
},
{
"code": null,
"e": 27524,
"s": 27514,
"text": "Blogathon"
},
{
"code": null,
"e": 27531,
"s": 27524,
"text": "How To"
},
{
"code": null,
"e": 27550,
"s": 27531,
"text": "Installation Guide"
},
{
"code": null,
"e": 27648,
"s": 27550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27689,
"s": 27648,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27746,
"s": 27689,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27781,
"s": 27746,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27819,
"s": 27781,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 27864,
"s": 27819,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 27896,
"s": 27864,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27949,
"s": 27896,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 27976,
"s": 27949,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 28020,
"s": 27976,
"text": "How to install Jupyter Notebook on Windows?"
}
] |
Build predictive Business Intelligence with Google Colab, Google Data Studio and Google Sheets | by Rostyslav Neskorozhenyi | Towards Data Science | Many of us are used to thinking that Business Intelligence is something that large companies use and that is created with tools that are expensive and often difficult to learn (although there are pleasant exceptions, such as Metabase and Superset). In my article, I want to show that practically everyone can use the power of Business Intelligence, and even add some Predictive Analytics to it with generally available and free online tools, such as Google Colab and Google Data Studio. Database deployment is not required. All data for analysis and visualization we will store in Google Sheets.
We will implement a machine learning model in Google Colab and, based on the sales history of the products, we will be able to predict future sales for several months and visualize our prediction in Google Data Studio.
We will use the dataset with information about the list of products and the sales history for 12 months for each product.
The model will analyze the sales history and changes in product features for each month, so that any change will dynamically affect the model predictions. This will allow us to quickly assess the consequences of certain decisions and adopt an optimal development strategy.
We consider, that all operations we do in Google Colab. First of all we will use kaggle module to download needed dataset. You can read in more detail about module and how to get Kaggle API Token by this link.
Dataset description: https://www.kaggle.com/c/online-sales/data .
!pip install kaggle
As we are using Google Colab, we will connect to Google Drive to copy Kaggle credentials.
from google.colab import drivedrive.mount(‘/content/drive/’)
Set a working directory with saved credentials (in our case directory is called “Colab Notebooks”).
import osos.chdir(“/content/drive/My Drive/Colab Notebooks”)
Copy credentials for Kaggle API.
import osos.chdir(“/content/drive/My Drive/Colab Notebooks”)
Download the dataset.
!kaggle competitions download -c online-sales
Load the dataset into the memory and replace null values with zeroes.
import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltdf = pd.read_csv(“TrainingDataset.csv”)df = df.replace(np.nan, 0, regex=True)
Now we can preview our dataset.
We will split our dataset into the training part (on which we will train our model) and the test part (on which we will test the correctness of our model).
from sklearn.model_selection import train_test_splitdf_train, df_test = train_test_split(df, test_size=0.2)print(df_train.shape)print(df_test.shape)
Let’s visualize our data. We will show the price change dynamics for 10 random products.
import randomindexes = random.sample(range(len(df)), 10)df_plot = pd.DataFrame()for i in indexes: df_plot[“product_”+str(i)] = df.iloc[i, 0:12]df_plot.plot();
As we see, sales are declining throughout the year in most cases.
We need to prepare our data in a special way to load into our model. We will build a model that forecasts future month outcome based on previous values. For each month model will analyze product features and information about previous month outcome.
Firstly, we will separate product features and information about outcome per month.
y_train_real = df_train.iloc[:, 0:12].valuesprint(y_train_real.shape)y_test_real = df_test.iloc[:, 0:12].valuesprint(y_test_real.shape)x_train_real = df_train.iloc[:, 12:].valuesx_test_real = df_test.iloc[:, 12:].valuesprint(x_train_real.shape)print(x_test_real.shape)
Scale values in one range for better predictions.
from sklearn.preprocessing import MinMaxScaler#scale datasetsx_scaler = MinMaxScaler()x_scaler = x_scaler.fit(x_train_real)x_train = x_scaler.transform(x_train_real)x_test = x_scaler.transform(x_test_real)y_scaler = MinMaxScaler()y_scaler = y_scaler.fit(y_train_real)y_train = y_scaler.transform(y_train_real)y_test = y_scaler.transform(y_test_real)
Now let us move to the most important step of this process: convert price history to multidimensional time series. For each product we will create TimeSeries with 1–12 timesteps with information about product features and previous timestep outcome. We do not know previous outcome for first timestep, so we will just take zero.
Here we create lists for training and test data, each list will contain 12 3-dimensional numpy arrays. Second dimension for each array will represent timesteps and gradually increases by 1.
x_train_series = []x_test_series = []for k in range(len(y_train[0])): x_train_series.append(np.zeros((x_train.shape[0], k+1, x_train.shape[1]+1)))for k in range(len(y_test[0])): x_test_series.append(np.zeros((x_test.shape[0], k+1, x_test.shape[1]+1)))
Add to each timestep information about product features and previous timestep outcome. Now we are using the same product features for each timestep, but the model allows to track features changes on each timestep to make more accurate predictions.
for k in range(len(y_train[0])): for i in range(len(x_train)): for j in range(k + 1): shifted_index = j - 1 if shifted_index < 0: x_train_series[k][i, j] = np.append(x_train[i], 0) else: x_train_series[k][i, j] = np.append(x_train[i], y_train[i, shifted_index])
The same timesteps conversion for test data.
for k in range(len(y_test[0])): for i in range(len(x_test)): for j in range(k + 1): shifted_index = j - 1 if shifted_index < 0: x_test_series[k][i, j] = np.append(x_test[i], 0) else: x_test_series[k][i, j] = np.append(x_test[i], y_test[i, shifted_index])
Make 12 lists with information about outcome per TimeSerie, per product.
y_train_series = []y_test_series = []for k in range(len(y_train[0])): y_train_series.append(np.zeros((len(y_train), 1))) y_test_series.append(np.zeros((len(y_test), 1))) for k in range(len(y_train[0])): y_train_series[k] = y_train[:, k].reshape(-1, 1) y_test_series[k] = y_test[:, k].reshape(-1, 1)
We will use long short term memory (LSTM) network of the Recurrent neural network (RNN). You can read more about these types of NN here:
http://colah.github.io/posts/2015-08-Understanding-LSTMs/
We use Keras framework for deep learning. Our model consists of just one LSTM layer with 256 units, one Dense layer with 128 units and the densely connected output layer with one neuron. We also added one Dropout layer to avoid overfitting. Model stays simple and quick, still able to make useful predictions.
from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTMfrom keras.layers import Dropoutmodel = Sequential()model.add(LSTM(256, input_shape=(None, x_train.shape[1]+1)))model.add(Dropout(0.5))model.add(Dense(128, activation = "relu"))model.add(Dense(1))model.summary()
model.compile(loss='mse', optimizer='rmsprop')
Train our model :
for i in range(len(x_train_series)): print(i) model.fit(x_train_series[i], y_train_series[i], epochs=10, validation_split=0.2)
Evaluate model for prediction of outcome after several months.
for i in range(len(x_test_series)): accr = model.evaluate(x_test_series[i], y_test_series[i]) print("Predicting outcome after {} months. MSE:".format(i), accr)
We will use our model to create a recursive function that will take information about product features and outcome history during several months. As a result this function will predict future outcome for as many months as you wish.
def predictor(features, history, future): ''' features: list of product features history: list with outcome per month future: int, number of months to predict outcome ''' if future == 0: return history p_serie = np.zeros((1, len(history), len(features)+1)) for j in range(len(history)): shifted_index = j - 1 if shifted_index < 0: p_serie[0, j] = np.append(features, 0) else: p_serie[0, j] = np.append(features, history[shifted_index]) prediction = model.predict(p_serie) history.append(prediction[0][0]) future -= 1 return predictor(features, history, future)
We will test our function on a random product n. We will create two lists. First with outcome history for first m months, second with product features
import randomn = random.choice(range(len(x_test)-1))m = 6future = 6features = x_test[n].tolist()history = y_test[n, 0:m].tolist()
Plot results of prediction comparing with real data
prediction = predictor(features, history, future)plt.plot(y_scaler.inverse_transform([prediction])[0])plt.plot(y_scaler.inverse_transform([y_test[n, :m+future]])[0])plt.title('Predicted and real outcome')plt.legend(['predicted', 'real'], loc='upper left')axes = plt.gca()plt.show()
As we can see it quite accurately showed sales change overall trend. Not bad result for a comparably simple model.
Now, when we have our predicted data, we can display it in Google Data Studio, a Google’s Business Intelligence solution. One of the advantages of this tool is that it can be used for free to make custom reports and dashboards.
Google Data Studio can connect multiple data sources for reporting. Google Sheets as data source is suitable for our purposes. We will save our predictions as a Google Sheet, and Google Data Studio will display the data from it on the dashbord. Thus, we can easily integrate Google Colaboratory and Data Studio.
I will not explain in detail Google Data Studio functionality. You can learn about it in the official documentation https://developers.google.com/datastudio/
We will take three random products, save predictions and outcome history for each. To save our data to Google Spreadsheet we will use gspread library.
Wee will need a client key to write on a Google Spreadsheet. How to get the key is described here https://gspread.readthedocs.io/en/latest/oauth2.html.
!pip install — upgrade oauth2client gspread
Connect to Google Sheets.
import gspreadfrom oauth2client.service_account import ServiceAccountCredentialsscope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']credentials = ServiceAccountCredentials.from_json_keyfile_name('spreadkey.json', scope)gc = gspread.authorize(credentials)
Make lists with real and predicted outcome history for three random products. For testing purposes we are using data from test dataset, but in real scenario you can insert any changes of product features in Google Sheets, load data from Google Sheets and make a prediction.
real_data = []predicted_data = []for i in range(3): n = random.choice(range(len(x_test)-1)) m = 6 future = 6 features = x_test[n].tolist() history = y_test[n, 0:m].tolist() prediction = predictor(features, history, future) predicted_data.append(y_scaler.inverse_transform([prediction])[0]) real_data.append(y_scaler.inverse_transform([y_test[n, :m+future]])[0])
Open Google Sheet for saving real and predicted data. We have two worksheets in it: “real” for real data, “predicted” for predicted data.
ws = gc.open('TrainingDataset2')ws_predicted = ws.worksheet("predicted")ws_real = ws.worksheet("real")
Write our real and predicted data to Google Sheets. We will write starting from the second row, reserving first row for column names(Product1, Product2, Product3).
for j in range(len(real_data)): for i in range(len(real_data[0])): ws_predicted.update_cell(i+2, j+1, float(predicted_data[j][i])) ws_real.update_cell(i+2, j+1, float(real_data[j][i])) for i in range(len(real_data[0])): # add index column ws_predicted.update_cell(i+2, len(real_data)+1, i) ws_real.update_cell(i+2, len(real_data)+1, i)
Review our data at Google Sheets
ws_real.get_all_records()[6:11]
As we have Google Sheets filled with real and predicted outcome, now we can connect Google Sheets as a datasource in Google Data Studio.
In Google Data Studio, create new dashboard and create a Data Source for it. You will find a Google Sheets in sources list. Add your Google Sheet as a data source.
Based on data from “predicted” and “real” worksheets we can make diagrams showing outcome change.
That’s it! Now you have AI Powered Dashboard, showing predictions about future outcome!
The main idea of this article is that Business Intelligence with even some AI features is more accessible than we can think. You can create advanced analytics, embed proposed graphs into your analytics reports and have an idea of both the current situation and the near future. All changes, that you want to check can be quickly inserted in Google Sheets, predicted consequences will be calculated in Google Colab and shown in Google Data Studio.
You can find Google Colab Notebook with all described code by this link. | [
{
"code": null,
"e": 768,
"s": 172,
"text": "Many of us are used to thinking that Business Intelligence is something that large companies use and that is created with tools that are expensive and often difficult to learn (although there are pleasant exceptions, such as Metabase and Superset). In my article, I want to show that practically everyone can use the power of Business Intelligence, and even add some Predictive Analytics to it with generally available and free online tools, such as Google Colab and Google Data Studio. Database deployment is not required. All data for analysis and visualization we will store in Google Sheets."
},
{
"code": null,
"e": 987,
"s": 768,
"text": "We will implement a machine learning model in Google Colab and, based on the sales history of the products, we will be able to predict future sales for several months and visualize our prediction in Google Data Studio."
},
{
"code": null,
"e": 1109,
"s": 987,
"text": "We will use the dataset with information about the list of products and the sales history for 12 months for each product."
},
{
"code": null,
"e": 1382,
"s": 1109,
"text": "The model will analyze the sales history and changes in product features for each month, so that any change will dynamically affect the model predictions. This will allow us to quickly assess the consequences of certain decisions and adopt an optimal development strategy."
},
{
"code": null,
"e": 1592,
"s": 1382,
"text": "We consider, that all operations we do in Google Colab. First of all we will use kaggle module to download needed dataset. You can read in more detail about module and how to get Kaggle API Token by this link."
},
{
"code": null,
"e": 1658,
"s": 1592,
"text": "Dataset description: https://www.kaggle.com/c/online-sales/data ."
},
{
"code": null,
"e": 1678,
"s": 1658,
"text": "!pip install kaggle"
},
{
"code": null,
"e": 1768,
"s": 1678,
"text": "As we are using Google Colab, we will connect to Google Drive to copy Kaggle credentials."
},
{
"code": null,
"e": 1829,
"s": 1768,
"text": "from google.colab import drivedrive.mount(‘/content/drive/’)"
},
{
"code": null,
"e": 1929,
"s": 1829,
"text": "Set a working directory with saved credentials (in our case directory is called “Colab Notebooks”)."
},
{
"code": null,
"e": 1990,
"s": 1929,
"text": "import osos.chdir(“/content/drive/My Drive/Colab Notebooks”)"
},
{
"code": null,
"e": 2023,
"s": 1990,
"text": "Copy credentials for Kaggle API."
},
{
"code": null,
"e": 2084,
"s": 2023,
"text": "import osos.chdir(“/content/drive/My Drive/Colab Notebooks”)"
},
{
"code": null,
"e": 2106,
"s": 2084,
"text": "Download the dataset."
},
{
"code": null,
"e": 2152,
"s": 2106,
"text": "!kaggle competitions download -c online-sales"
},
{
"code": null,
"e": 2222,
"s": 2152,
"text": "Load the dataset into the memory and replace null values with zeroes."
},
{
"code": null,
"e": 2373,
"s": 2222,
"text": "import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltdf = pd.read_csv(“TrainingDataset.csv”)df = df.replace(np.nan, 0, regex=True)"
},
{
"code": null,
"e": 2405,
"s": 2373,
"text": "Now we can preview our dataset."
},
{
"code": null,
"e": 2561,
"s": 2405,
"text": "We will split our dataset into the training part (on which we will train our model) and the test part (on which we will test the correctness of our model)."
},
{
"code": null,
"e": 2710,
"s": 2561,
"text": "from sklearn.model_selection import train_test_splitdf_train, df_test = train_test_split(df, test_size=0.2)print(df_train.shape)print(df_test.shape)"
},
{
"code": null,
"e": 2799,
"s": 2710,
"text": "Let’s visualize our data. We will show the price change dynamics for 10 random products."
},
{
"code": null,
"e": 2959,
"s": 2799,
"text": "import randomindexes = random.sample(range(len(df)), 10)df_plot = pd.DataFrame()for i in indexes: df_plot[“product_”+str(i)] = df.iloc[i, 0:12]df_plot.plot();"
},
{
"code": null,
"e": 3025,
"s": 2959,
"text": "As we see, sales are declining throughout the year in most cases."
},
{
"code": null,
"e": 3275,
"s": 3025,
"text": "We need to prepare our data in a special way to load into our model. We will build a model that forecasts future month outcome based on previous values. For each month model will analyze product features and information about previous month outcome."
},
{
"code": null,
"e": 3359,
"s": 3275,
"text": "Firstly, we will separate product features and information about outcome per month."
},
{
"code": null,
"e": 3628,
"s": 3359,
"text": "y_train_real = df_train.iloc[:, 0:12].valuesprint(y_train_real.shape)y_test_real = df_test.iloc[:, 0:12].valuesprint(y_test_real.shape)x_train_real = df_train.iloc[:, 12:].valuesx_test_real = df_test.iloc[:, 12:].valuesprint(x_train_real.shape)print(x_test_real.shape)"
},
{
"code": null,
"e": 3678,
"s": 3628,
"text": "Scale values in one range for better predictions."
},
{
"code": null,
"e": 4028,
"s": 3678,
"text": "from sklearn.preprocessing import MinMaxScaler#scale datasetsx_scaler = MinMaxScaler()x_scaler = x_scaler.fit(x_train_real)x_train = x_scaler.transform(x_train_real)x_test = x_scaler.transform(x_test_real)y_scaler = MinMaxScaler()y_scaler = y_scaler.fit(y_train_real)y_train = y_scaler.transform(y_train_real)y_test = y_scaler.transform(y_test_real)"
},
{
"code": null,
"e": 4356,
"s": 4028,
"text": "Now let us move to the most important step of this process: convert price history to multidimensional time series. For each product we will create TimeSeries with 1–12 timesteps with information about product features and previous timestep outcome. We do not know previous outcome for first timestep, so we will just take zero."
},
{
"code": null,
"e": 4546,
"s": 4356,
"text": "Here we create lists for training and test data, each list will contain 12 3-dimensional numpy arrays. Second dimension for each array will represent timesteps and gradually increases by 1."
},
{
"code": null,
"e": 4800,
"s": 4546,
"text": "x_train_series = []x_test_series = []for k in range(len(y_train[0])): x_train_series.append(np.zeros((x_train.shape[0], k+1, x_train.shape[1]+1)))for k in range(len(y_test[0])): x_test_series.append(np.zeros((x_test.shape[0], k+1, x_test.shape[1]+1)))"
},
{
"code": null,
"e": 5048,
"s": 4800,
"text": "Add to each timestep information about product features and previous timestep outcome. Now we are using the same product features for each timestep, but the model allows to track features changes on each timestep to make more accurate predictions."
},
{
"code": null,
"e": 5343,
"s": 5048,
"text": "for k in range(len(y_train[0])): for i in range(len(x_train)): for j in range(k + 1): shifted_index = j - 1 if shifted_index < 0: x_train_series[k][i, j] = np.append(x_train[i], 0) else: x_train_series[k][i, j] = np.append(x_train[i], y_train[i, shifted_index])"
},
{
"code": null,
"e": 5388,
"s": 5343,
"text": "The same timesteps conversion for test data."
},
{
"code": null,
"e": 5676,
"s": 5388,
"text": "for k in range(len(y_test[0])): for i in range(len(x_test)): for j in range(k + 1): shifted_index = j - 1 if shifted_index < 0: x_test_series[k][i, j] = np.append(x_test[i], 0) else: x_test_series[k][i, j] = np.append(x_test[i], y_test[i, shifted_index])"
},
{
"code": null,
"e": 5749,
"s": 5676,
"text": "Make 12 lists with information about outcome per TimeSerie, per product."
},
{
"code": null,
"e": 6054,
"s": 5749,
"text": "y_train_series = []y_test_series = []for k in range(len(y_train[0])): y_train_series.append(np.zeros((len(y_train), 1))) y_test_series.append(np.zeros((len(y_test), 1))) for k in range(len(y_train[0])): y_train_series[k] = y_train[:, k].reshape(-1, 1) y_test_series[k] = y_test[:, k].reshape(-1, 1)"
},
{
"code": null,
"e": 6191,
"s": 6054,
"text": "We will use long short term memory (LSTM) network of the Recurrent neural network (RNN). You can read more about these types of NN here:"
},
{
"code": null,
"e": 6249,
"s": 6191,
"text": "http://colah.github.io/posts/2015-08-Understanding-LSTMs/"
},
{
"code": null,
"e": 6559,
"s": 6249,
"text": "We use Keras framework for deep learning. Our model consists of just one LSTM layer with 256 units, one Dense layer with 128 units and the densely connected output layer with one neuron. We also added one Dropout layer to avoid overfitting. Model stays simple and quick, still able to make useful predictions."
},
{
"code": null,
"e": 6865,
"s": 6559,
"text": "from keras.models import Sequentialfrom keras.layers import Densefrom keras.layers import LSTMfrom keras.layers import Dropoutmodel = Sequential()model.add(LSTM(256, input_shape=(None, x_train.shape[1]+1)))model.add(Dropout(0.5))model.add(Dense(128, activation = \"relu\"))model.add(Dense(1))model.summary()"
},
{
"code": null,
"e": 6912,
"s": 6865,
"text": "model.compile(loss='mse', optimizer='rmsprop')"
},
{
"code": null,
"e": 6930,
"s": 6912,
"text": "Train our model :"
},
{
"code": null,
"e": 7059,
"s": 6930,
"text": "for i in range(len(x_train_series)): print(i) model.fit(x_train_series[i], y_train_series[i], epochs=10, validation_split=0.2)"
},
{
"code": null,
"e": 7122,
"s": 7059,
"text": "Evaluate model for prediction of outcome after several months."
},
{
"code": null,
"e": 7284,
"s": 7122,
"text": "for i in range(len(x_test_series)): accr = model.evaluate(x_test_series[i], y_test_series[i]) print(\"Predicting outcome after {} months. MSE:\".format(i), accr)"
},
{
"code": null,
"e": 7516,
"s": 7284,
"text": "We will use our model to create a recursive function that will take information about product features and outcome history during several months. As a result this function will predict future outcome for as many months as you wish."
},
{
"code": null,
"e": 8135,
"s": 7516,
"text": "def predictor(features, history, future): ''' features: list of product features history: list with outcome per month future: int, number of months to predict outcome ''' if future == 0: return history p_serie = np.zeros((1, len(history), len(features)+1)) for j in range(len(history)): shifted_index = j - 1 if shifted_index < 0: p_serie[0, j] = np.append(features, 0) else: p_serie[0, j] = np.append(features, history[shifted_index]) prediction = model.predict(p_serie) history.append(prediction[0][0]) future -= 1 return predictor(features, history, future)"
},
{
"code": null,
"e": 8286,
"s": 8135,
"text": "We will test our function on a random product n. We will create two lists. First with outcome history for first m months, second with product features"
},
{
"code": null,
"e": 8416,
"s": 8286,
"text": "import randomn = random.choice(range(len(x_test)-1))m = 6future = 6features = x_test[n].tolist()history = y_test[n, 0:m].tolist()"
},
{
"code": null,
"e": 8468,
"s": 8416,
"text": "Plot results of prediction comparing with real data"
},
{
"code": null,
"e": 8750,
"s": 8468,
"text": "prediction = predictor(features, history, future)plt.plot(y_scaler.inverse_transform([prediction])[0])plt.plot(y_scaler.inverse_transform([y_test[n, :m+future]])[0])plt.title('Predicted and real outcome')plt.legend(['predicted', 'real'], loc='upper left')axes = plt.gca()plt.show()"
},
{
"code": null,
"e": 8865,
"s": 8750,
"text": "As we can see it quite accurately showed sales change overall trend. Not bad result for a comparably simple model."
},
{
"code": null,
"e": 9093,
"s": 8865,
"text": "Now, when we have our predicted data, we can display it in Google Data Studio, a Google’s Business Intelligence solution. One of the advantages of this tool is that it can be used for free to make custom reports and dashboards."
},
{
"code": null,
"e": 9405,
"s": 9093,
"text": "Google Data Studio can connect multiple data sources for reporting. Google Sheets as data source is suitable for our purposes. We will save our predictions as a Google Sheet, and Google Data Studio will display the data from it on the dashbord. Thus, we can easily integrate Google Colaboratory and Data Studio."
},
{
"code": null,
"e": 9563,
"s": 9405,
"text": "I will not explain in detail Google Data Studio functionality. You can learn about it in the official documentation https://developers.google.com/datastudio/"
},
{
"code": null,
"e": 9714,
"s": 9563,
"text": "We will take three random products, save predictions and outcome history for each. To save our data to Google Spreadsheet we will use gspread library."
},
{
"code": null,
"e": 9866,
"s": 9714,
"text": "Wee will need a client key to write on a Google Spreadsheet. How to get the key is described here https://gspread.readthedocs.io/en/latest/oauth2.html."
},
{
"code": null,
"e": 9910,
"s": 9866,
"text": "!pip install — upgrade oauth2client gspread"
},
{
"code": null,
"e": 9936,
"s": 9910,
"text": "Connect to Google Sheets."
},
{
"code": null,
"e": 10237,
"s": 9936,
"text": "import gspreadfrom oauth2client.service_account import ServiceAccountCredentialsscope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']credentials = ServiceAccountCredentials.from_json_keyfile_name('spreadkey.json', scope)gc = gspread.authorize(credentials)"
},
{
"code": null,
"e": 10511,
"s": 10237,
"text": "Make lists with real and predicted outcome history for three random products. For testing purposes we are using data from test dataset, but in real scenario you can insert any changes of product features in Google Sheets, load data from Google Sheets and make a prediction."
},
{
"code": null,
"e": 10881,
"s": 10511,
"text": "real_data = []predicted_data = []for i in range(3): n = random.choice(range(len(x_test)-1)) m = 6 future = 6 features = x_test[n].tolist() history = y_test[n, 0:m].tolist() prediction = predictor(features, history, future) predicted_data.append(y_scaler.inverse_transform([prediction])[0]) real_data.append(y_scaler.inverse_transform([y_test[n, :m+future]])[0])"
},
{
"code": null,
"e": 11019,
"s": 10881,
"text": "Open Google Sheet for saving real and predicted data. We have two worksheets in it: “real” for real data, “predicted” for predicted data."
},
{
"code": null,
"e": 11122,
"s": 11019,
"text": "ws = gc.open('TrainingDataset2')ws_predicted = ws.worksheet(\"predicted\")ws_real = ws.worksheet(\"real\")"
},
{
"code": null,
"e": 11286,
"s": 11122,
"text": "Write our real and predicted data to Google Sheets. We will write starting from the second row, reserving first row for column names(Product1, Product2, Product3)."
},
{
"code": null,
"e": 11649,
"s": 11286,
"text": "for j in range(len(real_data)): for i in range(len(real_data[0])): ws_predicted.update_cell(i+2, j+1, float(predicted_data[j][i])) ws_real.update_cell(i+2, j+1, float(real_data[j][i])) for i in range(len(real_data[0])): # add index column ws_predicted.update_cell(i+2, len(real_data)+1, i) ws_real.update_cell(i+2, len(real_data)+1, i)"
},
{
"code": null,
"e": 11682,
"s": 11649,
"text": "Review our data at Google Sheets"
},
{
"code": null,
"e": 11714,
"s": 11682,
"text": "ws_real.get_all_records()[6:11]"
},
{
"code": null,
"e": 11851,
"s": 11714,
"text": "As we have Google Sheets filled with real and predicted outcome, now we can connect Google Sheets as a datasource in Google Data Studio."
},
{
"code": null,
"e": 12015,
"s": 11851,
"text": "In Google Data Studio, create new dashboard and create a Data Source for it. You will find a Google Sheets in sources list. Add your Google Sheet as a data source."
},
{
"code": null,
"e": 12113,
"s": 12015,
"text": "Based on data from “predicted” and “real” worksheets we can make diagrams showing outcome change."
},
{
"code": null,
"e": 12201,
"s": 12113,
"text": "That’s it! Now you have AI Powered Dashboard, showing predictions about future outcome!"
},
{
"code": null,
"e": 12648,
"s": 12201,
"text": "The main idea of this article is that Business Intelligence with even some AI features is more accessible than we can think. You can create advanced analytics, embed proposed graphs into your analytics reports and have an idea of both the current situation and the near future. All changes, that you want to check can be quickly inserted in Google Sheets, predicted consequences will be calculated in Google Colab and shown in Google Data Studio."
}
] |
Android | Display multiplication table of a number - GeeksforGeeks | 07 Dec, 2021
Given a number, the task is to display the multiplication table of this number using the Android App.
Steps to build app:
STEP-1: Open activity_main.xml file and add TextView, EditText, and a Button
STEP-2: Assign ID to each component
STEP-3: Now, open up the MainActivity file and declare the variables.
STEP-4: Read the values entered in the EditText boxes using an id that has been set in the XML code above.
STEP-5: Add a click listener to the Add button
STEP-6: When the Add button has been clicked we need to Multiply the values and store it in Buffer
STEP-7: Then show the resultant output in the TextView by setting the buffer in the TextView.
Implementation:
Filename: activity_main.xml
XML
<!-- First make the layout file xml and add button, edit text, text view --> <?xml version="1.0" encoding="utf-8"?><android.support.constraint.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" tools:layout_editor_absoluteY="25dp"> <!-- Add the button for run table logic and print result--> <!-- give id "button"--> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="TABLE" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/editText" app:layout_constraintTop_toTopOf="parent" /> <!-- Text view for result view--> <!-- give the id TextView--> <TextView android:id="@+id/textView" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginBottom="18dp" android:layout_marginEnd="36dp" android:layout_marginLeft="36dp" android:layout_marginRight="36dp" android:layout_marginStart="36dp" android:textColor="@color/colorPrimary" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/editText" /> <!-- edit Text for take input from user--> <!-- give the id editText--> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:layout_marginEnd="9dp" android:layout_marginRight="9dp" android:layout_marginTop="16dp" android:ems="10" android:inputType="number" app:layout_constraintBottom_toTopOf="@+id/textView2" app:layout_constraintEnd_toStartOf="@+id/button" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="UnknownId" /></android.support.constraint.ConstraintLayout>
Filename: MainActivity.Java
Java
// Build the java logic for multiplication table// using button, text view, edit text package com.example.windows10.table; import android.app.Dialog;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // define the global variable // variable number1, number2 for input input number // Add_button, result textView EditText editText; Button button; TextView result; int ans = 0; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // by ID we can use each component // whose id is assigned in the XML file editText = (EditText)findViewById(R.id.editText); button = (Button)findViewById(R.id.button); result = (TextView)findViewById(R.id.textView); // set clickListener on button button.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: StringBuffer buffer = new StringBuffer(); int res; // get the input number from editText String fs = editText.getText().toString(); // convert it to integer int n = Integer.parseInt(fs); // build the logic for table for (int i = 1; i <= 10; i++) { ans = (i * n); buffer.append(n + " X " + i + " = " + ans + "\n\n"); } // set the buffer textview result.setText(buffer); break; } }}
Output:
kapoorsagar226
surindertarika1234
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Overriding in Java | [
{
"code": null,
"e": 24527,
"s": 24499,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 24629,
"s": 24527,
"text": "Given a number, the task is to display the multiplication table of this number using the Android App."
},
{
"code": null,
"e": 24649,
"s": 24629,
"text": "Steps to build app:"
},
{
"code": null,
"e": 24726,
"s": 24649,
"text": "STEP-1: Open activity_main.xml file and add TextView, EditText, and a Button"
},
{
"code": null,
"e": 24762,
"s": 24726,
"text": "STEP-2: Assign ID to each component"
},
{
"code": null,
"e": 24832,
"s": 24762,
"text": "STEP-3: Now, open up the MainActivity file and declare the variables."
},
{
"code": null,
"e": 24939,
"s": 24832,
"text": "STEP-4: Read the values entered in the EditText boxes using an id that has been set in the XML code above."
},
{
"code": null,
"e": 24986,
"s": 24939,
"text": "STEP-5: Add a click listener to the Add button"
},
{
"code": null,
"e": 25085,
"s": 24986,
"text": "STEP-6: When the Add button has been clicked we need to Multiply the values and store it in Buffer"
},
{
"code": null,
"e": 25179,
"s": 25085,
"text": "STEP-7: Then show the resultant output in the TextView by setting the buffer in the TextView."
},
{
"code": null,
"e": 25195,
"s": 25179,
"text": "Implementation:"
},
{
"code": null,
"e": 25223,
"s": 25195,
"text": "Filename: activity_main.xml"
},
{
"code": null,
"e": 25227,
"s": 25223,
"text": "XML"
},
{
"code": "<!-- First make the layout file xml and add button, edit text, text view --> <?xml version=\"1.0\" encoding=\"utf-8\"?><android.support.constraint.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\" tools:layout_editor_absoluteY=\"25dp\"> <!-- Add the button for run table logic and print result--> <!-- give id \"button\"--> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"TABLE\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toEndOf=\"@+id/editText\" app:layout_constraintTop_toTopOf=\"parent\" /> <!-- Text view for result view--> <!-- give the id TextView--> <TextView android:id=\"@+id/textView\" android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:layout_marginBottom=\"18dp\" android:layout_marginEnd=\"36dp\" android:layout_marginLeft=\"36dp\" android:layout_marginRight=\"36dp\" android:layout_marginStart=\"36dp\" android:textColor=\"@color/colorPrimary\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <!-- edit Text for take input from user--> <!-- give the id editText--> <EditText android:id=\"@+id/editText\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"20dp\" android:layout_marginEnd=\"9dp\" android:layout_marginRight=\"9dp\" android:layout_marginTop=\"16dp\" android:ems=\"10\" android:inputType=\"number\" app:layout_constraintBottom_toTopOf=\"@+id/textView2\" app:layout_constraintEnd_toStartOf=\"@+id/button\" app:layout_constraintHorizontal_chainStyle=\"packed\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" tools:ignore=\"UnknownId\" /></android.support.constraint.ConstraintLayout>",
"e": 27598,
"s": 25227,
"text": null
},
{
"code": null,
"e": 27626,
"s": 27598,
"text": "Filename: MainActivity.Java"
},
{
"code": null,
"e": 27631,
"s": 27626,
"text": "Java"
},
{
"code": "// Build the java logic for multiplication table// using button, text view, edit text package com.example.windows10.table; import android.app.Dialog;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // define the global variable // variable number1, number2 for input input number // Add_button, result textView EditText editText; Button button; TextView result; int ans = 0; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // by ID we can use each component // whose id is assigned in the XML file editText = (EditText)findViewById(R.id.editText); button = (Button)findViewById(R.id.button); result = (TextView)findViewById(R.id.textView); // set clickListener on button button.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: StringBuffer buffer = new StringBuffer(); int res; // get the input number from editText String fs = editText.getText().toString(); // convert it to integer int n = Integer.parseInt(fs); // build the logic for table for (int i = 1; i <= 10; i++) { ans = (i * n); buffer.append(n + \" X \" + i + \" = \" + ans + \"\\n\\n\"); } // set the buffer textview result.setText(buffer); break; } }}",
"e": 29472,
"s": 27631,
"text": null
},
{
"code": null,
"e": 29481,
"s": 29472,
"text": "Output: "
},
{
"code": null,
"e": 29498,
"s": 29483,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 29517,
"s": 29498,
"text": "surindertarika1234"
},
{
"code": null,
"e": 29525,
"s": 29517,
"text": "android"
},
{
"code": null,
"e": 29530,
"s": 29525,
"text": "Java"
},
{
"code": null,
"e": 29535,
"s": 29530,
"text": "Java"
},
{
"code": null,
"e": 29633,
"s": 29535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29665,
"s": 29633,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29716,
"s": 29665,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29746,
"s": 29716,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29765,
"s": 29746,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29783,
"s": 29765,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29814,
"s": 29783,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29846,
"s": 29814,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29866,
"s": 29846,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29890,
"s": 29866,
"text": "Singleton Class in Java"
}
] |
EJB - Access Database | In EJB 3.0, persistence mechanism is used to access the database in which the container manages the database related operations. Developers can access database using JDBC API call directly in EJB business methods.
To demonstrate database access in EJB, we need to perform the following tasks −
Step 1 − Create a table in the database.
Step 1 − Create a table in the database.
Step 2 − Create a stateless EJB having business me.
Step 2 − Create a stateless EJB having business me.
Step 3 − Update stateless EJB. Add methods to add records and get records from database via entity manager.
Step 3 − Update stateless EJB. Add methods to add records and get records from database via entity manager.
Step 4 − A console based application client will access the stateless EJB to persist data in database.
Step 4 − A console based application client will access the stateless EJB to persist data in database.
Create a table books in default database postgres.
CREATE TABLE books (
id integer PRIMARY KEY,
name varchar(50)
);
public class Book implements Serializable{
private int id;
private String name;
public Book() {
}
public int getId() {
return id;
}
...
}
@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
public void addBook(Book book) {
//persist book using jdbc calls
}
public List<Book> getBooks() {
//get books using jdbc calls
}
...
}
After building the EJB module, we need a client to access the stateless bean, which we will be going to create in the next section.
Let us create a test EJB application to test EJB database access mechanism.
Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. You can also use the project created in EJB - Create Application chapter as such for this chapter to understand EJB data access concepts.
Create Book.java under package com.tutorialspoint.entity and modify it as shown below.
Create LibraryPersistentBean.java and LibraryPersistentBeanRemote as explained in the EJB - Create Application chapter and modify them as shown below.
Clean and Build the application to make sure business logic is working as per the requirements.
Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB. Modify it as shown below.
package com.tutorialspoint.entity;
import java.io.Serializable;
public class Book implements Serializable{
private int id;
private String name;
public Book() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.tutorialspoint.stateless;
import com.tutorialspoint.entity.Book;
import java.util.List;
import javax.ejb.Remote;
@Remote
public interface LibraryPersistentBeanRemote {
void addBook(Book bookName);
List<Book> getBooks();
}
package com.tutorialspoint.stateless;
import com.tutorialspoint.entity.Book;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
public LibraryPersistentBean() {
}
public void addBook(Book book) {
Connection con = null;
String url = "jdbc:postgresql://localhost:5432/postgres";
String driver = "org.postgresql.driver";
String userName = "sa";
String password = "sa";
List<Book> books = new ArrayList<Book>();
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url , userName, password);
PreparedStatement st =
con.prepareStatement("insert into book(name) values(?)");
st.setString(1,book.getName());
int result = st.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
public List<Book> getBooks() {
Connection con = null;
String url = "jdbc:postgresql://localhost:5432/postgres";
String driver = "org.postgresql.driver";
String userName = "sa";
String password = "sa";
List<Book> books = new ArrayList<Book>();
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url , userName, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from book");
Book book;
while (rs.next()) {
book = new Book();
book.setId(rs.getInt(1));
book.setName(rs.getString(2));
books.add(book);
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return books;
}
}
As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log.
As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log.
JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote.
JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote.
We will be using this lookup string to get remote business object of type −
com.tutorialspoint.stateless.LibraryPersistentBeanRemote
We will be using this lookup string to get remote business object of type −
com.tutorialspoint.stateless.LibraryPersistentBeanRemote
...
16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBeanRemote,service=EJB3
16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean
16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
...
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
These properties are used to initialize the InitialContext object of java naming service.
These properties are used to initialize the InitialContext object of java naming service.
InitialContext object will be used to lookup stateless session bean.
InitialContext object will be used to lookup stateless session bean.
package com.tutorialspoint.test;
import com.tutorialspoint.stateless.LibraryPersistentBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EJBTester {
BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;
{
props = new Properties();
try {
props.load(new FileInputStream("jndi.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {
ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
EJBTester ejbTester = new EJBTester();
ejbTester.testEntityEjb();
}
private void showGUI() {
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
}
private void testEntityEjb() {
try {
int choice = 1;
LibraryPersistentBeanRemote libraryBean =
LibraryPersistentBeanRemote)
ctx.lookup("LibraryPersistentBean/remote");
while (choice != 2) {
String bookName;
showGUI();
String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if (choice == 1) {
System.out.print("Enter book name: ");
bookName = brConsoleReader.readLine();
Book book = new Book();
book.setName(bookName);
libraryBean.addBook(book);
} else if (choice == 2) {
break;
}
}
List<Book> booksList = libraryBean.getBooks();
System.out.println("Book(s) entered so far: " + booksList.size());
int i = 0;
for (Book book:booksList) {
System.out.println((i+1)+". " + book.getName());
i++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}finally {
try {
if(brConsoleReader !=null) {
brConsoleReader.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
EJBTester performs the following tasks −
Load properties from jndi.properties and initialize the InitialContext object.
Load properties from jndi.properties and initialize the InitialContext object.
In testStatefulEjb() method, jndi lookup is done with the name - "LibraryStatelessSessionBean/remote" to obtain the remote business object (stateful EJB).
In testStatefulEjb() method, jndi lookup is done with the name - "LibraryStatelessSessionBean/remote" to obtain the remote business object (stateful EJB).
Then user is shown a library store User Interface and he/she is asked to enter a choice.
Then user is shown a library store User Interface and he/she is asked to enter a choice.
If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is persisting the book in database via EntityManager call.
If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is persisting the book in database via EntityManager call.
If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits.
If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits.
Then another jndi lookup is done with the name - "LibraryStatelessSessionBean/remote" to obtain the remote business object (stateful EJB) again and listing of books is done.
Then another jndi lookup is done with the name - "LibraryStatelessSessionBean/remote" to obtain the remote business object (stateful EJB) again and listing of books is done.
Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file.
Verify the following output in Netbeans console.
run:
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 1
Enter book name: Learn Java
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 2
Book(s) entered so far: 1
1. learn java
BUILD SUCCESSFUL (total time: 15 seconds)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2261,
"s": 2047,
"text": "In EJB 3.0, persistence mechanism is used to access the database in which the container manages the database related operations. Developers can access database using JDBC API call directly in EJB business methods."
},
{
"code": null,
"e": 2341,
"s": 2261,
"text": "To demonstrate database access in EJB, we need to perform the following tasks −"
},
{
"code": null,
"e": 2382,
"s": 2341,
"text": "Step 1 − Create a table in the database."
},
{
"code": null,
"e": 2423,
"s": 2382,
"text": "Step 1 − Create a table in the database."
},
{
"code": null,
"e": 2475,
"s": 2423,
"text": "Step 2 − Create a stateless EJB having business me."
},
{
"code": null,
"e": 2527,
"s": 2475,
"text": "Step 2 − Create a stateless EJB having business me."
},
{
"code": null,
"e": 2635,
"s": 2527,
"text": "Step 3 − Update stateless EJB. Add methods to add records and get records from database via entity manager."
},
{
"code": null,
"e": 2743,
"s": 2635,
"text": "Step 3 − Update stateless EJB. Add methods to add records and get records from database via entity manager."
},
{
"code": null,
"e": 2846,
"s": 2743,
"text": "Step 4 − A console based application client will access the stateless EJB to persist data in database."
},
{
"code": null,
"e": 2949,
"s": 2846,
"text": "Step 4 − A console based application client will access the stateless EJB to persist data in database."
},
{
"code": null,
"e": 3000,
"s": 2949,
"text": "Create a table books in default database postgres."
},
{
"code": null,
"e": 3077,
"s": 3000,
"text": "CREATE TABLE books (\n id integer PRIMARY KEY,\n name varchar(50)\n);"
},
{
"code": null,
"e": 3260,
"s": 3077,
"text": "public class Book implements Serializable{\n \n private int id;\n private String name;\n\n public Book() { \n }\n \n public int getId() {\n return id;\n }\n ...\n}"
},
{
"code": null,
"e": 3522,
"s": 3260,
"text": "@Stateless\npublic class LibraryPersistentBean implements LibraryPersistentBeanRemote {\n\t\n public void addBook(Book book) {\n //persist book using jdbc calls\n } \n\n public List<Book> getBooks() { \n //get books using jdbc calls\n }\n ...\n}"
},
{
"code": null,
"e": 3654,
"s": 3522,
"text": "After building the EJB module, we need a client to access the stateless bean, which we will be going to create in the next section."
},
{
"code": null,
"e": 3730,
"s": 3654,
"text": "Let us create a test EJB application to test EJB database access mechanism."
},
{
"code": null,
"e": 4006,
"s": 3730,
"text": "Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. You can also use the project created in EJB - Create Application chapter as such for this chapter to understand EJB data access concepts."
},
{
"code": null,
"e": 4093,
"s": 4006,
"text": "Create Book.java under package com.tutorialspoint.entity and modify it as shown below."
},
{
"code": null,
"e": 4244,
"s": 4093,
"text": "Create LibraryPersistentBean.java and LibraryPersistentBeanRemote as explained in the EJB - Create Application chapter and modify them as shown below."
},
{
"code": null,
"e": 4340,
"s": 4244,
"text": "Clean and Build the application to make sure business logic is working as per the requirements."
},
{
"code": null,
"e": 4507,
"s": 4340,
"text": "Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet."
},
{
"code": null,
"e": 4698,
"s": 4507,
"text": "Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB. Modify it as shown below."
},
{
"code": null,
"e": 5123,
"s": 4698,
"text": "package com.tutorialspoint.entity;\n\nimport java.io.Serializable;\n\npublic class Book implements Serializable{\n \n private int id;\n private String name;\n\n public Book() { \n }\n \n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n } \n}"
},
{
"code": null,
"e": 5372,
"s": 5123,
"text": "package com.tutorialspoint.stateless;\n\nimport com.tutorialspoint.entity.Book;\nimport java.util.List;\nimport javax.ejb.Remote;\n\n@Remote\npublic interface LibraryPersistentBeanRemote {\n\n void addBook(Book bookName);\n\n List<Book> getBooks();\n \n}"
},
{
"code": null,
"e": 7841,
"s": 5372,
"text": "package com.tutorialspoint.stateless;\n\nimport com.tutorialspoint.entity.Book;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.ejb.Stateless;\n\n@Stateless\npublic class LibraryPersistentBean implements LibraryPersistentBeanRemote {\n \n public LibraryPersistentBean() {\n }\n\n public void addBook(Book book) {\n Connection con = null;\n String url = \"jdbc:postgresql://localhost:5432/postgres\";\n String driver = \"org.postgresql.driver\";\n\n String userName = \"sa\";\n String password = \"sa\";\n List<Book> books = new ArrayList<Book>();\n try {\n\n Class.forName(driver).newInstance();\n con = DriverManager.getConnection(url , userName, password);\n\n PreparedStatement st = \n con.prepareStatement(\"insert into book(name) values(?)\");\n st.setString(1,book.getName());\n\n int result = st.executeUpdate(); \n\n } catch (SQLException ex) {\n ex.printStackTrace();\n } catch (InstantiationException ex) {\n ex.printStackTrace();\n } catch (IllegalAccessException ex) {\n ex.printStackTrace();\n } catch (ClassNotFoundException ex) {\n ex.printStackTrace();\n } \n } \n\n public List<Book> getBooks() {\n Connection con = null;\n String url = \"jdbc:postgresql://localhost:5432/postgres\";\n String driver = \"org.postgresql.driver\";\n \n String userName = \"sa\";\n String password = \"sa\";\n List<Book> books = new ArrayList<Book>();\n try {\n\n Class.forName(driver).newInstance();\n con = DriverManager.getConnection(url , userName, password);\n\n Statement st = con.createStatement();\n ResultSet rs = st.executeQuery(\"select * from book\");\n\n Book book;\n while (rs.next()) {\n book = new Book();\n book.setId(rs.getInt(1)); \n book.setName(rs.getString(2));\n books.add(book);\n }\n } catch (SQLException ex) {\n ex.printStackTrace();\n } catch (InstantiationException ex) {\n ex.printStackTrace();\n } catch (IllegalAccessException ex) {\n ex.printStackTrace();\n } catch (ClassNotFoundException ex) {\n ex.printStackTrace();\n }\n return books;\n }\n}\n"
},
{
"code": null,
"e": 7920,
"s": 7841,
"text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log."
},
{
"code": null,
"e": 7999,
"s": 7920,
"text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log."
},
{
"code": null,
"e": 8097,
"s": 7999,
"text": "JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote."
},
{
"code": null,
"e": 8195,
"s": 8097,
"text": "JBoss has automatically created a JNDI entry for our session bean - LibraryPersistentBean/remote."
},
{
"code": null,
"e": 8328,
"s": 8195,
"text": "We will be using this lookup string to get remote business object of type −\ncom.tutorialspoint.stateless.LibraryPersistentBeanRemote"
},
{
"code": null,
"e": 8461,
"s": 8328,
"text": "We will be using this lookup string to get remote business object of type −\ncom.tutorialspoint.stateless.LibraryPersistentBeanRemote"
},
{
"code": null,
"e": 9320,
"s": 8461,
"text": "...\n16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface\n LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface\n16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBeanRemote,service=EJB3\n16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean\n16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n\n LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface\n LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface\n... \n"
},
{
"code": null,
"e": 9488,
"s": 9320,
"text": "java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory\njava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces\njava.naming.provider.url=localhost"
},
{
"code": null,
"e": 9578,
"s": 9488,
"text": "These properties are used to initialize the InitialContext object of java naming service."
},
{
"code": null,
"e": 9668,
"s": 9578,
"text": "These properties are used to initialize the InitialContext object of java naming service."
},
{
"code": null,
"e": 9737,
"s": 9668,
"text": "InitialContext object will be used to lookup stateless session bean."
},
{
"code": null,
"e": 9806,
"s": 9737,
"text": "InitialContext object will be used to lookup stateless session bean."
},
{
"code": null,
"e": 12487,
"s": 9806,
"text": "package com.tutorialspoint.test;\n \nimport com.tutorialspoint.stateless.LibraryPersistentBeanRemote;\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.List;\nimport java.util.Properties;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\n\npublic class EJBTester {\n\n BufferedReader brConsoleReader = null; \n Properties props;\n InitialContext ctx;\n {\n props = new Properties();\n try {\n props.load(new FileInputStream(\"jndi.properties\"));\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n try {\n ctx = new InitialContext(props); \n } catch (NamingException ex) {\n ex.printStackTrace();\n }\n brConsoleReader = \n new BufferedReader(new InputStreamReader(System.in));\n }\n \n public static void main(String[] args) {\n\n EJBTester ejbTester = new EJBTester();\n\n ejbTester.testEntityEjb();\n }\n \n private void showGUI() {\n System.out.println(\"**********************\");\n System.out.println(\"Welcome to Book Store\");\n System.out.println(\"**********************\");\n System.out.print(\"Options \\n1. Add Book\\n2. Exit \\nEnter Choice: \");\n }\n \n private void testEntityEjb() {\n\n try {\n int choice = 1; \n\n LibraryPersistentBeanRemote libraryBean =\n LibraryPersistentBeanRemote)\n ctx.lookup(\"LibraryPersistentBean/remote\");\n\n while (choice != 2) {\n String bookName;\n showGUI();\n String strChoice = brConsoleReader.readLine();\n choice = Integer.parseInt(strChoice);\n if (choice == 1) {\n System.out.print(\"Enter book name: \");\n bookName = brConsoleReader.readLine();\n Book book = new Book();\n book.setName(bookName);\n libraryBean.addBook(book); \n } else if (choice == 2) {\n break;\n }\n }\n\n List<Book> booksList = libraryBean.getBooks();\n\n System.out.println(\"Book(s) entered so far: \" + booksList.size());\n int i = 0;\n for (Book book:booksList) {\n System.out.println((i+1)+\". \" + book.getName());\n i++;\n } \n } catch (Exception e) {\n System.out.println(e.getMessage());\n e.printStackTrace();\n }finally {\n try {\n if(brConsoleReader !=null) {\n brConsoleReader.close();\n }\n } catch (IOException ex) {\n System.out.println(ex.getMessage());\n }\n }\n }\n}"
},
{
"code": null,
"e": 12528,
"s": 12487,
"text": "EJBTester performs the following tasks −"
},
{
"code": null,
"e": 12607,
"s": 12528,
"text": "Load properties from jndi.properties and initialize the InitialContext object."
},
{
"code": null,
"e": 12686,
"s": 12607,
"text": "Load properties from jndi.properties and initialize the InitialContext object."
},
{
"code": null,
"e": 12841,
"s": 12686,
"text": "In testStatefulEjb() method, jndi lookup is done with the name - \"LibraryStatelessSessionBean/remote\" to obtain the remote business object (stateful EJB)."
},
{
"code": null,
"e": 12996,
"s": 12841,
"text": "In testStatefulEjb() method, jndi lookup is done with the name - \"LibraryStatelessSessionBean/remote\" to obtain the remote business object (stateful EJB)."
},
{
"code": null,
"e": 13085,
"s": 12996,
"text": "Then user is shown a library store User Interface and he/she is asked to enter a choice."
},
{
"code": null,
"e": 13174,
"s": 13085,
"text": "Then user is shown a library store User Interface and he/she is asked to enter a choice."
},
{
"code": null,
"e": 13364,
"s": 13174,
"text": "If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is persisting the book in database via EntityManager call."
},
{
"code": null,
"e": 13554,
"s": 13364,
"text": "If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is persisting the book in database via EntityManager call."
},
{
"code": null,
"e": 13661,
"s": 13554,
"text": "If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits."
},
{
"code": null,
"e": 13768,
"s": 13661,
"text": "If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits."
},
{
"code": null,
"e": 13942,
"s": 13768,
"text": "Then another jndi lookup is done with the name - \"LibraryStatelessSessionBean/remote\" to obtain the remote business object (stateful EJB) again and listing of books is done."
},
{
"code": null,
"e": 14116,
"s": 13942,
"text": "Then another jndi lookup is done with the name - \"LibraryStatelessSessionBean/remote\" to obtain the remote business object (stateful EJB) again and listing of books is done."
},
{
"code": null,
"e": 14211,
"s": 14116,
"text": "Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file."
},
{
"code": null,
"e": 14260,
"s": 14211,
"text": "Verify the following output in Netbeans console."
},
{
"code": null,
"e": 14604,
"s": 14260,
"text": "run:\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 1\nEnter book name: Learn Java\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 2\nBook(s) entered so far: 1\n1. learn java\nBUILD SUCCESSFUL (total time: 15 seconds)\n"
},
{
"code": null,
"e": 14611,
"s": 14604,
"text": " Print"
},
{
"code": null,
"e": 14622,
"s": 14611,
"text": " Add Notes"
}
] |
Introduction to Best Parallel Plot Python Library: “HiPlot” | by Moto DEI | Towards Data Science | HiPlot is Facebook’s Python library to support visualization of high-dimensional data table, released this January. It is particularly well known for its sophisticated interactive parallel plot.
Before anything, take a look at their compelling demo video. This explains how high its interactivity is, which we would appreciate when we do EDA.
, and play around their demo app with sample data here. Do not forget to select the range on axis and hold-and-move to check the interactivity.
HiPlot is not just good looking, but also has following four appreciated characteristics:
Very easy to implement
Implementing the parallel plot using their hiplot module is literally by one line and almost a no-brainer.
Highly interactive
As you can see in the demo video above, the plot is highly interactive. Giving some mouse clicks lets you deep dive to any subset of data.
Run fast
Despite its appearance, the runtime to visualize the large dataset as a parallel plot is short. Let’s see this later.
Native HTML rendering function
They prepared a native function to turn the parallel plot to HTML code (hooray!!) Produced HTML page can be downloaded as .html file or deployed from Flask with almost no additional rendering effort. I tried to run it on heroku through Flask in the exercise below.
Thanks to these benefits, I believe HiPlot is one of first-choice tool sets for EDA in data analysis project before jumping in other time-consuming visualizations.
Let’s take a look at each of the benefits one by one.
Let’s see how easy it is to get you started with HiPlot using the famous iris data set.
Installation of HiPlot is just as easy as ordinary modules. Just use pip:
pip install -U hiplot
To use external csv file, you even do not have to use Pandas DataFrame. They prepared a native method to run parallel plot directly from csv file as such Experiment.from_csv(). When you need to use DataFrame, use Experiment.from_dataframe() instead. And it is totally fine to use Jupyter Notebook.
import hiplot as hipiris_hiplot = hip.Experiment.from_csv('iris.csv')iris_hiplot.display()
And here’s what you will see:
You are going to love HiPlot once you start playing around.
As you already saw in the demo movie above, here are some examples of the uses of interactive chart.
To test the run time to show the parallel plot for larger data, I used Kaggle FIFA 19 complete player dataset. It is a dataset from a video game “FIFA 19”, as the name explains a game of soccer (or you may call football), where you can play as a team manager of a actual soccer team or as an actual soccer player. The dataset contains the all playable characters list with their skill levels (e.g. how good they are at heading, free kick etc.) The number of rows is 18,207 and of columns is 89. The first row is Messi from Argentina.
To do the performance test, I intentionally make the data size 10 times larger. I concatenated the FAFA 19 dataset 10 times, ended up with having 182,070 rows. Usually, visualizing large data set takes time to run and causes huge latency after the chart shows up. Interactivity? Forget and rerun the script! What about HiPlot?
I ran HiPlot on 182,070 rows x 89 columns dataset without any edits. It took 81 seconds to process and additional 5 mins to display the graph. I think it is short enough for its size.
fifa = pd.read_csv('fifa19_data.csv',index_col='Unnamed: 0')fifa_extended = pd.concat([fifa,fifa,fifa,fifa,fifa,fifa,fifa,fifa,fifa,fifa],axis=0,ignore_index=True,sort=False)fifa_hiplot = hip.Experiment.from_dataframe(fifa_extended)fifa_hiplot.display()
What is even greater about HiPlot is that data size does not harm its interactivity too much. After selecting the range on axis, it tries to show only the plots belonging to the range. This change re-renders the plot almost within a second, which is surprising quick compared to other visualization tools.
When we want to share the plot with someone else, we may run the code on notebook and copy-and-paste the plot, but it removes the graph interactivity.
HiPlot has its native HTML rendering function Experience.to_html(), which returns HTML file with the plot embedded with just one line of code.
Let me go with the original rows and fewer columns from FIFA 19 dataset for simplicity.
fifa = pd.read_csv('fifa19_data.csv',index_col='Unnamed: 0')fifa_small = fifa[['Age','Nationality','Value','Height', 'Weight', 'Crossing', 'Finishing', 'HeadingAccuracy', 'ShortPassing', 'Volleys', 'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl', 'Acceleration']]fifa_hiplot = hip.Experiment.from_dataframe(fifa_small)fifa_hiplot.display()
This code will produce a new .html file on your local with the plot.
_ = fifa_hiplot.to_html("fifa_hiplot.html")
Now you can share the .html file directly with your team members to let them play around the plot.
Since Experience.to_html() returns html code, it’s even just easily connected to web server and deploy the plot externally.
Let me try it with Flask and Heroku. As I explained a lot here, I needed four files pushed to GitHub repository, to be synced with Heroku app.
fifa19_data.csv: FIFA19 dataset file.
hiplot_fifa.py: Python code to run and kick off Flask app.
import hiplot as hipimport pandas as pdfrom flask import Flaskapp = Flask(__name__)@app.route('/')def fifa_experiment(): fifa = pd.read_csv('fifa19_data.csv',index_col='Unnamed: 0') fifa_hiplot = hip.Experiment.from_dataframe(fifa[['Age','Nationality','Value','Height', 'Weight', 'Crossing','Finishing', 'HeadingAccuracy', 'ShortPassing', 'Volleys', 'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl', 'Acceleration']]) return fifa_hiplot.to_html()if __name__ == "__main__": app.run()
requirements.txt: a requirement file for Heroku to install the necessary modules.
gunicorn==19.9.0pandas==0.24.2hiplot==0.1.12Flask==1.1.1
Procfile: a start-up command for Heroku to run when it starts the app.
web: gunicorn hiplot_fifa:app
Sync the code files and make a set up on Heroku. Opening the web app gives the following HiPlot graph page, which is globally accessible through domain name.
In this post, I introduced the HiPlot the current best option of parallel plot to start EDA to take a look at the variable interaction overview.
It is easy to run, highly interactive, fast, and with much shareable through HTML file or code.
Although the data science projects definitely need further investigation such as looking at the shape of distribution of values, imputing the missing values etc, HiPlot would be a much help to start off the data preprocessing and understanding. | [
{
"code": null,
"e": 367,
"s": 172,
"text": "HiPlot is Facebook’s Python library to support visualization of high-dimensional data table, released this January. It is particularly well known for its sophisticated interactive parallel plot."
},
{
"code": null,
"e": 515,
"s": 367,
"text": "Before anything, take a look at their compelling demo video. This explains how high its interactivity is, which we would appreciate when we do EDA."
},
{
"code": null,
"e": 659,
"s": 515,
"text": ", and play around their demo app with sample data here. Do not forget to select the range on axis and hold-and-move to check the interactivity."
},
{
"code": null,
"e": 749,
"s": 659,
"text": "HiPlot is not just good looking, but also has following four appreciated characteristics:"
},
{
"code": null,
"e": 772,
"s": 749,
"text": "Very easy to implement"
},
{
"code": null,
"e": 879,
"s": 772,
"text": "Implementing the parallel plot using their hiplot module is literally by one line and almost a no-brainer."
},
{
"code": null,
"e": 898,
"s": 879,
"text": "Highly interactive"
},
{
"code": null,
"e": 1037,
"s": 898,
"text": "As you can see in the demo video above, the plot is highly interactive. Giving some mouse clicks lets you deep dive to any subset of data."
},
{
"code": null,
"e": 1046,
"s": 1037,
"text": "Run fast"
},
{
"code": null,
"e": 1164,
"s": 1046,
"text": "Despite its appearance, the runtime to visualize the large dataset as a parallel plot is short. Let’s see this later."
},
{
"code": null,
"e": 1195,
"s": 1164,
"text": "Native HTML rendering function"
},
{
"code": null,
"e": 1460,
"s": 1195,
"text": "They prepared a native function to turn the parallel plot to HTML code (hooray!!) Produced HTML page can be downloaded as .html file or deployed from Flask with almost no additional rendering effort. I tried to run it on heroku through Flask in the exercise below."
},
{
"code": null,
"e": 1624,
"s": 1460,
"text": "Thanks to these benefits, I believe HiPlot is one of first-choice tool sets for EDA in data analysis project before jumping in other time-consuming visualizations."
},
{
"code": null,
"e": 1678,
"s": 1624,
"text": "Let’s take a look at each of the benefits one by one."
},
{
"code": null,
"e": 1766,
"s": 1678,
"text": "Let’s see how easy it is to get you started with HiPlot using the famous iris data set."
},
{
"code": null,
"e": 1840,
"s": 1766,
"text": "Installation of HiPlot is just as easy as ordinary modules. Just use pip:"
},
{
"code": null,
"e": 1862,
"s": 1840,
"text": "pip install -U hiplot"
},
{
"code": null,
"e": 2160,
"s": 1862,
"text": "To use external csv file, you even do not have to use Pandas DataFrame. They prepared a native method to run parallel plot directly from csv file as such Experiment.from_csv(). When you need to use DataFrame, use Experiment.from_dataframe() instead. And it is totally fine to use Jupyter Notebook."
},
{
"code": null,
"e": 2251,
"s": 2160,
"text": "import hiplot as hipiris_hiplot = hip.Experiment.from_csv('iris.csv')iris_hiplot.display()"
},
{
"code": null,
"e": 2281,
"s": 2251,
"text": "And here’s what you will see:"
},
{
"code": null,
"e": 2341,
"s": 2281,
"text": "You are going to love HiPlot once you start playing around."
},
{
"code": null,
"e": 2442,
"s": 2341,
"text": "As you already saw in the demo movie above, here are some examples of the uses of interactive chart."
},
{
"code": null,
"e": 2976,
"s": 2442,
"text": "To test the run time to show the parallel plot for larger data, I used Kaggle FIFA 19 complete player dataset. It is a dataset from a video game “FIFA 19”, as the name explains a game of soccer (or you may call football), where you can play as a team manager of a actual soccer team or as an actual soccer player. The dataset contains the all playable characters list with their skill levels (e.g. how good they are at heading, free kick etc.) The number of rows is 18,207 and of columns is 89. The first row is Messi from Argentina."
},
{
"code": null,
"e": 3303,
"s": 2976,
"text": "To do the performance test, I intentionally make the data size 10 times larger. I concatenated the FAFA 19 dataset 10 times, ended up with having 182,070 rows. Usually, visualizing large data set takes time to run and causes huge latency after the chart shows up. Interactivity? Forget and rerun the script! What about HiPlot?"
},
{
"code": null,
"e": 3487,
"s": 3303,
"text": "I ran HiPlot on 182,070 rows x 89 columns dataset without any edits. It took 81 seconds to process and additional 5 mins to display the graph. I think it is short enough for its size."
},
{
"code": null,
"e": 3741,
"s": 3487,
"text": "fifa = pd.read_csv('fifa19_data.csv',index_col='Unnamed: 0')fifa_extended = pd.concat([fifa,fifa,fifa,fifa,fifa,fifa,fifa,fifa,fifa,fifa],axis=0,ignore_index=True,sort=False)fifa_hiplot = hip.Experiment.from_dataframe(fifa_extended)fifa_hiplot.display()"
},
{
"code": null,
"e": 4047,
"s": 3741,
"text": "What is even greater about HiPlot is that data size does not harm its interactivity too much. After selecting the range on axis, it tries to show only the plots belonging to the range. This change re-renders the plot almost within a second, which is surprising quick compared to other visualization tools."
},
{
"code": null,
"e": 4198,
"s": 4047,
"text": "When we want to share the plot with someone else, we may run the code on notebook and copy-and-paste the plot, but it removes the graph interactivity."
},
{
"code": null,
"e": 4341,
"s": 4198,
"text": "HiPlot has its native HTML rendering function Experience.to_html(), which returns HTML file with the plot embedded with just one line of code."
},
{
"code": null,
"e": 4429,
"s": 4341,
"text": "Let me go with the original rows and fewer columns from FIFA 19 dataset for simplicity."
},
{
"code": null,
"e": 4786,
"s": 4429,
"text": "fifa = pd.read_csv('fifa19_data.csv',index_col='Unnamed: 0')fifa_small = fifa[['Age','Nationality','Value','Height', 'Weight', 'Crossing', 'Finishing', 'HeadingAccuracy', 'ShortPassing', 'Volleys', 'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl', 'Acceleration']]fifa_hiplot = hip.Experiment.from_dataframe(fifa_small)fifa_hiplot.display()"
},
{
"code": null,
"e": 4855,
"s": 4786,
"text": "This code will produce a new .html file on your local with the plot."
},
{
"code": null,
"e": 4899,
"s": 4855,
"text": "_ = fifa_hiplot.to_html(\"fifa_hiplot.html\")"
},
{
"code": null,
"e": 4998,
"s": 4899,
"text": "Now you can share the .html file directly with your team members to let them play around the plot."
},
{
"code": null,
"e": 5122,
"s": 4998,
"text": "Since Experience.to_html() returns html code, it’s even just easily connected to web server and deploy the plot externally."
},
{
"code": null,
"e": 5265,
"s": 5122,
"text": "Let me try it with Flask and Heroku. As I explained a lot here, I needed four files pushed to GitHub repository, to be synced with Heroku app."
},
{
"code": null,
"e": 5303,
"s": 5265,
"text": "fifa19_data.csv: FIFA19 dataset file."
},
{
"code": null,
"e": 5362,
"s": 5303,
"text": "hiplot_fifa.py: Python code to run and kick off Flask app."
},
{
"code": null,
"e": 5880,
"s": 5362,
"text": "import hiplot as hipimport pandas as pdfrom flask import Flaskapp = Flask(__name__)@app.route('/')def fifa_experiment(): fifa = pd.read_csv('fifa19_data.csv',index_col='Unnamed: 0') fifa_hiplot = hip.Experiment.from_dataframe(fifa[['Age','Nationality','Value','Height', 'Weight', 'Crossing','Finishing', 'HeadingAccuracy', 'ShortPassing', 'Volleys', 'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl', 'Acceleration']]) return fifa_hiplot.to_html()if __name__ == \"__main__\": app.run()"
},
{
"code": null,
"e": 5962,
"s": 5880,
"text": "requirements.txt: a requirement file for Heroku to install the necessary modules."
},
{
"code": null,
"e": 6019,
"s": 5962,
"text": "gunicorn==19.9.0pandas==0.24.2hiplot==0.1.12Flask==1.1.1"
},
{
"code": null,
"e": 6090,
"s": 6019,
"text": "Procfile: a start-up command for Heroku to run when it starts the app."
},
{
"code": null,
"e": 6120,
"s": 6090,
"text": "web: gunicorn hiplot_fifa:app"
},
{
"code": null,
"e": 6278,
"s": 6120,
"text": "Sync the code files and make a set up on Heroku. Opening the web app gives the following HiPlot graph page, which is globally accessible through domain name."
},
{
"code": null,
"e": 6423,
"s": 6278,
"text": "In this post, I introduced the HiPlot the current best option of parallel plot to start EDA to take a look at the variable interaction overview."
},
{
"code": null,
"e": 6519,
"s": 6423,
"text": "It is easy to run, highly interactive, fast, and with much shareable through HTML file or code."
}
] |
Create charts from Google Sheets using Google Apps Script - GeeksforGeeks | 29 Sep, 2021
Google Apps Script is a cloud-based tool used for automating basic tasks. You can write your code in modern JavaScript. Using Apps Script you can add custom menus, write custom functions and macros for Google sheets, and can publish your web Apps. You can automate tasks in Google Sheets, Google Docs, gmail, etc. For using this, you will need a Google account and Google Chrome installed in your system. It is written in script editor in Google Chrome.
In this article, we will be writing a script to create a chart from the data available in Google Sheet. Here, we will be using Chart.js which is a JavaScript library. We are basically developing a web app by publishing the script .
Web App: The script can be published as web app if it contains the function either doGet(e) or doPost(e) and the function must return HTML Service HtmlOutput object. You will learn how to link HTML file to the script in the steps discussed below.
Procedure for writing code in Script Editor:
Start by creating a new Google Sheet.
Then click the Tools tab in the menu as Tools> Script Editor
A new window will open as shown below:
You can insert your code between the curly braces of the function myFunction block.
Let’s see step by step implementation.
Step 1: Prepare your Google Sheet data. We are having the data of the number of Covid cases in different states in India in lakhs which is as shown below. So, the first step is to prepare your data.
Step 2: Add standard Google Apps Script function doGet(e) to code.gs file. Next step is to go to the tools and select script editor. Save it as ‘Chart’ or any other name.Here we are saving as code.gs . Also create a new HTML file and save it as ‘webappchart.html’ .
Add the below code in code.gs file.
code.gs
function doGet(e) { return HtmlService.createHtmlOutputFromFile('webappchart'); }
The above function is the standard Google Apps Script function which is used to publish/deploy your web app. This function returns an output file that is nothing but your HTML file.
Now let’ understand the relation between HTML file and code.gs file:
HtmlService:
This class is used as a service to return HTML and other text content from a script
createHtmlOutputFromFile(filename):
The above function creates a new HtmlOutput object from a file in the code editor. In our case we have named the file as webappchart.html. So we are using doGet(e) function which returns an HtmlOutput object to our HTML page. Filename should be given in string . The function returns an error if the file is not found.
Step 3: Add the required CDN in your HTML file. Next open your HTML file i.e webappchart.html and we will include the cdn for jQuery and Chartjs which we will be using to make our chart.
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js” integrity=”sha512-lUsN5TEogpe12qeV8NF4cxlJJatTZ12jnx9WXkFXOy7yFbuHwYRTjmctvwbRIuZPhv+lpvy7Cm9o8T9e+9pTrg==” crossorigin=”anonymous” referrerpolicy=”no-referrer”>
Step 4: Create a canvas for the rendering charts. In the next step we complete our html code by adding canvas for displaying our chart inside a div element in the body tag as written below:
HTML
<div style='width:800px height:400px'> <canvas id='barchart' class='chartjs-render-monitor'></canvas></div>
The HTML code is completed over here and now we add the script code.
Step 5: Adding the jQuery Script Code. We initially write the standard jQuery method which is called when the screen is fully loaded with html code and we call getCases() method inside it which we will be defining in the next step.
Javascript
$(document).ready(function(){ getcases(); });
We then define our getCases() function as below:
Javascript
function getCases(){ google.script.run.withSuccessHandler(function(ar){ console.log(ar); var data=[]; var label=[]; ar.forEach(function(item,index){ data.push(item[1]); label.push(item[0]); }); });}
In the above code we are calling the standard function of Google Apps Script.
Syntax:
google.script.run.withSuccessHandler(function(ar)){
}.getCases();
Step 6: Defining function in code.gs file to return data retrieved from Google Sheet. The function getCases which is called over here is defined in the code.gs file as below.Add the below code in code.gs file:
Javascript
function getCases(){ var ss=SpreadsheetApp.getActiveSpreadsheet(); var casesSheet=ss.getSheetByName('Sheet1'); var getLastrow=casesSheet.getLastRow(); return casesSheet.getRange(2,1,getLastrow-1,2).getValues();}
Explanation: In the above code we are setting the active spreadsheet to ss and the sheet which is required i.e., Sheet 1 to casesSheet . Then we are getting the last row and setting it in getLastrow variable. Finally we are returning the values from the range given above i.e., starting from second row and so on. An array containing the values from the whole sheet is returned over here and it will be accessible as ar. We are then iterating over the array and pushing the first item in an array as label[] and the second item in an array as data[]. We then will be using these arrays for creating a chart.
Step 7: Creating the chart. Now the data is prepared and we create a bar chart as below:
Javascript
var ctx=document.getElementById("barchart").getContext('2d'); var barchart=new Chart(ctx, { type: "bar", title:{ display: true, text: "covid cases in different states of India" }, data : { labels: label, datasets: [{ label: 'Covid cases in different states of India', data: data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { legend: {display: false}, title: { display: true, text: "Covid Cases in India" } }})
Explanation: In the above code we are assigning number of cases to data and labels are nothing but names of different states in my case. Then we are setting the background color and the border colors of all the bars in our bar chart.
Step 8: Running the WebApp:
Now let’s see the complete code of the above implementation.
code.gs
function doGet(e) { return HtmlService.createHtmlOutputFromFile('webappchart'); }function getCases(){ var ss=SpreadsheetApp.getActiveSpreadsheet(); var casesSheet=ss.getSheetByName('Sheet1'); var getLastrow=casesSheet.getLastRow(); return casesSheet.getRange(2,1,getLastrow-1,2).getValues();}
index.html
<!DOCTYPE html><html> <head> <base target="_top"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js" integrity="sha512-lUsN5TEogpe12qeV8NF4cxlJJatTZ12jnx9WXkFXOy7yFbuHwYRTjmctvwbRIuZPhv+lpvy7Cm9o8T9e+9pTrg==" crossorigin=" anonymous" referrerpolicy="no-referrer"> </script></head> <body> <div style='width:800px; height:400px;'> <canvas id='barchart' class='chartjs-render-monitor'> </canvas> </div> <script> $(document).ready(function () { getcases(); }); function getcases() { google.script.run .withSuccessHandler(function (ar) { console.log(ar); var data = []; var label = []; ar.forEach(function (item, index) { data.push(item[1]); label.push(item[0]); }); var ctx = document.getElementById( "barchart").getContext("2d"); var barchart = new Chart(ctx, { type: "bar", title: { display: true, text: "covid cases in different states of India", }, data: { labels: label, datasets: [{ label: "Covid cases in different states of India", data: data, backgroundColor: [ "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)", ], borderColor: [ "rgba(255,99,132,1)", "rgba(54, 162, 235, 1)", "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)", "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)", "rgba(255,99,132,1)", "rgba(54, 162, 235, 1)", "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)", "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)", ], borderWidth: 1, }, ], }, options: { legend: { display: false }, title: { display: true, text: "Covid Cases in India", }, }, }); }) .getCases(); } </script></body> </html>
Output:
HTML-Questions
JavaScript-Questions
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
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?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ? | [
{
"code": null,
"e": 24894,
"s": 24866,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 25348,
"s": 24894,
"text": "Google Apps Script is a cloud-based tool used for automating basic tasks. You can write your code in modern JavaScript. Using Apps Script you can add custom menus, write custom functions and macros for Google sheets, and can publish your web Apps. You can automate tasks in Google Sheets, Google Docs, gmail, etc. For using this, you will need a Google account and Google Chrome installed in your system. It is written in script editor in Google Chrome."
},
{
"code": null,
"e": 25580,
"s": 25348,
"text": "In this article, we will be writing a script to create a chart from the data available in Google Sheet. Here, we will be using Chart.js which is a JavaScript library. We are basically developing a web app by publishing the script ."
},
{
"code": null,
"e": 25828,
"s": 25580,
"text": "Web App: The script can be published as web app if it contains the function either doGet(e) or doPost(e) and the function must return HTML Service HtmlOutput object. You will learn how to link HTML file to the script in the steps discussed below. "
},
{
"code": null,
"e": 25873,
"s": 25828,
"text": "Procedure for writing code in Script Editor:"
},
{
"code": null,
"e": 25911,
"s": 25873,
"text": "Start by creating a new Google Sheet."
},
{
"code": null,
"e": 25973,
"s": 25911,
"text": "Then click the Tools tab in the menu as Tools> Script Editor"
},
{
"code": null,
"e": 26012,
"s": 25973,
"text": "A new window will open as shown below:"
},
{
"code": null,
"e": 26096,
"s": 26012,
"text": "You can insert your code between the curly braces of the function myFunction block."
},
{
"code": null,
"e": 26135,
"s": 26096,
"text": "Let’s see step by step implementation."
},
{
"code": null,
"e": 26334,
"s": 26135,
"text": "Step 1: Prepare your Google Sheet data. We are having the data of the number of Covid cases in different states in India in lakhs which is as shown below. So, the first step is to prepare your data."
},
{
"code": null,
"e": 26601,
"s": 26334,
"text": "Step 2: Add standard Google Apps Script function doGet(e) to code.gs file. Next step is to go to the tools and select script editor. Save it as ‘Chart’ or any other name.Here we are saving as code.gs . Also create a new HTML file and save it as ‘webappchart.html’ ."
},
{
"code": null,
"e": 26637,
"s": 26601,
"text": "Add the below code in code.gs file."
},
{
"code": null,
"e": 26645,
"s": 26637,
"text": "code.gs"
},
{
"code": "function doGet(e) { return HtmlService.createHtmlOutputFromFile('webappchart'); }",
"e": 26731,
"s": 26645,
"text": null
},
{
"code": null,
"e": 26913,
"s": 26731,
"text": "The above function is the standard Google Apps Script function which is used to publish/deploy your web app. This function returns an output file that is nothing but your HTML file."
},
{
"code": null,
"e": 26982,
"s": 26913,
"text": "Now let’ understand the relation between HTML file and code.gs file:"
},
{
"code": null,
"e": 26996,
"s": 26982,
"text": "HtmlService: "
},
{
"code": null,
"e": 27080,
"s": 26996,
"text": "This class is used as a service to return HTML and other text content from a script"
},
{
"code": null,
"e": 27116,
"s": 27080,
"text": "createHtmlOutputFromFile(filename):"
},
{
"code": null,
"e": 27435,
"s": 27116,
"text": "The above function creates a new HtmlOutput object from a file in the code editor. In our case we have named the file as webappchart.html. So we are using doGet(e) function which returns an HtmlOutput object to our HTML page. Filename should be given in string . The function returns an error if the file is not found."
},
{
"code": null,
"e": 27622,
"s": 27435,
"text": "Step 3: Add the required CDN in your HTML file. Next open your HTML file i.e webappchart.html and we will include the cdn for jQuery and Chartjs which we will be using to make our chart."
},
{
"code": null,
"e": 27949,
"s": 27622,
"text": "<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js” integrity=”sha512-lUsN5TEogpe12qeV8NF4cxlJJatTZ12jnx9WXkFXOy7yFbuHwYRTjmctvwbRIuZPhv+lpvy7Cm9o8T9e+9pTrg==” crossorigin=”anonymous” referrerpolicy=”no-referrer”>"
},
{
"code": null,
"e": 28139,
"s": 27949,
"text": "Step 4: Create a canvas for the rendering charts. In the next step we complete our html code by adding canvas for displaying our chart inside a div element in the body tag as written below:"
},
{
"code": null,
"e": 28144,
"s": 28139,
"text": "HTML"
},
{
"code": "<div style='width:800px height:400px'> <canvas id='barchart' class='chartjs-render-monitor'></canvas></div>",
"e": 28255,
"s": 28144,
"text": null
},
{
"code": null,
"e": 28325,
"s": 28255,
"text": "The HTML code is completed over here and now we add the script code. "
},
{
"code": null,
"e": 28558,
"s": 28325,
"text": "Step 5: Adding the jQuery Script Code. We initially write the standard jQuery method which is called when the screen is fully loaded with html code and we call getCases() method inside it which we will be defining in the next step. "
},
{
"code": null,
"e": 28569,
"s": 28558,
"text": "Javascript"
},
{
"code": "$(document).ready(function(){ getcases(); });",
"e": 28623,
"s": 28569,
"text": null
},
{
"code": null,
"e": 28672,
"s": 28623,
"text": "We then define our getCases() function as below:"
},
{
"code": null,
"e": 28683,
"s": 28672,
"text": "Javascript"
},
{
"code": "function getCases(){ google.script.run.withSuccessHandler(function(ar){ console.log(ar); var data=[]; var label=[]; ar.forEach(function(item,index){ data.push(item[1]); label.push(item[0]); }); });}",
"e": 28909,
"s": 28683,
"text": null
},
{
"code": null,
"e": 28987,
"s": 28909,
"text": "In the above code we are calling the standard function of Google Apps Script."
},
{
"code": null,
"e": 28995,
"s": 28987,
"text": "Syntax:"
},
{
"code": null,
"e": 29063,
"s": 28995,
"text": " google.script.run.withSuccessHandler(function(ar)){\n}.getCases(); "
},
{
"code": null,
"e": 29273,
"s": 29063,
"text": "Step 6: Defining function in code.gs file to return data retrieved from Google Sheet. The function getCases which is called over here is defined in the code.gs file as below.Add the below code in code.gs file:"
},
{
"code": null,
"e": 29284,
"s": 29273,
"text": "Javascript"
},
{
"code": "function getCases(){ var ss=SpreadsheetApp.getActiveSpreadsheet(); var casesSheet=ss.getSheetByName('Sheet1'); var getLastrow=casesSheet.getLastRow(); return casesSheet.getRange(2,1,getLastrow-1,2).getValues();}",
"e": 29502,
"s": 29284,
"text": null
},
{
"code": null,
"e": 30110,
"s": 29502,
"text": "Explanation: In the above code we are setting the active spreadsheet to ss and the sheet which is required i.e., Sheet 1 to casesSheet . Then we are getting the last row and setting it in getLastrow variable. Finally we are returning the values from the range given above i.e., starting from second row and so on. An array containing the values from the whole sheet is returned over here and it will be accessible as ar. We are then iterating over the array and pushing the first item in an array as label[] and the second item in an array as data[]. We then will be using these arrays for creating a chart."
},
{
"code": null,
"e": 30199,
"s": 30110,
"text": "Step 7: Creating the chart. Now the data is prepared and we create a bar chart as below:"
},
{
"code": null,
"e": 30210,
"s": 30199,
"text": "Javascript"
},
{
"code": "var ctx=document.getElementById(\"barchart\").getContext('2d'); var barchart=new Chart(ctx, { type: \"bar\", title:{ display: true, text: \"covid cases in different states of India\" }, data : { labels: label, datasets: [{ label: 'Covid cases in different states of India', data: data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { legend: {display: false}, title: { display: true, text: \"Covid Cases in India\" } }})",
"e": 31519,
"s": 30210,
"text": null
},
{
"code": null,
"e": 31753,
"s": 31519,
"text": "Explanation: In the above code we are assigning number of cases to data and labels are nothing but names of different states in my case. Then we are setting the background color and the border colors of all the bars in our bar chart."
},
{
"code": null,
"e": 31781,
"s": 31753,
"text": "Step 8: Running the WebApp:"
},
{
"code": null,
"e": 31842,
"s": 31781,
"text": "Now let’s see the complete code of the above implementation."
},
{
"code": null,
"e": 31850,
"s": 31842,
"text": "code.gs"
},
{
"code": "function doGet(e) { return HtmlService.createHtmlOutputFromFile('webappchart'); }function getCases(){ var ss=SpreadsheetApp.getActiveSpreadsheet(); var casesSheet=ss.getSheetByName('Sheet1'); var getLastrow=casesSheet.getLastRow(); return casesSheet.getRange(2,1,getLastrow-1,2).getValues();}",
"e": 32153,
"s": 31850,
"text": null
},
{
"code": null,
"e": 32164,
"s": 32153,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html> <head> <base target=\"_top\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js\" integrity=\"sha512-lUsN5TEogpe12qeV8NF4cxlJJatTZ12jnx9WXkFXOy7yFbuHwYRTjmctvwbRIuZPhv+lpvy7Cm9o8T9e+9pTrg==\" crossorigin=\" anonymous\" referrerpolicy=\"no-referrer\"> </script></head> <body> <div style='width:800px; height:400px;'> <canvas id='barchart' class='chartjs-render-monitor'> </canvas> </div> <script> $(document).ready(function () { getcases(); }); function getcases() { google.script.run .withSuccessHandler(function (ar) { console.log(ar); var data = []; var label = []; ar.forEach(function (item, index) { data.push(item[1]); label.push(item[0]); }); var ctx = document.getElementById( \"barchart\").getContext(\"2d\"); var barchart = new Chart(ctx, { type: \"bar\", title: { display: true, text: \"covid cases in different states of India\", }, data: { labels: label, datasets: [{ label: \"Covid cases in different states of India\", data: data, backgroundColor: [ \"rgba(255, 99, 132, 0.2)\", \"rgba(54, 162, 235, 0.2)\", \"rgba(255, 206, 86, 0.2)\", \"rgba(75, 192, 192, 0.2)\", \"rgba(153, 102, 255, 0.2)\", \"rgba(255, 159, 64, 0.2)\", \"rgba(255, 99, 132, 0.2)\", \"rgba(54, 162, 235, 0.2)\", \"rgba(255, 206, 86, 0.2)\", \"rgba(75, 192, 192, 0.2)\", \"rgba(153, 102, 255, 0.2)\", \"rgba(255, 159, 64, 0.2)\", ], borderColor: [ \"rgba(255,99,132,1)\", \"rgba(54, 162, 235, 1)\", \"rgba(255, 206, 86, 1)\", \"rgba(75, 192, 192, 1)\", \"rgba(153, 102, 255, 1)\", \"rgba(255, 159, 64, 1)\", \"rgba(255,99,132,1)\", \"rgba(54, 162, 235, 1)\", \"rgba(255, 206, 86, 1)\", \"rgba(75, 192, 192, 1)\", \"rgba(153, 102, 255, 1)\", \"rgba(255, 159, 64, 1)\", ], borderWidth: 1, }, ], }, options: { legend: { display: false }, title: { display: true, text: \"Covid Cases in India\", }, }, }); }) .getCases(); } </script></body> </html>",
"e": 35031,
"s": 32164,
"text": null
},
{
"code": null,
"e": 35039,
"s": 35031,
"text": "Output:"
},
{
"code": null,
"e": 35054,
"s": 35039,
"text": "HTML-Questions"
},
{
"code": null,
"e": 35075,
"s": 35054,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 35080,
"s": 35075,
"text": "HTML"
},
{
"code": null,
"e": 35091,
"s": 35080,
"text": "JavaScript"
},
{
"code": null,
"e": 35108,
"s": 35091,
"text": "Web Technologies"
},
{
"code": null,
"e": 35113,
"s": 35108,
"text": "HTML"
},
{
"code": null,
"e": 35211,
"s": 35113,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35235,
"s": 35211,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 35272,
"s": 35235,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 35292,
"s": 35272,
"text": "Angular File Upload"
},
{
"code": null,
"e": 35321,
"s": 35292,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 35349,
"s": 35321,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 35394,
"s": 35349,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35455,
"s": 35394,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35524,
"s": 35455,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 35596,
"s": 35524,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Sort an array of dates in PHP | To sort an array of dates in PHP, the code is as follows−
Live Demo
<?php
function compareDates($date1, $date2){
return strtotime($date1) - strtotime($date2);
}
$dateArr = array("2019-11-11", "2019-10-10","2019-08-10", "2019-09-08");
usort($dateArr, "compareDates");
print_r($dateArr);
?>
This will produce the following output−
Array
(
[0] => 2019-08-10
[1] => 2019-09-08
[2] => 2019-10-10
[3] => 2019-11-11
)
Let us now see another example −
Live Demo
<?php
function compareDates($date1, $date2){
if (strtotime($date1) < strtotime($date2))
return 1;
else if (strtotime($date1) > strtotime($date2))
return -1;
else
return 0;
}
$dateArr = array("2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11", "2019-01-01");
usort($dateArr, "compareDates");
print_r($dateArr);
?>
This will produce the following output−
Array
(
[0] => 2019-11-11
[1] => 2019-11-11
[2] => 2019-10-10
[3] => 2019-09-08
[4] => 2019-05-11
[5] => 2019-01-01
) | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "To sort an array of dates in PHP, the code is as follows−"
},
{
"code": null,
"e": 1131,
"s": 1120,
"text": " Live Demo"
},
{
"code": null,
"e": 1373,
"s": 1131,
"text": "<?php\n function compareDates($date1, $date2){\n return strtotime($date1) - strtotime($date2);\n }\n $dateArr = array(\"2019-11-11\", \"2019-10-10\",\"2019-08-10\", \"2019-09-08\");\n usort($dateArr, \"compareDates\");\n print_r($dateArr);\n?>"
},
{
"code": null,
"e": 1413,
"s": 1373,
"text": "This will produce the following output−"
},
{
"code": null,
"e": 1507,
"s": 1413,
"text": "Array\n(\n [0] => 2019-08-10\n [1] => 2019-09-08\n [2] => 2019-10-10\n [3] => 2019-11-11\n)"
},
{
"code": null,
"e": 1540,
"s": 1507,
"text": "Let us now see another example −"
},
{
"code": null,
"e": 1551,
"s": 1540,
"text": " Live Demo"
},
{
"code": null,
"e": 1940,
"s": 1551,
"text": "<?php\n function compareDates($date1, $date2){\n if (strtotime($date1) < strtotime($date2))\n return 1;\n else if (strtotime($date1) > strtotime($date2))\n return -1;\n else\n return 0;\n }\n $dateArr = array(\"2019-11-11\", \"2019-10-10\",\"2019-11-11\", \"2019-09-08\",\"2019-05-11\", \"2019-01-01\");\n usort($dateArr, \"compareDates\");\n print_r($dateArr);\n?>"
},
{
"code": null,
"e": 1980,
"s": 1940,
"text": "This will produce the following output−"
},
{
"code": null,
"e": 2116,
"s": 1980,
"text": "Array\n(\n [0] => 2019-11-11\n [1] => 2019-11-11\n [2] => 2019-10-10\n [3] => 2019-09-08\n [4] => 2019-05-11\n [5] => 2019-01-01\n)"
}
] |
Music Genre Classification: Transformers vs Recurrent Neural Networks | by Youness Mansar | Towards Data Science | The objective of this post is to implement a music genre classification model by comparing two popular architectures for sequence modeling: Recurrent Neural networks and Transformers.
RNNs are popular for all sorts of 1D sequence processing tasks, they re-use the same weights at each time step and pass information from a time-step to the next by keeping an internal state and using a gating mechanism (LSTM, GRUs ... ). Since they use recurrence, those models can suffer from vanishing/exploding gradients which can make training and learning long-range patterns harder.
Transformers are a relatively newer architecture that can process sequences without using any recurrence or convolution [https://arxiv.org/pdf/1706.03762.pdf]. The transformer layer is mostly point-wise feed-forward operations and self-attention. These types of networks are having some great success in natural language processing, especially when pre-trained on a large amount of unlabeled data [https://arxiv.org/pdf/1810.04805].
We will use the Free Music Archive Dataset https://github.com/mdeff/fma/ and more specifically the large version with 106,574 tracks of 30s, 161 unbalanced genres, which sums to a total of 93 Gb of music data. Each track is labeled with a set of genres that best describe it.
"20": [ "Experimental Pop", "Singer-Songwriter" ], "26": [ "Experimental Pop", "Singer-Songwriter" ], "30": [ "Experimental Pop", "Singer-Songwriter" ], "46": [ "Experimental Pop", "Singer-Songwriter" ], "48": [ "Experimental Pop", "Singer-Songwriter" ], "134": [ "Hip-Hop" ]
Our target in this project is to predict those tags. Since a song can be attached to more than one tag it can be formulated as a multi-label classification problem with 163 targets, one for each class.
Some classes are very frequent like Electronic music for example where exists for 22% of the data but some other classes appear very few times like Salsa where it contributes by 0.01% of the dataset. This creates an extreme imbalance in the training and evaluation, which leads us to use the micro-average area under the precision-recall curve as our metric.
| | Genre | Frequency | Fraction ||----:|:-------------------------|------------:|------------:|| 0 | Experimental | 24912 | 0.233753 || 1 | Electronic | 23866 | 0.223938 || 2 | Avant-Garde | 8693 | 0.0815677 || 3 | Rock | 8038 | 0.0754218 || 4 | Noise | 7268 | 0.0681967 || 5 | Ambient | 7206 | 0.067615 || 6 | Experimental Pop | 7144 | 0.0670332 || 7 | Folk | 7105 | 0.0666673 || 8 | Pop | 6362 | 0.0596956 || 9 | Electroacoustic | 6110 | 0.0573311 || 10 | Instrumental | 6055 | 0.056815 || 11 | Lo-Fi | 6041 | 0.0566836 || 12 | Hip-Hop | 5922 | 0.055567 || 13 | Ambient Electronic | 5723 | 0.0536998 |...| 147 | North African | 40 | 0.000375326 || 148 | Sound Effects | 36 | 0.000337793 || 149 | Tango | 30 | 0.000281495 || 150 | Fado | 26 | 0.000243962 || 151 | Talk Radio | 26 | 0.000243962 || 152 | Symphony | 25 | 0.000234579 || 153 | Pacific | 23 | 0.000215812 || 154 | Musical Theater | 18 | 0.000168897 || 155 | South Indian Traditional | 17 | 0.000159514 || 156 | Salsa | 12 | 0.000112598 || 157 | Banter | 9 | 8.44484e-05 || 158 | Western Swing | 4 | 3.75326e-05 || 159 | N. Indian Traditional | 4 | 3.75326e-05 || 160 | Deep Funk | 1 | 9.38315e-06 |
We use Mel-Spectrograms as input to our networks since its a denser representation of the audio input and it fits the transformer architecture better since it turns the raw audio-waves into a sequence of vectors.
def pre_process_audio_mel_t(audio, sample_rate=16000): mel_spec = librosa.feature.melspectrogram(y=audio, sr=sample_rate, n_mels=n_mels) mel_db = (librosa.power_to_db(mel_spec, ref=np.max) + 40) / 40return mel_db.T
Each 128-D vector on the Time axis is considered an element of the input sequence.
Loading the audio file and sub-sampling it to 16kHz and then computing the Mel-spectrograms can take a significant amount of time, so we pre-compute and save them on disk as a .npy file using NumPy.save.
I choose the hyper-parameters so that both the RNNs and Transformers have a similar number of trainable parameters.
Model: "Transformer"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, None, 128)] 0 _________________________________________________________________encoder (Encoder) (None, None, 128) 529920 _________________________________________________________________dropout_9 (Dropout) (None, None, 128) 0 _________________________________________________________________global_average_pooling1d (Gl (None, 128) 0 _________________________________________________________________dense_24 (Dense) (None, 652) 84108 _________________________________________________________________dense_25 (Dense) (None, 163) 106439 =================================================================Total params: 720,467Trainable params: 720,467Non-trainable params: 0_________________________________________________________________Model: "RNN"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, None, 128)] 0 _________________________________________________________________bidirectional (Bidirectional (None, None, 256) 198144 _________________________________________________________________bidirectional_1 (Bidirection (None, None, 256) 296448 _________________________________________________________________dropout (Dropout) (None, None, 256) 0 _________________________________________________________________global_average_pooling1d (Gl (None, 256) 0 _________________________________________________________________dense (Dense) (None, 652) 167564 _________________________________________________________________dense_1 (Dense) (None, 163) 106439 =================================================================Total params: 768,595Trainable params: 768,595Non-trainable params: 0_________________________________________________________________
The only difference between the two models is the encoder part being either a transformer or bi-directional GRU. The two models have 700k trainable parameters.
We will evaluate each genre using the area under the precision-recall curve and then micro-average across classes.
RNN vs Transformer AUC PR =>transformer micro-average : 0.20rnn micro-average : 0.18
We can see that the transformer works a little better than GRU. We can improve the performance by doing some Test-Time augmentation and averaging the prediction of multiple crops of the input sequence.
Test-Time Augmentation =>transformer micro-average : 0.22rnn micro-average : 0.19
The results overall seem a little weak, it is probably due to the great number of classes that make the task harder or maybe due to the class imbalance. One possible improvement is to ditch the multi-label approach and work on a ranking approach, since its less sensitive to class imbalance and the big number of classes.
Top 5 predictions:
Siesta by Jahzzar
('Folk', 0.7591149806976318)('Pop', 0.7336021065711975)('Indie-Rock', 0.6384000778198242)('Instrumental', 0.5678483843803406)('Singer-Songwriter', 0.558732271194458)
Wise Guy by Yung Kartz
('Electronic', 0.8624182939529419)('Experimental', 0.6041183471679688)('Hip-Hop', 0.369397908449173)('Glitch', 0.31879115104675293)('Techno', 0.30013027787208557)
In this post, we compared two popular architectures for sequence modeling RNNs and Transformers. We saw that transformers slightly over-performs GRUs which shows that Transformers can be a viable option to test even outside Natural Language Processing.
TF2 Transformers : https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/transformer.ipynb
Code : https://github.com/CVxTz/music_genre_classification | [
{
"code": null,
"e": 356,
"s": 172,
"text": "The objective of this post is to implement a music genre classification model by comparing two popular architectures for sequence modeling: Recurrent Neural networks and Transformers."
},
{
"code": null,
"e": 745,
"s": 356,
"text": "RNNs are popular for all sorts of 1D sequence processing tasks, they re-use the same weights at each time step and pass information from a time-step to the next by keeping an internal state and using a gating mechanism (LSTM, GRUs ... ). Since they use recurrence, those models can suffer from vanishing/exploding gradients which can make training and learning long-range patterns harder."
},
{
"code": null,
"e": 1178,
"s": 745,
"text": "Transformers are a relatively newer architecture that can process sequences without using any recurrence or convolution [https://arxiv.org/pdf/1706.03762.pdf]. The transformer layer is mostly point-wise feed-forward operations and self-attention. These types of networks are having some great success in natural language processing, especially when pre-trained on a large amount of unlabeled data [https://arxiv.org/pdf/1810.04805]."
},
{
"code": null,
"e": 1454,
"s": 1178,
"text": "We will use the Free Music Archive Dataset https://github.com/mdeff/fma/ and more specifically the large version with 106,574 tracks of 30s, 161 unbalanced genres, which sums to a total of 93 Gb of music data. Each track is labeled with a set of genres that best describe it."
},
{
"code": null,
"e": 1840,
"s": 1454,
"text": "\"20\": [ \"Experimental Pop\", \"Singer-Songwriter\" ], \"26\": [ \"Experimental Pop\", \"Singer-Songwriter\" ], \"30\": [ \"Experimental Pop\", \"Singer-Songwriter\" ], \"46\": [ \"Experimental Pop\", \"Singer-Songwriter\" ], \"48\": [ \"Experimental Pop\", \"Singer-Songwriter\" ], \"134\": [ \"Hip-Hop\" ]"
},
{
"code": null,
"e": 2042,
"s": 1840,
"text": "Our target in this project is to predict those tags. Since a song can be attached to more than one tag it can be formulated as a multi-label classification problem with 163 targets, one for each class."
},
{
"code": null,
"e": 2401,
"s": 2042,
"text": "Some classes are very frequent like Electronic music for example where exists for 22% of the data but some other classes appear very few times like Salsa where it contributes by 0.01% of the dataset. This creates an extreme imbalance in the training and evaluation, which leads us to use the micro-average area under the precision-recall curve as our metric."
},
{
"code": null,
"e": 4265,
"s": 2401,
"text": "| | Genre | Frequency | Fraction ||----:|:-------------------------|------------:|------------:|| 0 | Experimental | 24912 | 0.233753 || 1 | Electronic | 23866 | 0.223938 || 2 | Avant-Garde | 8693 | 0.0815677 || 3 | Rock | 8038 | 0.0754218 || 4 | Noise | 7268 | 0.0681967 || 5 | Ambient | 7206 | 0.067615 || 6 | Experimental Pop | 7144 | 0.0670332 || 7 | Folk | 7105 | 0.0666673 || 8 | Pop | 6362 | 0.0596956 || 9 | Electroacoustic | 6110 | 0.0573311 || 10 | Instrumental | 6055 | 0.056815 || 11 | Lo-Fi | 6041 | 0.0566836 || 12 | Hip-Hop | 5922 | 0.055567 || 13 | Ambient Electronic | 5723 | 0.0536998 |...| 147 | North African | 40 | 0.000375326 || 148 | Sound Effects | 36 | 0.000337793 || 149 | Tango | 30 | 0.000281495 || 150 | Fado | 26 | 0.000243962 || 151 | Talk Radio | 26 | 0.000243962 || 152 | Symphony | 25 | 0.000234579 || 153 | Pacific | 23 | 0.000215812 || 154 | Musical Theater | 18 | 0.000168897 || 155 | South Indian Traditional | 17 | 0.000159514 || 156 | Salsa | 12 | 0.000112598 || 157 | Banter | 9 | 8.44484e-05 || 158 | Western Swing | 4 | 3.75326e-05 || 159 | N. Indian Traditional | 4 | 3.75326e-05 || 160 | Deep Funk | 1 | 9.38315e-06 |"
},
{
"code": null,
"e": 4478,
"s": 4265,
"text": "We use Mel-Spectrograms as input to our networks since its a denser representation of the audio input and it fits the transformer architecture better since it turns the raw audio-waves into a sequence of vectors."
},
{
"code": null,
"e": 4744,
"s": 4478,
"text": "def pre_process_audio_mel_t(audio, sample_rate=16000): mel_spec = librosa.feature.melspectrogram(y=audio, sr=sample_rate, n_mels=n_mels) mel_db = (librosa.power_to_db(mel_spec, ref=np.max) + 40) / 40return mel_db.T"
},
{
"code": null,
"e": 4827,
"s": 4744,
"text": "Each 128-D vector on the Time axis is considered an element of the input sequence."
},
{
"code": null,
"e": 5031,
"s": 4827,
"text": "Loading the audio file and sub-sampling it to 16kHz and then computing the Mel-spectrograms can take a significant amount of time, so we pre-compute and save them on disk as a .npy file using NumPy.save."
},
{
"code": null,
"e": 5147,
"s": 5031,
"text": "I choose the hyper-parameters so that both the RNNs and Transformers have a similar number of trainable parameters."
},
{
"code": null,
"e": 7528,
"s": 5147,
"text": "Model: \"Transformer\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, None, 128)] 0 _________________________________________________________________encoder (Encoder) (None, None, 128) 529920 _________________________________________________________________dropout_9 (Dropout) (None, None, 128) 0 _________________________________________________________________global_average_pooling1d (Gl (None, 128) 0 _________________________________________________________________dense_24 (Dense) (None, 652) 84108 _________________________________________________________________dense_25 (Dense) (None, 163) 106439 =================================================================Total params: 720,467Trainable params: 720,467Non-trainable params: 0_________________________________________________________________Model: \"RNN\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, None, 128)] 0 _________________________________________________________________bidirectional (Bidirectional (None, None, 256) 198144 _________________________________________________________________bidirectional_1 (Bidirection (None, None, 256) 296448 _________________________________________________________________dropout (Dropout) (None, None, 256) 0 _________________________________________________________________global_average_pooling1d (Gl (None, 256) 0 _________________________________________________________________dense (Dense) (None, 652) 167564 _________________________________________________________________dense_1 (Dense) (None, 163) 106439 =================================================================Total params: 768,595Trainable params: 768,595Non-trainable params: 0_________________________________________________________________"
},
{
"code": null,
"e": 7688,
"s": 7528,
"text": "The only difference between the two models is the encoder part being either a transformer or bi-directional GRU. The two models have 700k trainable parameters."
},
{
"code": null,
"e": 7803,
"s": 7688,
"text": "We will evaluate each genre using the area under the precision-recall curve and then micro-average across classes."
},
{
"code": null,
"e": 7906,
"s": 7803,
"text": "RNN vs Transformer AUC PR =>transformer micro-average : 0.20rnn micro-average : 0.18"
},
{
"code": null,
"e": 8108,
"s": 7906,
"text": "We can see that the transformer works a little better than GRU. We can improve the performance by doing some Test-Time augmentation and averaging the prediction of multiple crops of the input sequence."
},
{
"code": null,
"e": 8208,
"s": 8108,
"text": "Test-Time Augmentation =>transformer micro-average : 0.22rnn micro-average : 0.19"
},
{
"code": null,
"e": 8530,
"s": 8208,
"text": "The results overall seem a little weak, it is probably due to the great number of classes that make the task harder or maybe due to the class imbalance. One possible improvement is to ditch the multi-label approach and work on a ranking approach, since its less sensitive to class imbalance and the big number of classes."
},
{
"code": null,
"e": 8549,
"s": 8530,
"text": "Top 5 predictions:"
},
{
"code": null,
"e": 8567,
"s": 8549,
"text": "Siesta by Jahzzar"
},
{
"code": null,
"e": 8733,
"s": 8567,
"text": "('Folk', 0.7591149806976318)('Pop', 0.7336021065711975)('Indie-Rock', 0.6384000778198242)('Instrumental', 0.5678483843803406)('Singer-Songwriter', 0.558732271194458)"
},
{
"code": null,
"e": 8756,
"s": 8733,
"text": "Wise Guy by Yung Kartz"
},
{
"code": null,
"e": 8919,
"s": 8756,
"text": "('Electronic', 0.8624182939529419)('Experimental', 0.6041183471679688)('Hip-Hop', 0.369397908449173)('Glitch', 0.31879115104675293)('Techno', 0.30013027787208557)"
},
{
"code": null,
"e": 9172,
"s": 8919,
"text": "In this post, we compared two popular architectures for sequence modeling RNNs and Transformers. We saw that transformers slightly over-performs GRUs which shows that Transformers can be a viable option to test even outside Natural Language Processing."
},
{
"code": null,
"e": 9279,
"s": 9172,
"text": "TF2 Transformers : https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/transformer.ipynb"
}
] |
Recursive program to find an element in an array linearly. | Following is a Java program to find an element in an array linearly.
Live Demo
import java.util.Scanner;
public class SearchingRecursively {
public static boolean searchArray(int[] myArray, int element, int size){
if (size == 0){
return false;
}
if (myArray[size-1] == element){
return true;
}
return searchArray(myArray, element, size-1);
}
public static void main(String args[]){
System.out.println("Enter the required size of the array: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
}
System.out.println("Enter the element to be searched: ");
int target = s.nextInt();
boolean bool = searchArray(myArray, target ,size);
if(bool){
System.out.println("Element found");
}else{
System.out.println("Element not found");
}
}
}
Enter the required size of the array:
5
Enter the elements of the array one by one
14
632
88
98
75
Enter the element to be searched:
632
Element found | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "Following is a Java program to find an element in an array linearly."
},
{
"code": null,
"e": 1142,
"s": 1131,
"text": " Live Demo"
},
{
"code": null,
"e": 2122,
"s": 1142,
"text": "import java.util.Scanner;\npublic class SearchingRecursively {\n public static boolean searchArray(int[] myArray, int element, int size){\n if (size == 0){\n return false;\n }\n if (myArray[size-1] == element){\n return true;\n }\n return searchArray(myArray, element, size-1);\n }\n public static void main(String args[]){\n System.out.println(\"Enter the required size of the array: \");\n Scanner s = new Scanner(System.in);\n int size = s.nextInt();\n int myArray[] = new int [size];\n System.out.println(\"Enter the elements of the array one by one \");\n for(int i=0; i<size; i++){\n myArray[i] = s.nextInt();\n }\n System.out.println(\"Enter the element to be searched: \");\n int target = s.nextInt();\n boolean bool = searchArray(myArray, target ,size);\n if(bool){\n System.out.println(\"Element found\");\n }else{\n System.out.println(\"Element not found\");\n }\n }\n}"
},
{
"code": null,
"e": 2273,
"s": 2122,
"text": "Enter the required size of the array:\n5\nEnter the elements of the array one by one\n14\n632\n88\n98\n75\nEnter the element to be searched:\n632\nElement found"
}
] |
MongoDB - Insert Multiple Document Using MongoShell - GeeksforGeeks | 27 Feb, 2020
In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to insert multiple documents in the collection by using db.collection.insertMany() method.
insertMany() is a mongo shell method, which can insert multiple documents. This method can be used in the multi-document transactions. In this method, you can add documents in the collection with or without _id field. If you add documents without _id field, then mongodb will automatically add _id fields for each documents and assign them with a unique ObjectId. This method by default insert documents in order.
Syntax:
db.collection.insertMany(
[ <Document1>, <Document2>, <Document3> ... ],
{
writeConcern: <Document>,
order: <Boolean>
}
)
Parameters:
Document: It represents the array of the documents that will insert in the collection.Optional Parameters:
writeConcern: It is only used when you do not want to use the default write concern,
order: It specifies whether the mongodb instance performs an ordered or unordered insert, the default value of this parameter is true.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: student
In this example, we are inserting multiple documents in the student collection without _id field using db.collection.insertMany() method.
In this example, we are inserting multiple documents in the student collection with _id field using db.collection.insertMany() method.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
OpenCV - Overview
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
Mounting a Volume Inside Docker Container
Getting Started with System Design
How to create a REST API using Java Spring Boot
Basics of API Testing Using Postman
Q-Learning in Python | [
{
"code": null,
"e": 23837,
"s": 23809,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 24228,
"s": 23837,
"text": "In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to insert multiple documents in the collection by using db.collection.insertMany() method."
},
{
"code": null,
"e": 24642,
"s": 24228,
"text": "insertMany() is a mongo shell method, which can insert multiple documents. This method can be used in the multi-document transactions. In this method, you can add documents in the collection with or without _id field. If you add documents without _id field, then mongodb will automatically add _id fields for each documents and assign them with a unique ObjectId. This method by default insert documents in order."
},
{
"code": null,
"e": 24650,
"s": 24642,
"text": "Syntax:"
},
{
"code": null,
"e": 24795,
"s": 24650,
"text": "db.collection.insertMany(\n [ <Document1>, <Document2>, <Document3> ... ],\n {\n writeConcern: <Document>,\n order: <Boolean> \n }\n)"
},
{
"code": null,
"e": 24807,
"s": 24795,
"text": "Parameters:"
},
{
"code": null,
"e": 24914,
"s": 24807,
"text": "Document: It represents the array of the documents that will insert in the collection.Optional Parameters:"
},
{
"code": null,
"e": 24999,
"s": 24914,
"text": "writeConcern: It is only used when you do not want to use the default write concern,"
},
{
"code": null,
"e": 25134,
"s": 24999,
"text": "order: It specifies whether the mongodb instance performs an ordered or unordered insert, the default value of this parameter is true."
},
{
"code": null,
"e": 25366,
"s": 25134,
"text": "Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document."
},
{
"code": null,
"e": 25376,
"s": 25366,
"text": "Examples:"
},
{
"code": null,
"e": 25424,
"s": 25376,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 25468,
"s": 25424,
"text": "Database: GeeksforGeeks\nCollection: student"
},
{
"code": null,
"e": 25606,
"s": 25468,
"text": "In this example, we are inserting multiple documents in the student collection without _id field using db.collection.insertMany() method."
},
{
"code": null,
"e": 25741,
"s": 25606,
"text": "In this example, we are inserting multiple documents in the student collection with _id field using db.collection.insertMany() method."
},
{
"code": null,
"e": 25749,
"s": 25741,
"text": "MongoDB"
},
{
"code": null,
"e": 25775,
"s": 25749,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 25873,
"s": 25775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25882,
"s": 25873,
"text": "Comments"
},
{
"code": null,
"e": 25895,
"s": 25882,
"text": "Old Comments"
},
{
"code": null,
"e": 25939,
"s": 25895,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 25980,
"s": 25939,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 25998,
"s": 25980,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 26025,
"s": 25998,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 26088,
"s": 26025,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 26130,
"s": 26088,
"text": "Mounting a Volume Inside Docker Container"
},
{
"code": null,
"e": 26165,
"s": 26130,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 26213,
"s": 26165,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 26249,
"s": 26213,
"text": "Basics of API Testing Using Postman"
}
] |
Break a list into chunks of size N in Python - GeeksforGeeks | 24 Apr, 2020
Method 1: Using yieldThe yield keyword enables a function to comeback where it left off when it is called again. This is the critical difference from a regular function. A regular function cannot comes back where it left off. The yield keyword helps a function to remember its state. The yield enables a function to suspend and resume while it turns in a value at the time of the suspension of the execution.
my_list = ['geeks', 'for', 'geeks', 'like', 'geeky','nerdy', 'geek', 'love', 'questions','words', 'life'] # Yield successive n-sized# chunks from l.def divide_chunks(l, n): # looping till length l for i in range(0, len(l), n): yield l[i:i + n] # How many elements each# list should haven = 5 x = list(divide_chunks(my_list, n))print (x)
Output:
[['geeks', 'for', 'geeks', 'like', 'geeky'],
['nerdy', 'geek', 'love', 'questions', 'words'],
['life']]
Method 2: Using List comprehensionList comprehension is an elegant way to break a list in one line of code.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # How many elements each# list should haven = 4 # using list comprehensionfinal = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] print (final)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
Alternate Implementation :
l = [1, 2, 3, 4, 5, 6, 7, 8, 9] # How many elements each # list should have n = 4 # using list comprehension x = [l[i:i + n] for i in range(0, len(l), n)] print(x)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
sloanlancegeeksforgeeksorg
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Print lists in Python (4 Different Ways) | [
{
"code": null,
"e": 25008,
"s": 24980,
"text": "\n24 Apr, 2020"
},
{
"code": null,
"e": 25417,
"s": 25008,
"text": "Method 1: Using yieldThe yield keyword enables a function to comeback where it left off when it is called again. This is the critical difference from a regular function. A regular function cannot comes back where it left off. The yield keyword helps a function to remember its state. The yield enables a function to suspend and resume while it turns in a value at the time of the suspension of the execution."
},
{
"code": "my_list = ['geeks', 'for', 'geeks', 'like', 'geeky','nerdy', 'geek', 'love', 'questions','words', 'life'] # Yield successive n-sized# chunks from l.def divide_chunks(l, n): # looping till length l for i in range(0, len(l), n): yield l[i:i + n] # How many elements each# list should haven = 5 x = list(divide_chunks(my_list, n))print (x)",
"e": 25801,
"s": 25417,
"text": null
},
{
"code": null,
"e": 25809,
"s": 25801,
"text": "Output:"
},
{
"code": null,
"e": 25918,
"s": 25809,
"text": "[['geeks', 'for', 'geeks', 'like', 'geeky'], \n ['nerdy', 'geek', 'love', 'questions', 'words'], \n ['life']]\n"
},
{
"code": null,
"e": 26026,
"s": 25918,
"text": "Method 2: Using List comprehensionList comprehension is an elegant way to break a list in one line of code."
},
{
"code": "my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # How many elements each# list should haven = 4 # using list comprehensionfinal = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] print (final)",
"e": 26250,
"s": 26026,
"text": null
},
{
"code": null,
"e": 26258,
"s": 26250,
"text": "Output:"
},
{
"code": null,
"e": 26293,
"s": 26258,
"text": "[[1, 2, 3, 4], [5, 6, 7, 8], [9]]\n"
},
{
"code": null,
"e": 26320,
"s": 26293,
"text": "Alternate Implementation :"
},
{
"code": "l = [1, 2, 3, 4, 5, 6, 7, 8, 9] # How many elements each # list should have n = 4 # using list comprehension x = [l[i:i + n] for i in range(0, len(l), n)] print(x)",
"e": 26489,
"s": 26320,
"text": null
},
{
"code": null,
"e": 26497,
"s": 26489,
"text": "Output:"
},
{
"code": null,
"e": 26532,
"s": 26497,
"text": "[[1, 2, 3, 4], [5, 6, 7, 8], [9]]\n"
},
{
"code": null,
"e": 26559,
"s": 26532,
"text": "sloanlancegeeksforgeeksorg"
},
{
"code": null,
"e": 26580,
"s": 26559,
"text": "Python list-programs"
},
{
"code": null,
"e": 26592,
"s": 26580,
"text": "python-list"
},
{
"code": null,
"e": 26599,
"s": 26592,
"text": "Python"
},
{
"code": null,
"e": 26611,
"s": 26599,
"text": "python-list"
},
{
"code": null,
"e": 26709,
"s": 26611,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26731,
"s": 26709,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26763,
"s": 26731,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26805,
"s": 26763,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26831,
"s": 26805,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26868,
"s": 26831,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26897,
"s": 26868,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26922,
"s": 26897,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26978,
"s": 26922,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27020,
"s": 26978,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
How to create Python dictionary from the value of another dictionary? | You can do this by merging the other dictionary to the first dictionary. In Python 3.5+, you can use the ** operator to unpack a dictionary and combine multiple dictionaries using the following syntax −
a = {'foo': 125}
b = {'bar': "hello"}
c = {**a, **b}
print(c)
This will give the output −
{'foo': 125, 'bar': 'hello'}
This is not supported in older versions. You can however replace it using the following similar syntax −
a = {'foo': 125}
b = {'bar': "hello"}
c = dict(a, **b)
print(c)
This will give the output −
{'foo': 125, 'bar': 'hello'}
Another thing you can do is using copy and update functions to merge the dictionaries.
def merge_dicts(x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modify z with y's keys and values
return z
a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c)
This will give the output −
{'foo': 125, 'bar': 'hello'} | [
{
"code": null,
"e": 1265,
"s": 1062,
"text": "You can do this by merging the other dictionary to the first dictionary. In Python 3.5+, you can use the ** operator to unpack a dictionary and combine multiple dictionaries using the following syntax −"
},
{
"code": null,
"e": 1327,
"s": 1265,
"text": "a = {'foo': 125}\nb = {'bar': \"hello\"}\nc = {**a, **b}\nprint(c)"
},
{
"code": null,
"e": 1355,
"s": 1327,
"text": "This will give the output −"
},
{
"code": null,
"e": 1384,
"s": 1355,
"text": "{'foo': 125, 'bar': 'hello'}"
},
{
"code": null,
"e": 1489,
"s": 1384,
"text": "This is not supported in older versions. You can however replace it using the following similar syntax −"
},
{
"code": null,
"e": 1553,
"s": 1489,
"text": "a = {'foo': 125}\nb = {'bar': \"hello\"}\nc = dict(a, **b)\nprint(c)"
},
{
"code": null,
"e": 1581,
"s": 1553,
"text": "This will give the output −"
},
{
"code": null,
"e": 1610,
"s": 1581,
"text": "{'foo': 125, 'bar': 'hello'}"
},
{
"code": null,
"e": 1698,
"s": 1610,
"text": "Another thing you can do is using copy and update functions to merge the dictionaries. "
},
{
"code": null,
"e": 1902,
"s": 1698,
"text": "def merge_dicts(x, y):\n z = x.copy() # start with x's keys and values\n z.update(y) # modify z with y's keys and values\n return z\na = {'foo': 125}\nb = {'bar': \"hello\"}\nc = merge_dicts(a, b)\nprint(c)"
},
{
"code": null,
"e": 1930,
"s": 1902,
"text": "This will give the output −"
},
{
"code": null,
"e": 1959,
"s": 1930,
"text": "{'foo': 125, 'bar': 'hello'}"
}
] |
How to change the color and font of Android ListView using Kotlin? | This example demonstrates how to change the color and font of Android ListView using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:textColor="@android:color/holo_orange_dark"
android:textSize="24sp"
android:textStyle="italic|bold" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
var operatingSystem: Array<String> = arrayOf("Android", "IPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val listView: ListView = findViewById(R.id.listView)
val adapter = object : ArrayAdapter<String>(this, R.layout.list_item, R.id.textView, operatingSystem) {
}
listView.adapter = adapter
}
}
Step 4 − Create a Layout resource file (list_item.xml) and add the following code −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:textColor="@android:color/holo_orange_dark"
android:textSize="24sp"
android:textStyle="italic|bold" />
</LinearLayout>
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code. | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrates how to change the color and font of Android ListView using Kotlin."
},
{
"code": null,
"e": 1283,
"s": 1155,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1874,
"s": 1348,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n<TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:fontFamily=\"sans-serif-condensed\"\n android:textColor=\"@android:color/holo_orange_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"italic|bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1929,
"s": 1874,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2639,
"s": 1929,
"text": "import android.os.Bundle\nimport android.widget.ArrayAdapter\nimport android.widget.ListView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n var operatingSystem: Array<String> = arrayOf(\"Android\", \"IPhone\", \"WindowsMobile\", \"Blackberry\", \"WebOS\", \"Ubuntu\", \"Windows7\", \"Max OS X\")\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val listView: ListView = findViewById(R.id.listView)\n val adapter = object : ArrayAdapter<String>(this, R.layout.list_item, R.id.textView, operatingSystem) {\n }\n listView.adapter = adapter\n }\n}"
},
{
"code": null,
"e": 2723,
"s": 2639,
"text": "Step 4 − Create a Layout resource file (list_item.xml) and add the following code −"
},
{
"code": null,
"e": 3249,
"s": 2723,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n<TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:fontFamily=\"sans-serif-condensed\"\n android:textColor=\"@android:color/holo_orange_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"italic|bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 3304,
"s": 3249,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3975,
"s": 3304,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4323,
"s": 3975,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
},
{
"code": null,
"e": 4364,
"s": 4323,
"text": "Click here to download the project code."
}
] |
Multimodal deep learning to predict movie genres | by Dhruv Verma | Towards Data Science | “Batman raises the stakes in his war on crime. With the help of Lt. Jim Gordon and District Attorney Harvey Dent, Batman sets out to dismantle the remaining criminal organizations that plague the streets. The partnership proves to be effective, but they soon find themselves prey to a reign of chaos unleashed by a rising criminal mastermind known to the terrified citizens of Gotham as the Joker.” -TMDB
‘The Dark Knight’ — one of my favourite movies. TMDB classifies this movie into four genres — Drama, Action, Crime, Thriller. A multimodal deep learning model I have trained classifies this movie as — Action, Drama, Thriller. Let’s take a look at how this model manages to do this.
Modality is a particular way of doing or experiencing something. We live our daily lives in a multimodal environment. We see things, hear sounds, smell odours and feel textures. Analogous to this, multimodal deep learning involves multiple modalities used together to predict some output. In this project, I concatenated the features extracted from images and text sequences using a Convolutional Neural Network (CNN) and a Long Short-Term Memory (LSTM) network, respectively. These features were used to try and predict movie genres.
For this project, I have used Kaggle’s The Movies Dataset. It consists of over 40,000 movies with overviews, the poster URL link on TMDB and genres taken from the TMDB website. After splitting the dataset, the training set consists of 26864 examples; the test set includes of 7463 samples, and the validation set consists of 2986 cases.
Before preprocessing the data, it was essential to understand how the class distribution of each genre was. Some genres such as “Aniplex”, “BROSTA TV” seem to occur only once in the entire dataset. Hence, I removed those. In addition to this, some genres like “TV Movie” and “Foreign” are not easily perceived by posters and movie summaries. Hence, those were removed as well. The snippet below shows a list of genres which were removed from the dataset.
invalid_genres = ['Aniplex', 'BROSTA TV', 'Carousel Productions', 'GoHands', 'Mardock Scramble Production Committee', 'Odyssey Media', 'Pulser Productions', 'Rogue State', 'Sentai Filmworks', 'Telescene Film Group Productions', 'The Cartel', 'Vision View Entertainment', 'TV Movie', 'Foreign']
I also scanned the dataset for rows which did not have a genre specified anymore. Over 2471 rows did not have any values in the genre_list column. So these rows were dropped.
In addition to this, it was essential to see how balanced the dataset was in terms of genre labels. As clear from the graph below, there is a class imbalance in the dataset.
Data cleaning and preprocessing allow us to remove irrelevant information from the data such as URLs. These familiar words occur very frequently without adding much semantic meaning such as articles in the English language. The text processing involved the following steps:
Removing of all punctuations from the text.Converting the text to lower case, removing non-alphabetic inputs and all NLTK stopwords.Word lemmatization using NLTK. The goal of lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form. For example, ‘Finds’ can be replaced with just ‘Find’.
Removing of all punctuations from the text.
Converting the text to lower case, removing non-alphabetic inputs and all NLTK stopwords.
Word lemmatization using NLTK. The goal of lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form. For example, ‘Finds’ can be replaced with just ‘Find’.
The cleaned text is tokenized using the Keras Tokenizer API. This tokenizer is used to convert all texts to sequences to be input into the LSTM network. All sequences are made of the same length by padding them with zeros. This is done to ensure that all inputs have the same dimensions.
One of the inputs to the model is the movie poster. Hence, I had to download a single poster corresponding to each movie in the dataset. The original dataset contains a URL to the posters stored in TMDB as well. However, the majority of links seem to obsolete, so I had to improvise and make use of the TMDB API. I used python’s tmdbv3api, which wraps around the TMDB API. Using the movie IDs from the original dataset, I found a single poster corresponding to a movie. A point to be noted is that some movies may not have posters available on TMDB.
The ‘Movie’ object allows us to search for movies based on the TMDB ID. The posters are downloaded with a simple GET request and saved to my Google Drive. The path corresponding to a movie poster is saved in a list which is added to the dataset as a column.
In case there are any errors in downloading the posters or the poster_path for a movie does not exist, that movie is dropped from the dataset.
Here is a glimpse of how the final dataset looks.
The final preprocessing step is to resize the posters and append them to a NumPy array. This NumPy array is saved to make it easier to access the posters in a valid input format. This process takes a lot of time, and the output NumPy array is around 2–3 GB. A considerable amount of RAM is needed to save this array. I would recommend using Google colab for this entire process. The code snippet for converting an image to a NumPy array is below. In case any posters are not found at the specified path in the dataset, the respective rows are dropped.
So I have finally preprocessed the text inputs and image inputs. Now, on to training the model.
Each movie is associated with a certain number of genres in the dataset. However, this needs to be made into a one-hot encoded vector where each one would correspond to a genre label. To do this, I used the MultilabelBinarizer class of the scikit-learn library. It results in a sparse matrix where each row vector is one-hot encoded. This means that a row vector will have a 1 in indexes associated with the label it has been classified as and 0 in all other places. Hence, this is a multilabel classification problem. As seen below, there are a total of 18 classes present in the dataset.
The model comprises of two networks — a stacked LSTM and a CNN. The text sequences are input to an embedding layer. I used Google’s pre-trained Word2Vec embedding. However, to fine-tune the model, I allowed the embedding layer to be trainable. The embedding layer is followed by two stacked LSTMs whose outputs are fed into a fully connected layer.
The images are input to a CNN. The CNN consists of consecutive 2D convolutional and max-pooling layers. The output of the last max-pooling layer is flattened and fed into a fully connected layer.
The fully connected layers of the LSTM and CNN then concatenated and fed forward till the final fully connected layer. The last layer has an output size of 18, each correlating to one genre.
DataLoader object was initialized with a batch size of 64, which passes inputs to the model. The TensorDataset object is used to wrap the dataset inputs and labels. Each TensorDataset is then provided to the DataLoader object. This will allow us to send batches of the dataset to the model for training, validation and testing.
The loss I used was binary cross-entropy along with the Adam optimizer. Gradient clipping was also used to prevent exploding gradients. The model was trained for 20 epochs. During the training, I computed the accuracy and loss for every epoch as an average of the accuracy and loss for all batches.
The final epoch had the following accuracy and loss:
Epoch 20: train_loss: 0.1340 train_acc: 0.9200 | val_loss: 0.3431 val_acc: 0.8726
After training and saving the model, I evaluated the accuracy and loss on the test set:
acc: 0.8737 loss: 0.3406
The accuracy and loss seem to show that the model is performing reasonably well. However, some better evaluation metrics would be precision, recall, F1 score and the Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) score due to a class imbalance in the dataset. The output consisting of un-thresholded probabilities of a movie belonging to a genre is converted to a sparse matrix with one-hot encoded row vectors to compute precision, recall and F1 score. This was done using an arbitrary threshold value of 0.5. This value can be further improved by using Matthew’s correlation coefficient. It can also be enhanced by plotting the ROC curve for each class.
Precision on test set: 0.5732Recall on test set: 0.5210F1 score on test set: 0.5080
The ROC AUC score was calculated using the non-thresholded outputs of the model.
roc auc macro score: 0.8021
Another evaluation metric used was the Hamming Loss. The Hamming loss gives a fraction of wrong labels to the total numbers of labels.
Hamming loss on the test set: 0.1078
As evident from the evaluation metrics above, the model seems to be performing well on the test set. The precision, recall and f1-score can probably be boosted further by taking an optimized threshold value for each label rather than an arbitrary value of 0.5. Another way of improving the model would be to evaluate the CNN and LSTM individually to judge the scope of improvement for both.
This project explores a multimodal deep learning approach to tackle a multilabel classification problem of predicting movie genres from movie posters and overviews.The model accuracy and loss on the test set were good. However, there are better-suited evaluation metrics for this problem — precision, recall, f1 score and the ROC AUC score.Such a model might be able to distinguish between the features of a comedy movie’s poster and overview from a horror movie’s poster and summary.
This project explores a multimodal deep learning approach to tackle a multilabel classification problem of predicting movie genres from movie posters and overviews.
The model accuracy and loss on the test set were good. However, there are better-suited evaluation metrics for this problem — precision, recall, f1 score and the ROC AUC score.
Such a model might be able to distinguish between the features of a comedy movie’s poster and overview from a horror movie’s poster and summary.
Thanks for reading this article! The entire code for this project can is at https://github.com/dh1105/Multi-modal-movie-genre-prediction. | [
{
"code": null,
"e": 577,
"s": 172,
"text": "“Batman raises the stakes in his war on crime. With the help of Lt. Jim Gordon and District Attorney Harvey Dent, Batman sets out to dismantle the remaining criminal organizations that plague the streets. The partnership proves to be effective, but they soon find themselves prey to a reign of chaos unleashed by a rising criminal mastermind known to the terrified citizens of Gotham as the Joker.” -TMDB"
},
{
"code": null,
"e": 859,
"s": 577,
"text": "‘The Dark Knight’ — one of my favourite movies. TMDB classifies this movie into four genres — Drama, Action, Crime, Thriller. A multimodal deep learning model I have trained classifies this movie as — Action, Drama, Thriller. Let’s take a look at how this model manages to do this."
},
{
"code": null,
"e": 1394,
"s": 859,
"text": "Modality is a particular way of doing or experiencing something. We live our daily lives in a multimodal environment. We see things, hear sounds, smell odours and feel textures. Analogous to this, multimodal deep learning involves multiple modalities used together to predict some output. In this project, I concatenated the features extracted from images and text sequences using a Convolutional Neural Network (CNN) and a Long Short-Term Memory (LSTM) network, respectively. These features were used to try and predict movie genres."
},
{
"code": null,
"e": 1731,
"s": 1394,
"text": "For this project, I have used Kaggle’s The Movies Dataset. It consists of over 40,000 movies with overviews, the poster URL link on TMDB and genres taken from the TMDB website. After splitting the dataset, the training set consists of 26864 examples; the test set includes of 7463 samples, and the validation set consists of 2986 cases."
},
{
"code": null,
"e": 2186,
"s": 1731,
"text": "Before preprocessing the data, it was essential to understand how the class distribution of each genre was. Some genres such as “Aniplex”, “BROSTA TV” seem to occur only once in the entire dataset. Hence, I removed those. In addition to this, some genres like “TV Movie” and “Foreign” are not easily perceived by posters and movie summaries. Hence, those were removed as well. The snippet below shows a list of genres which were removed from the dataset."
},
{
"code": null,
"e": 2480,
"s": 2186,
"text": "invalid_genres = ['Aniplex', 'BROSTA TV', 'Carousel Productions', 'GoHands', 'Mardock Scramble Production Committee', 'Odyssey Media', 'Pulser Productions', 'Rogue State', 'Sentai Filmworks', 'Telescene Film Group Productions', 'The Cartel', 'Vision View Entertainment', 'TV Movie', 'Foreign']"
},
{
"code": null,
"e": 2655,
"s": 2480,
"text": "I also scanned the dataset for rows which did not have a genre specified anymore. Over 2471 rows did not have any values in the genre_list column. So these rows were dropped."
},
{
"code": null,
"e": 2829,
"s": 2655,
"text": "In addition to this, it was essential to see how balanced the dataset was in terms of genre labels. As clear from the graph below, there is a class imbalance in the dataset."
},
{
"code": null,
"e": 3103,
"s": 2829,
"text": "Data cleaning and preprocessing allow us to remove irrelevant information from the data such as URLs. These familiar words occur very frequently without adding much semantic meaning such as articles in the English language. The text processing involved the following steps:"
},
{
"code": null,
"e": 3455,
"s": 3103,
"text": "Removing of all punctuations from the text.Converting the text to lower case, removing non-alphabetic inputs and all NLTK stopwords.Word lemmatization using NLTK. The goal of lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form. For example, ‘Finds’ can be replaced with just ‘Find’."
},
{
"code": null,
"e": 3499,
"s": 3455,
"text": "Removing of all punctuations from the text."
},
{
"code": null,
"e": 3589,
"s": 3499,
"text": "Converting the text to lower case, removing non-alphabetic inputs and all NLTK stopwords."
},
{
"code": null,
"e": 3809,
"s": 3589,
"text": "Word lemmatization using NLTK. The goal of lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form. For example, ‘Finds’ can be replaced with just ‘Find’."
},
{
"code": null,
"e": 4097,
"s": 3809,
"text": "The cleaned text is tokenized using the Keras Tokenizer API. This tokenizer is used to convert all texts to sequences to be input into the LSTM network. All sequences are made of the same length by padding them with zeros. This is done to ensure that all inputs have the same dimensions."
},
{
"code": null,
"e": 4647,
"s": 4097,
"text": "One of the inputs to the model is the movie poster. Hence, I had to download a single poster corresponding to each movie in the dataset. The original dataset contains a URL to the posters stored in TMDB as well. However, the majority of links seem to obsolete, so I had to improvise and make use of the TMDB API. I used python’s tmdbv3api, which wraps around the TMDB API. Using the movie IDs from the original dataset, I found a single poster corresponding to a movie. A point to be noted is that some movies may not have posters available on TMDB."
},
{
"code": null,
"e": 4905,
"s": 4647,
"text": "The ‘Movie’ object allows us to search for movies based on the TMDB ID. The posters are downloaded with a simple GET request and saved to my Google Drive. The path corresponding to a movie poster is saved in a list which is added to the dataset as a column."
},
{
"code": null,
"e": 5048,
"s": 4905,
"text": "In case there are any errors in downloading the posters or the poster_path for a movie does not exist, that movie is dropped from the dataset."
},
{
"code": null,
"e": 5098,
"s": 5048,
"text": "Here is a glimpse of how the final dataset looks."
},
{
"code": null,
"e": 5650,
"s": 5098,
"text": "The final preprocessing step is to resize the posters and append them to a NumPy array. This NumPy array is saved to make it easier to access the posters in a valid input format. This process takes a lot of time, and the output NumPy array is around 2–3 GB. A considerable amount of RAM is needed to save this array. I would recommend using Google colab for this entire process. The code snippet for converting an image to a NumPy array is below. In case any posters are not found at the specified path in the dataset, the respective rows are dropped."
},
{
"code": null,
"e": 5746,
"s": 5650,
"text": "So I have finally preprocessed the text inputs and image inputs. Now, on to training the model."
},
{
"code": null,
"e": 6336,
"s": 5746,
"text": "Each movie is associated with a certain number of genres in the dataset. However, this needs to be made into a one-hot encoded vector where each one would correspond to a genre label. To do this, I used the MultilabelBinarizer class of the scikit-learn library. It results in a sparse matrix where each row vector is one-hot encoded. This means that a row vector will have a 1 in indexes associated with the label it has been classified as and 0 in all other places. Hence, this is a multilabel classification problem. As seen below, there are a total of 18 classes present in the dataset."
},
{
"code": null,
"e": 6685,
"s": 6336,
"text": "The model comprises of two networks — a stacked LSTM and a CNN. The text sequences are input to an embedding layer. I used Google’s pre-trained Word2Vec embedding. However, to fine-tune the model, I allowed the embedding layer to be trainable. The embedding layer is followed by two stacked LSTMs whose outputs are fed into a fully connected layer."
},
{
"code": null,
"e": 6881,
"s": 6685,
"text": "The images are input to a CNN. The CNN consists of consecutive 2D convolutional and max-pooling layers. The output of the last max-pooling layer is flattened and fed into a fully connected layer."
},
{
"code": null,
"e": 7072,
"s": 6881,
"text": "The fully connected layers of the LSTM and CNN then concatenated and fed forward till the final fully connected layer. The last layer has an output size of 18, each correlating to one genre."
},
{
"code": null,
"e": 7400,
"s": 7072,
"text": "DataLoader object was initialized with a batch size of 64, which passes inputs to the model. The TensorDataset object is used to wrap the dataset inputs and labels. Each TensorDataset is then provided to the DataLoader object. This will allow us to send batches of the dataset to the model for training, validation and testing."
},
{
"code": null,
"e": 7699,
"s": 7400,
"text": "The loss I used was binary cross-entropy along with the Adam optimizer. Gradient clipping was also used to prevent exploding gradients. The model was trained for 20 epochs. During the training, I computed the accuracy and loss for every epoch as an average of the accuracy and loss for all batches."
},
{
"code": null,
"e": 7752,
"s": 7699,
"text": "The final epoch had the following accuracy and loss:"
},
{
"code": null,
"e": 7834,
"s": 7752,
"text": "Epoch 20: train_loss: 0.1340 train_acc: 0.9200 | val_loss: 0.3431 val_acc: 0.8726"
},
{
"code": null,
"e": 7922,
"s": 7834,
"text": "After training and saving the model, I evaluated the accuracy and loss on the test set:"
},
{
"code": null,
"e": 7947,
"s": 7922,
"text": "acc: 0.8737 loss: 0.3406"
},
{
"code": null,
"e": 8629,
"s": 7947,
"text": "The accuracy and loss seem to show that the model is performing reasonably well. However, some better evaluation metrics would be precision, recall, F1 score and the Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) score due to a class imbalance in the dataset. The output consisting of un-thresholded probabilities of a movie belonging to a genre is converted to a sparse matrix with one-hot encoded row vectors to compute precision, recall and F1 score. This was done using an arbitrary threshold value of 0.5. This value can be further improved by using Matthew’s correlation coefficient. It can also be enhanced by plotting the ROC curve for each class."
},
{
"code": null,
"e": 8713,
"s": 8629,
"text": "Precision on test set: 0.5732Recall on test set: 0.5210F1 score on test set: 0.5080"
},
{
"code": null,
"e": 8794,
"s": 8713,
"text": "The ROC AUC score was calculated using the non-thresholded outputs of the model."
},
{
"code": null,
"e": 8822,
"s": 8794,
"text": "roc auc macro score: 0.8021"
},
{
"code": null,
"e": 8957,
"s": 8822,
"text": "Another evaluation metric used was the Hamming Loss. The Hamming loss gives a fraction of wrong labels to the total numbers of labels."
},
{
"code": null,
"e": 8994,
"s": 8957,
"text": "Hamming loss on the test set: 0.1078"
},
{
"code": null,
"e": 9385,
"s": 8994,
"text": "As evident from the evaluation metrics above, the model seems to be performing well on the test set. The precision, recall and f1-score can probably be boosted further by taking an optimized threshold value for each label rather than an arbitrary value of 0.5. Another way of improving the model would be to evaluate the CNN and LSTM individually to judge the scope of improvement for both."
},
{
"code": null,
"e": 9870,
"s": 9385,
"text": "This project explores a multimodal deep learning approach to tackle a multilabel classification problem of predicting movie genres from movie posters and overviews.The model accuracy and loss on the test set were good. However, there are better-suited evaluation metrics for this problem — precision, recall, f1 score and the ROC AUC score.Such a model might be able to distinguish between the features of a comedy movie’s poster and overview from a horror movie’s poster and summary."
},
{
"code": null,
"e": 10035,
"s": 9870,
"text": "This project explores a multimodal deep learning approach to tackle a multilabel classification problem of predicting movie genres from movie posters and overviews."
},
{
"code": null,
"e": 10212,
"s": 10035,
"text": "The model accuracy and loss on the test set were good. However, there are better-suited evaluation metrics for this problem — precision, recall, f1 score and the ROC AUC score."
},
{
"code": null,
"e": 10357,
"s": 10212,
"text": "Such a model might be able to distinguish between the features of a comedy movie’s poster and overview from a horror movie’s poster and summary."
}
] |
Subsets and Splits